【问题标题】:Django 2 form is_valid is not working even on valid form dataDjango 2 form is_valid 即使在有效的表单数据上也不起作用
【发布时间】:2019-11-27 05:25:58
【问题描述】:

我正在开发一个非常简单的表单来在 Django(2) 中发布数据,但由于 form.is_valid() 没有被调用,所以表单总是无效。

这是我目前所拥有的:

来自models.py

class UserGroup(models.Model):
    email = models.EmailField(primary_key=True)
    group = models.CharField(max_length=250, default='notingroup')

    def __str__(self):
        return self.group

来自forms.py

class UserGroupForm(forms.ModelForm):
    class Meta:
        model = UserGroup
        fields = ('group', 'email')

来自views.py

def group_name(request):
    error = ''
    if request.method == 'POST':
        print(request.POST['email'])
        group_form = UserGroupForm(request.POST)
        print(group_form)
        if group_form.is_valid():
            ug_obj = UserGroup()
            ug_obj.group = group_form.cleaned_data['group']
            ug_obj.email = group_form.cleaned_data['email']
            ug_obj.save()
            return JsonResponse({"message": 'Got it inside valid'})

        else:
            error = 'Something went wrong'
            print(error)

        return JsonResponse({"message": 'an error occurs!'})

来自html template

<form method="post" id="gitForm" action="javascript:call_my_form()">
                {% csrf_token %}
                <label>Groupname: </label>
                <input id="user_email" type="text" value="{{ user.email }}" hidden>
                <input id="input" type="text" class="">
                <input type="submit" value="Mehet" class="btn btn-primary">
       <div id="error" style="color:red"></div>
</form>

来自javasctip function for Ajax

function call_my_form() {
    $(document).on('submit', '#gitForm', function (e) {
        e.preventDefault();
        console.log($('#input').val());
        console.log($('#user_email').val());
        $.ajax({
            type: 'POST',
            url: '/groupname',
            data: {
                group: $('#input').val(),
                email: $('#user_email').val(),
                csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val()
            },
            success: function (jsonResponse) {
                document.getElementById("demo").innerHTML = jsonResponse.message;

            }
        }).done(function (jsonResponse) {
            document.getElementById("demo").innerHTML = jsonResponse.message;
        })
    });
}

我在视图中获取了正确的数据,但 form.is_valid() 仍然没有被调用,

这是输出:

**********@mail.com <tr><th><label for="id_group">Group:</label></th><td><input type="text" name="group" value="scsacas" maxlength="250" required id="id_group"></td></tr> <tr><th><label for="id_email">Email:</label></th><td><ul class="errorlist"><li>User group with this Email already exists.</li></ul><input type="email" name="email" value="abdul12391@gmail.com" maxlength="254" required id="id_email"></td></tr>

出了点问题 [18/Jul/2019 09:47:47] "POST /groupname HTTP/1.1" 200 31

【问题讨论】:

  • 您应该在 else 块中打印 group_form.errors 以查看问题所在。更好的是,在您的 JsonResponse 中返回它
  • 因为email是主键,所以它是唯一的,所以你使用了same的email地址。

标签: python django django-forms django-2.0 django-validation


【解决方案1】:

正如您在输出中所说:User group with this Email already exists.

所以您正在尝试提交一封已经存在的电子邮件。这就是你的form.is_valid() 没有被调用的原因。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-05
    • 2018-06-09
    • 2023-01-17
    • 1970-01-01
    • 2019-03-06
    相关资源
    最近更新 更多