新的Django类视图表单上的用户当前用户

时间:2010-12-22 18:13:50

标签: django django-forms

我在主干上使用django 1.3,并开始学习类视图。

我有这个:

class Project(models.Model):
    title = models.CharField(max_length=90)
    slug = models.CharField(max_length=90)
    description = models.TextField()
    owner = models.ForeignKey(User)

class ProjectForm(ModelForm):

    class Meta:
        model = Project
        exclude = ('owner',)
        widgets = {
            'description': Textarea(attrs={'cols': 40, 'rows': 20}),
        }

class ProjectCreateView(CreateView):
    model = Project
    form_class = ProjectForm

    def get(self, request, *args, **kwargs):
        return super(ProjectCreateView, self).get(request, *args, **kwargs)

    def post(self, request, *args, **kwargs):
        return super(ProjectCreateView, self).post(request, *args, **kwargs)

我正在尝试使用django中不包含所有者字段的模型表单来获取表单,以获取request.user属性之后的字段值。

表格原样,有效。但是如何确保ModelForm使用request.owner字段的request.user?

我的第一个猜测是,从视图中覆盖get_form_kwargs方法

class ProjectCreateView(CreateView):

    # .....

    def get_form_kwargs(self, **kwargs):
        self.initial['owner': self.request.user})
        kwargs = super(ProjectCreateView, self).get_form_kwargs(**kwargs)
        return kwargs

但似乎对模型表单使用的数据没有影响

1 个答案:

答案 0 :(得分:11)

get_form_kwargs应该为您的表单返回dict个参数 - 您设置self.initial,但未将其附加到kwargs

def get_form_kwargs(self, **kwargs):
    kwargs = super(ProjectCreateView, self).get_form_kwargs(**kwargs)
    kwargs['initial']['owner'] = self.request.user
    return kwargs