在Django Vanilla CreateView上设置当前用户 [英] Setting current user on django vanilla CreateView

查看:86
本文介绍了在Django Vanilla CreateView上设置当前用户的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用当前登录的用户更新我的模型。我正在使用django-vanilla-views。为了存储新记录,我尝试使用CreateView。我不想在表单上显示用户,只需自动更新即可。

I would like to update my model with the currently logged in user. I am using django-vanilla-views. To store a new record I am trying to use CreateView. I don't want to display user on the form, just update it automatically.

这是我的模型:

class Measurement(models.Model):
    date = models.DateField()
    user = models.ForeignKey(User)

这是我的观点:

class CreateMeasurement(CreateView):
    model = Measurement
    fields = ['date']
    success_url = reverse_lazy('list_measurements')

    def get_form(self, data=None, files=None, **kwargs):
        kwargs['user'] = self.request.user
        return super(CreateMeasurement, self).get_form(data=data, files=files, **kwargs)

不幸的是,访问视图时出现以下异常:

Unfortunately when accessing the view I get the following exception:

TypeError: __init__() got an unexpected keyword argument 'user'

我也尝试为我的模型创建一个ModelForm,但是得到了完全相同的错误。有什么想法我可能做错了吗?

I also tried to create a ModelForm for my model but got exactly the same error. Any ideas what I might be doing wrong?

推荐答案

您不需要将用户传递给表单,所以不要t覆盖 get_form 方法。您已经通过在视图中设置 fields 从模型表单中排除了用户 field ,因此您不需要自定义模型形式。

You don't need to pass the user to the form, so don't override the get_form method. You have already excluded the user field from the model form by setting fields in your view, so you shouldn't need a custom model form either.

应该足以覆盖 form_valid 方法,并在保存表单时设置用户。

It should be enough to override the form_valid method, and set the user when the form is saved.

from django.http import HttpResponseRedirect

class CreateMeasurement(CreateView):
    model = Measurement
    fields = ['date']
    success_url = reverse_lazy('list_measurements')

    def form_valid(self, form):
        obj = form.save(commit=False)
        obj.user = self.request.user
        obj.save()
        return HttpResponseRedirect(self.get_success_url())

这篇关于在Django Vanilla CreateView上设置当前用户的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆