问题描述
我正在尝试更新 ModelForm 的某些字段,这些字段不是固定的.(我只有由视图自动填充的 tutor
)
I'm trying to update certain fields a ModelForm, these fields are not fixed. (I have only tutor
that is autopopulated by the view)
型号:
class Session(models.Model):
tutor = models.ForeignKey(User)
start_time = models.DateTimeField()
end_time = models.DateTimeField()
status = models.CharField(max_length=1)
表格:
class SessionForm(forms.ModelForm):
class Meta:
model = Session
exclude = ['tutor']
对于给定的会话,有时我只需要更新 end_time
,有时只需要更新 start_time
&end_time
.
For a given session sometimes I need to update only end_time
, sometimes only start_time
& end_time
.
我怎样才能在视图中做到这一点?
How can I do that in a view ?
编辑
我已经给出了示例但不限于这些示例,我需要更新的字段不是预定义的,我需要能够更新任何字段
I have given examples but it's not limited to these examples, the fields I need to update are not predefined, I need to be able to update any field(s)
推荐答案
我以前也做过类似的事情,虽然不是很漂亮,但非常有效.它涉及在运行时动态创建一个类型,并使用该类型.对于一些文档,您可以查看 DynamicModels for django.
I've had to do something similar before, and while it isn't exactly pretty, it is quite effective. It involves dynamically creating a type at runtime, and using that type. For some documentation, you can see DynamicModels for django.
我们开始……您的要求.
Here we go.. your requirements.
- 您希望能够使用表单更新模型
- 您希望有选择地指定要在运行时更新的字段
所以,一些代码:
def create_form(model, field_names):
# the inner class is the only useful bit of your ModelForm
class Meta:
pass
setattr(Meta, 'model', model)
setattr(Meta, 'include', field_names)
attrs = {'Meta': Meta}
name = 'DynamicForm'
baseclasses = (forms.ModelForm,)
form = type('DynamicForm', baseclasses, attrs)
return form
def my_awesome_view(request):
fields = ['start_time', 'end_time']
form = create_form(Session, fields)
# work with your form!
这篇关于Django - ModelForm 动态字段更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!