如何在Django中提交后清除基于类的视图中的表单字段

时间:2016-08-11 21:27:22

标签: python django python-3.x django-views reset-password

我在Django项目中使用基于类的视图进行密码重置。我的表单只有一个字段,用户可以在那里写电子邮件地址或用户名。成功提交后,用户可以在同一页面中看到成功消息。我的问题是,提交后我看到空字段,但同时我可以通过单击按钮再次发送数据。 成功提交后如何清除表单字段?我有点不耐烦。

views.py

class PasswordResetRequestView(FormView):
    template_name = "registration/password_reset.html"
    success_url = '/account/password_reset'
    form_class = PasswordResetRequestForm

    @staticmethod
    def validate_email_address(email):
        try:
            validate_email(email)
            return True
        except ValidationError:
            return False

    def post(self, request, *args, **kwargs):
        global data
        form = self.form_class(request.POST)
        try:
            if form.is_valid():
                data = form.cleaned_data["email_or_username"]
            if self.validate_email_address(data) is True:
                associated_users = User.objects.filter(Q(email=data) | Q(username=data))
                if associated_users.exists():
                    for user in associated_users:
                        c = {
                            'email': user.email,
                            'domain': request.META['HTTP_HOST'],
                            'site_name': 'your site',
                            'uid': urlsafe_base64_encode(force_bytes(user.pk)),
                            'user': user,
                            'token': default_token_generator.make_token(user),
                            'protocol': 'http',
                        }
                        subject_template_name = 'registration/password_reset_subject.txt'
                        email_template_name = 'registration/password_reset_email.html'
                        subject = loader.render_to_string(subject_template_name, c)
                        subject = ''.join(subject.splitlines())
                        email = loader.render_to_string(email_template_name, c)
                        send_mail(subject, email, DEFAULT_FROM_EMAIL, [user.email], fail_silently=False)
                    result = self.form_valid(form)
                    messages.success(request, 'An email has been sent to ' +
                                     data + ". Please check its inbox to continue reseting password.")
                    return result
                result = self.form_invalid(form)
                messages.error(request, 'No user is associated with this email address')
                return result
            else:
                associated_users = User.objects.filter(username=data)
                if associated_users.exists():
                    for user in associated_users:
                        c = {
                            'email': user.email,
                            'domain': 'example.info',
                            'site_name': 'example',
                            'uid': urlsafe_base64_encode(force_bytes(user.pk)),
                            'user': user,
                            'token': default_token_generator.make_token(user),
                            'protocol': 'http',
                        }
                        subject_template_name = 'registration/password_reset_subject.txt'
                        email_template_name = 'registration/password_reset_email.html'
                        subject = loader.render_to_string(subject_template_name, c)
                        # Email subject *must not* contain newlines
                        subject = ''.join(subject.splitlines())
                        email = loader.render_to_string(email_template_name, c)
                        send_mail(subject, email, DEFAULT_FROM_EMAIL, [user.email], fail_silently=False)
                    result = self.form_valid(form)
                    messages.success(request, 'Email has been sent to ' +
                                     data + "'s email address. Please check its inbox to continue reseting password.")
                    return result
                result = self.form_invalid(form)
                messages.error(request, _('This username does not exist in the system.'))
                return result
        except Exception as e:
            print(e)
        return self.form_invalid(form)

1 个答案:

答案 0 :(得分:1)

首先,永远不要使用全局变量。

其次,您可以将帖子逻辑放入form.save()方法中。 IMO在那里更合适,它与DjangoForm正在做的事情很接近

这就是class PasswordResetRequestForm(forms.Form): #We are not using EmailField on purpose #because you want to treat it #as a username if its not an email email = forms.CharField(required=True) def __init__(self, *args, **kwargs): #For sending emails we are gonna need the request. request = kwargs.pop('request') super(PasswordResetRequestForm, self).__init__(*args, **kwargs) def clean_email(self): #You can add form error here if no user exists email = self.cleaned_data['email'] users = User.objects.filter(Q(email=email)|Q(username=email)) if not users.exists(): self.add_error('email', 'No associated account found') def send_email(self, user): c = { 'email': user.email, 'domain': self.request.META['HTTP_HOST'], 'site_name': 'your site', 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'user': user, 'token': default_token_generator.make_token(user), 'protocol': 'http', } subject_template_name = 'registration/password_reset_subject.txt' email_template_name = 'registration/password_reset_email.html' subject = loader.render_to_string(subject_template_name, c) subject = ''.join(subject.splitlines()) email = loader.render_to_string(email_template_name, c) send_mail(subject, email, DEFAULT_FROM_EMAIL, [user.email], fail_silently=False) def save(self): email = self.cleaned_data['email'] users = User.objects.filter(Q(email=email)|Q(username=email)) for user in users: self.send_email(user) messages.success(self.request, """An email has been sent to %s. Please check its inbox to continue reseting password.""" % email ) 课程的样子:

View

现在在request,您只需将form.kwarg作为form.save()发送,并在`form.is_valid()时调用class PasswordResetRequestView(FormView): template_name = "registration/password_reset.html" success_url = '/account/password_reset' form_class = PasswordResetRequestForm def get_form_kwargs(self, *args, **kwargs): kwargs = super(PasswordResetRequestView, self).get_form_kwargs(*args, **kwargs) kwargs['request'] = self.request return kwargs def form_valid(self, *args, **kwargs): form = kwargs['form'] form.save() return super(PasswordResetRequestView, self).form_valid(*args, **kwargs)

String.Join(",", myArray)