python – Django CreateView:将ForeignKey附加到CustomForm数据
作者:互联网
我有一个CreateView如下:
class ResumeCreateView(CreateView):
model = Resume
def form_valid(self, request, form):
candidate = Candidate.objects.get(user=self.request.user)
self.object = form.save(commit=False)
self.object.candidate = candidate
self.object.save()
f = self.request.FILES.get('file')
data = [{
'title': self.request['title'],
'name': f.name,
}]
response = JSONResponse(data, {}, response_mimetype(self.request))
response['Content-Disposition'] = 'inline; filename=files.json'
return response
在这里,我试图将候选实例附加到Resume模型候选字段,该字段是Candidate模型的ForeignKey.
但我总是收到验证错误{‘候选人’:’这个字段是必需的’}
>我使用自定义表单而不是模型表单,因为它使用twitter引导标识符.
我错过了什么?
解决方法:
您必须使用候选作为排除字段定义modelForm,然后在form_valid()方法中设置它.
class ResumeForm(forms.ModelForm):
class Meta:
model = Resume
exclude = ('candidate',)
class ResumeCreateView(CreateView):
form_class = ResumeForm
model = Resume
def form_valid(self, form):
form.instance.candidate = Candidate.objects.get(user=self.request.user)
....
更详细的参考资料:Models and request.user
标签:python,django,foreign-keys,form-data,create-view 来源: https://codeday.me/bug/20190714/1455259.html