Django:检查用户是否存在,不显示validationerror

时间:2017-04-18 17:38:19

标签: python django

(Django新)我已经尝试了所有的东西,并花了一整天努力让这个工作。 我试图检查用户是否存在并显示ValidationError(如果已存在)。现在,我正在使用views.py来显示模板,其中显示帐户未创建,因为forms.py应该处理的验证错误未显示。

forms.py

from django.contrib.auth.models import User
from django import forms


class UserForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(UserForm, self).__init__(*args, **kwargs)
        self.fields['email'].required = True

    password = forms.CharField(widget=forms.PasswordInput)


    def clean_username(self):
        username = self.cleaned_data['username']
        if User.objects.filter(username=username).exists():
            raise forms.ValidationError("That user is already taken")
        return username

    class Meta:
        model = User
        fields = ['username', 'password', 'email']

        labels = {
            "email": "Email"
        }

    # including my login form too just in case
class LoginForm(forms.ModelForm):
    password = forms.CharField(widget=forms.PasswordInput)

    class Meta:
        model = User
        fields = ['username', 'password']
        labels = {
            "email": "Email"
        }

views.py

from django.shortcuts import render, redirect
from .forms import UserForm


def index(request):
    if request.user.is_authenticated:
        return redirect('/myaccount')
    else:
        title = "welcome"
        form = UserForm()

        context = {
            "template_title": title,
            "form": form

        }

        return render(request, "index.html", context)

def new_user(request):
    if request.method == "POST":

        form = UserForm(request.POST)
        if form.is_valid():
            username = form.cleaned_data.get("username")
            password = form.cleaned_data.get("password")
            email = form.cleaned_data.get("email")
            form.save()

            return render(request, "created.html")

        return render(request, "notcreated.html")

0 个答案:

没有答案