[英](Django) (Foreign Key Issues) model.person_id May not be NULL
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. 我知道这似乎是Django界的一个过于质疑的问题,但我不敢说我还没有找到解决方案。
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. 我已经尝试覆盖管理定义中的save_model()并覆盖表单中的save()但似乎没有任何效果。
If you were to auto add data into a ForeignKey or OneToOneField column to a Model how would you do it? 如果您要将数据自动添加到ForeignKey或OneToOneField列中,您将如何执行此操作?
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. 这与Ignacio所说的非常相似,只有commit = False才是保存实例而不抛出异常的关键语句。 Thanks all who helped!! 谢谢所有帮助过的人!!
Cheers 干杯
In your PersonalForm, you can subclass your save() function, so the appropriate data is added, something like this: 在PersonalForm中,您可以继承save()函数,因此添加了适当的数据,如下所示:
class PersonalForm(ModelForm):
def save(self, *args, **kwargs):
self.person = request.user
super(PersonalForm, self).save(*args, **kwargs)
class Meta:
model = Personal
see this 看到这个
parent = models.ForeignKey('self', blank=True, null=True, verbose_name=_("parent"))
this ok but have problem with sqlite , change it to postgresql its ok. 这个没问题,但有sqlite的问题,将其更改为postgresql它确定。 ( its for my code , change it to your status ) (它代表我的代码,将其更改为您的状态)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.