Django在视图中保存和更新模型字段

时间:2018-04-16 06:19:09

标签: django django-models django-forms django-views

SetPasswordForm只设置用户密码

class SetPasswordForm(forms.Form):
    password = forms.CharField(label="Password", widget=forms.PasswordInput)

    def __init__(self, user, *args, **kwargs):
        self.user = user
        super(SetPasswordForm, self).__init__(*args, **kwargs)

    def save(self, commit=True):
        self.user.set_password(self.cleaned_data['password'])

        if commit:
            self.user.save(update_fields=['password'])

        return self.user
设置密码后使用User方法激活新用户的

activate()模型

class User(BaseUser):
        activation_code = models.CharField(max_length=100, blank=True, null=True)
        activated_at = models.DateTimeField(blank=True, null=True)

    def activate(self):
        self.is_active = True
        self.activation_code = None
        self.activated_at = datetime.now()
        self.save(update_fields=['is_active', 'activation_code', 'activated_at'])

在视图中,当用户提交表单时,它应该设置新密码并激活用户

class ActivateUserView(View):
    def post(self, request, activation_code):
        try:
            user = User.objects.get(activation_code=activation_code)
        except User.DoesNotExist:
            return Http404()

        form = SetPasswordForm(user=user, data=request.POST)

        if form.is_valid():
            user = form.save(commit=False)
            user.activate()

            return render(request, 'users/activate_user_done.html', {'user': user})

        return render(request, self.template_name, {'user': user})

问题是我不知道在哪里拨打user.activate()? 在形式或视野中?

我不认为form.save()也应该调用此方法,因为表单在其他地方不可重复使用。

1 个答案:

答案 0 :(得分:0)

<div class="parent"> <div class="child1">child 1</div> <div class="child2">child 2</div> </div> .parent { width: 100%; overflow: hidden; position: relative; height: 200px; } .child1 { width: 100%; left: 0; top: 0; position: absolute; } .child2 { width: 100%; left: -100%; top: 0; position: absolute; } 之前致电user.activate,因为您只想在用户激活帐户时保存用户。