如何使用Django UpdateView使用当前用户数据填充表单

时间:2015-11-16 16:50:38

标签: python django django-forms django-views

我有一个用户定义,部分原因如下:

TVTopShelfItemsDidChangeNotification

用户可以是自由职业者或客户。以Freelancer为例:

class User(AbstractBaseUser):
    ...
    email = models.EmailField(unique=True)
    type = models.IntegerField(choices=STATUS_CHOICES)
    verified = models.BooleanField(default=False)
    created_date = models.DateTimeField(default=timezone.now)

    USERNAME_FIELD = 'email'

...

我已经为用户注册创建了一个表单。当我注册时,我得到他们选择的用户类型,并在相应的表格中创建一条记录:

class Freelancer(models.Model):
    user = models.ForeignKey(User)
    first_name = models.CharField(max_length=128)
    ...

所以现在我有一个用户和一个自由职业者链接到该用户,现在我希望让用户能够编辑他们的所有细节:

if form.is_valid():
            user = form.save(commit=False)
            user.set_password(user.password)
            user.save()
            # create subgroup based on user type
            if user.type == 1:
                fl = Freelancer(user=user)
                fl.save()

表格如下:

class Profile(UpdateView):
    model = User
    form_class = UserUpdateForm
    second_form_class = FreelanceUpdateForm
    template_name = "freelancestudent/profile.html"

    def get_queryset(self):
        queryset = super(Profile, self).get_queryset()
        if not self.request.user.is_authenticated():
            return queryset.none()
        else:
            return queryset.filter(pk=self.request.user.pk)

    def get_context_data(self, **kwargs):
            context = super(Profile, self).get_context_data(**kwargs)
            context['form'] = self.form_class(self.request.GET, instance=self.request.user)
            context['form2'] = self.second_form_class(self.request.GET, instance=self.request.user)
            return context

    def get(self, request, *args, **kwargs):
        super(Profile, self).get(request, *args, **kwargs)
        form = self.form_class
        form2 = self.second_form_class
        return self.render_to_response(self.get_context_data(
            object=self.object, form=form, form2=form2))

问题是它不会用现有数据填充数据。我查看了this,这引出了我class UserUpdateForm(forms.ModelForm): class Meta: model = User fields = ('email',) class FreelanceUpdateForm(forms.ModelForm): class Meta: model = Freelancer fields = ('university',) 的想法,当我调试时,我可以看到它确实得到了用户的实例,但没有人口。这是为什么?

1 个答案:

答案 0 :(得分:0)

您必须使用initial属性填充表单。

以下是填充用户的电子邮件字段的示例。不要忘记删除self.request.GET,在此视图中它无用且无法使用:

context['form'] = self.form_class(instance=self.request.user, initial={'email':self.request.user.email})

阅读Django文档以获取更多信息:dynamic-initial-values