所以我有一个模特:
class MyThing(models.Model):
my_field = OneToOneField(SomeOtherModel)
... other fields
表格:
class MyThingForm(forms.ModelForm):
class Meta:
model = MyThing
观点:
class MyThingView(views.TemplateView):
template_name = 'thing.html'
def get(self, request, *args, **kwargs):
form = MyThingForm()
return render(self.template_name, {'form': form})
def post(self, request, *args, **kwargs):
... retrieve some_instance
request.POST['my_field'] = some_instance
form = MyThingForm(request.POST)
if form.is_valid():
form.save()
return HttpResponseRedirect(...somewhere else)
return render(self.template_name, {'form': form})
my thing.html模板:
{% for field in form %}
{{ field }}
{% endfor %}
我的问题是:
所以基本的问题是:如何创建一个隐藏但可保存的必填字段?
答案 0 :(得分:5)
通常用例查看this doc。
总之,您可以从表单中排除该字段,并在从某处检索后保存该字段。
将代码更新为
class MyThingForm(forms.ModelForm):
class Meta:
model = MyThing
exclude = ['my_field', ]
class MyThingView(views.TemplateView):
...
def post(self, request, *args, **kwargs):
form = MyThingForm(request.POST)
#retrieved_my_field = retrieve the field
if form.is_valid():
inst = form.save(commit=False)
inst.my_field = retrieved_my_field
inst.save()
return HttpResponseRedirect(...somewhere else)
return render(self.template_name, {'form': form})