Django 2表单is_valid即使在有效的表单数据上也不起作用

时间:2019-07-18 09:51:41

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

我正在使用一种非常简单的表单将数据发布到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

1 个答案:

答案 0 :(得分:1)

如您的输出中所述:User group with this Email already exists.

因此,您正在尝试提交已存在的电子邮件。这就是为什么您的form.is_valid()不被呼叫的原因。