问题描述
我正在尝试更新某些字段的ModelForm,这些字段不是固定的。 (我只有导师
,由视图自动填充)
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)
Form:
class SessionForm(forms.ModelForm):
class Meta:
model = Session
exclude = ['tutor']
对于给定的会话,有时我需要仅更新 end_time
,有时只有 start_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)
推荐答案
不得不做类似的事情,虽然它不是很漂亮,它是非常有效的。它涉及在运行时动态创建类型,并使用该类型。对于某些文档,您可以查看
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动态字段更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!