在视图中保存时设置 user_id - Django

发布于 2024-12-22 20:41:35 字数 1811 浏览 0 评论 0原文

我需要设置在添加视图中创建帖子的用户:

@login_required 
def add(request):
    if request.method == 'POST':
        form = BusinessForm(request.POST)
        form.user_id = request.user.id
        if form.is_valid():
            form.save()
            return HttpResponseRedirect(reverse('listing.views.detail'), args=(f.id))
    else:
        form = BusinessForm()
    return render_to_response('business/add.html', {'form':form},
        context_instance=RequestContext(request))

我分配了用户 id form.user_id = request.user.id 但在保存时,它仍然给我一个错误 列 user_id 不能为空

我做错了什么吗?谢谢

编辑:

我将用户从模型中的表单中排除:

class BusinessForm(ModelForm):
    class Meta:
        model = Business
        exclude = ('user',)

这会导致问题吗?我该如何解决这个问题?

编辑 2:

按照建议编辑了我的 BusinessForm() 类,但不起作用:

class BusinessForm(ModelForm):
    class Meta:
        model = Business
        exclude = ('user',)
    def __init__(self, *args, **kwargs):
        self.request = kwargs.pop('request', None)
        return super(BusinessForm, self).__init__(*args, **kwargs)

    def save(self, *args, **kwargs):
        kwargs['commit']=False
        obj = super(BusinessForm, self).save(*args, **kwargs)
        if self.request:
            obj.user = self.request.user
        obj.save()

业务模型

class Business(models.Model):
    name = models.CharField(max_length=200)
    user = models.ForeignKey(User, unique=False)
    description = models.TextField()
    category = models.ForeignKey(Category)
    address = models.CharField(max_length=200)
    phone_number = models.CharField(max_length=10)
    website = models.URLField()
    image = models.ImageField(upload_to='business_pictures',blank=True)

I need to set the user that is creating the post in the add view:

@login_required 
def add(request):
    if request.method == 'POST':
        form = BusinessForm(request.POST)
        form.user_id = request.user.id
        if form.is_valid():
            form.save()
            return HttpResponseRedirect(reverse('listing.views.detail'), args=(f.id))
    else:
        form = BusinessForm()
    return render_to_response('business/add.html', {'form':form},
        context_instance=RequestContext(request))

I assign the user id form.user_id = request.user.id but when saving, it still gives me an error Column user_id cannot be null

Am I doing something wrong? Thanks

EDIT:

I am excluding the user from the form in the model:

class BusinessForm(ModelForm):
    class Meta:
        model = Business
        exclude = ('user',)

Could that be causing the problem?? How can I work around this?

EDIT 2:

Edited my BusinessForm() class as suggested but did not work:

class BusinessForm(ModelForm):
    class Meta:
        model = Business
        exclude = ('user',)
    def __init__(self, *args, **kwargs):
        self.request = kwargs.pop('request', None)
        return super(BusinessForm, self).__init__(*args, **kwargs)

    def save(self, *args, **kwargs):
        kwargs['commit']=False
        obj = super(BusinessForm, self).save(*args, **kwargs)
        if self.request:
            obj.user = self.request.user
        obj.save()

Business model

class Business(models.Model):
    name = models.CharField(max_length=200)
    user = models.ForeignKey(User, unique=False)
    description = models.TextField()
    category = models.ForeignKey(Category)
    address = models.CharField(max_length=200)
    phone_number = models.CharField(max_length=10)
    website = models.URLField()
    image = models.ImageField(upload_to='business_pictures',blank=True)

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

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

发布评论

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

评论(2

萌吟 2024-12-29 20:41:35

您不必为此使用 initsave 覆盖。

您只需在表单上设置一个属性,表单不会对其执行任何操作。它的行为并不神奇地像模型实例(您的表单没有 user_id 属性)。

由于您的表单是 ModelForm,因此您只需使用 commit=False 获取未保存的实例,设置用户,然后在实例上调用 save

 if request.method == 'POST':
    form = BusinessForm(request.POST)
    if form.is_valid():
        business = form.save(commit=False)
        business.user = request.user
        business.save()

You don't have to use init or save overrides for this.

You're just setting an attribute on your form and the form doesn't do anything with it. It doesn't magically behave like a model instance (your form wouldn't have a user_id attribute).

Since your form is a ModelForm, you can simply call save on it with commit=False to get the unsaved instance, set the user, then call save on the instance.

 if request.method == 'POST':
    form = BusinessForm(request.POST)
    if form.is_valid():
        business = form.save(commit=False)
        business.user = request.user
        business.save()
半枫 2024-12-29 20:41:35

似乎正是您所寻找的。

this seems to be exactly what your looking for.

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