如果表单无效,如何阻止表单提交?

时间:2016-12-15 08:00:08

标签: python django django-forms django-views

因此,当表单无效且我点击提交时,由于return redirect('/'),它只会重定向到/ home。那么我在这里有return来阻止表单提交并提出错误消息?这是我的代码:

views.py

class BoxesView(ListView, FormMixin):
    template_name = 'polls.html'  # extends base.html
    form_class = UserRegistrationForm

    def get_context_data(self, **kwargs):
        context = super(BoxesView, self).get_context_data()

        question_list = Question.objects.all().order_by('-date')
        choice = Choice.objects.all()
        context['question_list'] = question_list
        context['choice'] = choice

        q_list = []
        returned_list = []

        for i in question_list:
            q_list.append(i)

        for a, b in CATEGORY_CHOICES:
            name = resolve(self.request.path_info).url_name
            if b == name:
                category = a

        search = self.request.GET.get('search')
        posts = Post.objects.all().filter(category=category).order_by('-date')
        if search:
            posts = posts.filter(
                Q(title__icontains=search) |
                Q(content__icontains=search)
            )
        else:
            posts = Post.objects.all().filter(category=category).order_by('-date')

        context['posts'] = posts

        total = 0
        for post in posts:
            returned_list.append(post)
            total += 1
            if total == 4:
                total = 0
                for i in q_list:
                    returned_list.append(i)
                    q_list.remove(i)
                    break

        paginator = Paginator(returned_list, 14)
        page = self.request.GET.get('page')

        try:
            lst = paginator.page(page)
        except PageNotAnInteger:
            # If page is not an integer, deliver first page.
            lst = paginator.page(1)
        except EmptyPage:
            # If page is out of range (e.g. 9999), deliver last page of results.
            lst = paginator.page(paginator.num_pages)

        context['lst'] = lst

        return context

    def get_queryset(self):
        pass

def register(request):
    form = UserRegistrationForm(request.POST)
    if form.is_valid():
        username = form.cleaned_data['username']
        password = form.cleaned_data['password']
        email = form.cleaned_data['email']
        user = User.objects.create_user(username=username, password=password, email=email)
        user.save()
        return redirect('/')
    else:
        print(form.errors)
        form = UserRegistrationForm()
    return redirect('/')

在我的forms.py中,它会向终端引发异常错误,但表单仍然提交。

forms.py

class UserRegistrationForm(forms.ModelForm):
    email = forms.EmailField()
    username = forms.CharField(max_length=25)
    password = forms.CharField(widget=forms.PasswordInput)
    confirm_password = forms.CharField(widget=forms.PasswordInput)

    class Meta:
        model = User

        fields = [
            'username',
            'email',
            'password',
        ]

    def clean(self):
        email = self.cleaned_data.get('email')

        current_emails = User.objects.filter(email=email)

        if current_emails.exists():
            raise forms.ValidationError("That email is taken")

base.html文件

<form method="post" enctype="multipart/form-data" action="{% url 'register' %}">{% csrf_token %}
    <div class="registerBox">
        <p><label for="id_username"></label> <input id="id_username" type="text" name="username" maxlength="30" placeholder="username"/></p>
        <p><label for="id_email"></label> <input type="email" name="email" id="id_email" placeholder="email"/></p>
    <p><label for="id_password"></label> <input type="password" name="password" id="id_password" placeholder="password"/></p>
        <p><label for="id_confirm_password"></label> <input type="password" name="confirm_password" id="id_confirm_password" placeholder="confirm password"/></p>
    <input type="submit" value="register" />
    </div>
</form>

有什么想法吗?

3 个答案:

答案 0 :(得分:2)

当表单无效时,您不应该尝试阻止提交。您应该做的是接受提交,检查错误,然后将错误和填写的表单返回到模板。

但是你做了三件事就是为了防止这种情况发生:你总是在表单无效时重新实例化,你总是重定向,并且你不会在模板中显示错误或以前的值。

所以你应该这样做:

def register(request):
    form = UserRegistrationForm(request.POST)
    if form.is_valid():
        username = form.cleaned_data['username']
        password = form.cleaned_data['password']
        email = form.cleaned_data['email']
        user = User.objects.create_user(username=username, password=password, email=email)
        user.save()
        return redirect('/')
    return render('mytemplate.html', {"form": form})

并在模板中:

<div class="registerBox">
    {{ form.non_field_errors }}
    <p>{{ form.username.label_tag }} {{ form.username }} {{ form.username.errors }}</p>
    <p>{{ form.email.label_tag }} {{ form.email }} {{ form.email.errors }}</p>
    <p><label for="id_password"></label> <input type="password" name="password" id="id_password" placeholder="password"/></p>
    <p><label for="id_confirm_password"></label> <input type="password" name="confirm_password" id="id_confirm_password" placeholder="confirm password"/></p>
    <input type="submit" value="register" />
</div>

答案 1 :(得分:0)

如果您不想提交无效表单,则应使用ajax验证。

答案 2 :(得分:0)

你试过吗

if form.is_valid():
    ...
else:
    return form_invalid(form)