Django自动填充用户详细信息

时间:2015-05-21 23:48:40

标签: django

我使用Django通用CreateView添加条目。这是我的模特:

class MyModel(models.Model):
    purpose = models.CharField(max_length=50)
    is_visible = models.BooleanField(default=True)
    created_by = models.ForeignKey(User)

我的观点:

class MyModelAdd(CreateView):
    model = MyModel
    template_name = 'mymodeladd.html'
    fields = ('id', 'purpose', 'is_visible')

    def get_success_url(self):
        return '/myapp/success'

如何使用登录用户(request.user)填充created_by字段?

1 个答案:

答案 0 :(得分:1)

您可以覆盖form_valid功能。

class MyModelAdd(CreateView):
    model = MyModel
    template_name = 'mymodeladd.html'
    fields = ('id', 'purpose', 'is_visible')

    def form_valid(self, form):
        form.instance.created_by = self.request.user
        return super(MyModelAdd, self).form_valid(form)