(Django) (外键问题) model.person_id 不能为 NULL

发布于 2024-10-21 17:57:45 字数 1328 浏览 4 评论 0原文

我知道这在 Django 圈子里似乎是一个被过度询问的问题,但我不敢说我​​还没有找到解决方案。

我的模型 -

from djago.... import User
class InfoPersonal(models.Model):
...
person = models.OneToOneField(User)

我尝试覆盖管理定义中的 save_model() 并覆盖表单中的 save() 但似乎没有任何效果。

如果您要自动将数据添加到模型的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 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()} 

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

囍笑 2024-10-28 17:57:45

我得到了答案!!!我感觉很好!

personal = form.save(commit = False)
personal.person = request.user
personal.save()

这就像 Ignacio 所说的那样,只有 commit = False 才是保存实例而不引发异常的关键语句。感谢所有提供帮助的人!!
干杯

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

何必那么矫情 2024-10-28 17:57:45

在 PersonalForm 中,您可以子类化 save() 函数,以便添加适当的数据,如下所示:

class PersonalForm(ModelForm):
    def save(self, *args, **kwargs):
        self.person = request.user
        super(PersonalForm, self).save(*args, **kwargs)

    class Meta:
        model = Personal

In your PersonalForm, you can subclass your save() function, so the appropriate data is added, something like this:

class PersonalForm(ModelForm):
    def save(self, *args, **kwargs):
        self.person = request.user
        super(PersonalForm, self).save(*args, **kwargs)

    class Meta:
        model = Personal
黑色毁心梦 2024-10-28 17:57:45

看到这个

parent = models.ForeignKey('self', blank=True, null=True, verbose_name=_("parent"))

没问题,但是 sqlite 有问题,将其更改为 postgresql 就可以了。 (这是我的代码,将其更改为您的状态)

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. ( its for my code , change it to your status )

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文