(Django的)(外国关键问题)model.person_id不能为null [英] (Django) (Foreign Key Issues) model.person_id May not be NULL
问题描述
我知道这似乎是在Django的圆圈过问的问题,但我不敢说,我还没有找到解决这个。
我的模型 -
从djago ....导入用户
类InfoPersonal(models.Model):
...
人= models.OneToOneField(用户)
我试过重写save_model()的管理员定义,以及覆盖保存()的形式,但似乎没有任何工作。
如果您要自动将数据添加到一个ForeignKey的或OneToOneField列模型,你会怎么做呢?
高清profile_creation_personal(要求):
如果request.method =='POST':#如果表单已经提交...
形式= PersonalForm(request.POST)#绑定到POST数据的表单
#form.person = request.user
如果form.is_valid():#所有验证规则传递
#过程中form.cleaned_data数据
#...
form.save()
POST后返回的Htt presponseRedirect('/完成)#重定向
其他:
形成= PersonalForm()#绑定表单
返回render_to_response(信息/个人/ profile_create.html',{形式:形式,})
类PersonalForm(的ModelForm):
#hometown_id = ModelChoiceField(查询集= InfoReferenceCities.objects.all(),empty_label =无)
高清保存(个体经营,* ARGS,** kwargs):
self.person = request.user
超(PersonalForm,个体经营).save(* ARGS,** kwargs)
类元:
模型= InfoPersonal
排除=('人',)
小部件= {'出生日期':SelectDateWidget()}
我得到了答案!我感觉很好!
个人= form.save(提交= FALSE)
personal.person = request.user
personal.save()
这进入视图很像伊格纳西奥说,只有犯=假是一个关键的语句是为了救一个实例未抛出异常。感谢所有谁帮助!结果
干杯
I know this seems to be an over-asked question in the Django circles but I'm afraid to say that i've not yet found the solution to this.
My Model -
from djago.... import User
class InfoPersonal(models.Model):
...
person = models.OneToOneField(User)
I've tried overriding the save_model() in the admin definition and also overriding the save() in the Form but nothing seems to work.
If you were to auto add data into a ForeignKey or OneToOneField column to a Model how would you do it?
def profile_creation_personal(request):
if request.method == 'POST': # If the form has been submitted...
form = PersonalForm(request.POST) # A form bound to the POST data
# form.person = request.user
if form.is_valid(): # All validation rules pass
# Process the data in form.cleaned_data
# ...
form.save()
return HttpResponseRedirect('/done') # Redirect after POST
else:
form = PersonalForm() # An unbound form
return render_to_response('info/personal/profile_create.html', { 'form': form,})
class PersonalForm(ModelForm):
#hometown_id = ModelChoiceField(queryset=InfoReferenceCities.objects.all(),empty_label=None)
def save(self, *args, **kwargs):
self.person = request.user
super(PersonalForm, self).save(*args, **kwargs)
class Meta:
model = InfoPersonal
exclude = ('person',)
widgets = {'dateofbirth' : SelectDateWidget()}
I got the answer!!! I feel good!
personal = form.save(commit = False)
personal.person = request.user
personal.save()
This goes into the view much like Ignacio said, only commit = False being a critical statement for it to save an instance without throwing an exception. Thanks all who helped!!
Cheers
这篇关于(Django的)(外国关键问题)model.person_id不能为null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!