表单提交后Django init值更改

时间:2019-08-23 14:49:23

标签: django django-forms django-class-based-views

我正试图更改用户LoginView,出于某种原因,我想使用手机号码作为用户名,并且在用户输入电话号码后,我将通过短信将代码发送到手机。在发送SMS之前,我想确定垃圾邮件,但不要攻击我的表单。

我知道,我可以使用Google验证码和其他插件。但是对于我的训练,我想用自己的方式。我为模型名称创建了一个问题,表格中有很多问答。每次页面刷新时,都会向访问者显示一个随机问题。这工作正常,没有任何问题。但是我的问题是当我想验证表单self.question每次选择另一个随机问题时。这非常令人困惑。我试图验证内部视图和表单,没有差异的问题总是返回另一个问题。

model.py

class Question (models.Model):

    question = models.CharField(max_length=100, null=False)
    answer = models.CharField(max_length=100, null=False)
    secend_answer = models.CharField(max_length=100,blank=True, null=True)
    KIND_CHOISE = (
        ('I', 'idoms'),
        ('M', 'mathematic'),
        ('K', 'knowledge'),
    )
    question_kind = models.CharField(max_length=1, choices=KIND_CHOISE)

    def __str__(self):
        return  "quest => {}, answer is ==> {}".format(self.question, self.answer)

views.py

class LoginnView( FormView):
    form_class = UserLoginForm
    template_name  = 'accounts/login.html'
    success_url = 'accounts/login.html'

    def bquestion(self):
        ques = None
        max_id = Question.objects.all().aggregate(max_id=Max("id"))['max_id']
        while ques is None:
            ques = Question.objects.get(id=random.randint(1, max_id))
        return ques


    def get_form_kwargs(self):
        """This method is what injects forms with their keyword
            arguments."""
        # grab the current set of form #kwargs
        kwargs = super(LoginnView, self).get_form_kwargs()
        kwargs['question'] = self.bquestion()
        return kwargs

    def form_invalid(self, form):
        response = super(LoginnView, self).form_invalid(form)
        if self.request.is_ajax():
            return JsonResponse(form.errors, status=400)
        else:
            return response



    def form_valid(self, form):
        response = super(LoginnView, self).form_valid(form)

        if self.request.is_ajax():
            print(form.cleaned_data)
            data = {
                'message': "Successfully submitted form data."
            }
            return JsonResponse(data)
        else:
            return response

forms.py

class UserLoginForm(forms.Form):
    username = forms.CharField(max_length=11)
    security_question = forms.CharField()

    def __init__(self,question , *args, **kwargs):
        # self.question = kwargs.pop('question')
        super(UserLoginForm, self).__init__(*args, **kwargs)
        self.question = question

    def clean_username(self):
        message = self.cleaned_data['username']
        if not message.isdigit():
            self.add_error('username','error')

        if len(message) < 11:
            self.add_error('username','error')
        if len(message) > 11:
            self.add_error('username','error')

        return message


    def clean(self):
        cleaned_data = super(UserLoginForm, self).clean()
        answer = cleaned_data.get("security_question")
        ques = self.question.question
        ans = self.question.answer
        if answer != self.question.answer : #todo != self.question.secend_answer:
            msg = u"you answer is wrong"
            self.add_error('security_question', msg)
        return cleaned_data

login.html

                <form method='POST' action='.' data-url='{{ request.build_absolute_uri|safe }}'>
                    {% csrf_token %}
                    <div class="form-group">
                        <h4>please enter your phone</h4>
                        <input  class="form-control" value="{{ username }}"
                               id="id_username" name="username">
                        <div class="invalid-feedback">
                            {{ form.username.errors }}
                          </div>
                    </div>
                    <div class="form-group" id="question">

                    <h4>answer this question.</h4>



                        <br>
                        <h5>{{ form.question.question }}</h5>

                        <input class="form-control"
                                id="security_question" name="security_question">
                        <div class="invalid-feedback">
                            {{ form.security_question.errors }}
                        </div>
                    </div>



                    <button type="submit" class="button primary-bg btn-block">submit</button>
                </form>

我尝试在form_valid中查看答案,但效果相同。

感谢您的时间来帮助和阅读。

0 个答案:

没有答案