Django表单不会显示错误

时间:2018-02-20 09:49:41

标签: python django error-handling registration

我正在尝试显示注册页面的错误消息。但不幸的是它根本不起作用。当我提交时,它只是进入登录页面。

这是我的register.html

    {% load widget_tweaks %}
    <form method="post">
        {% csrf_token %}
        {{ form.as_p }}

        <div style="margin-top: 1em;">
          <button class="btn btn-success btn-sm" type="submit">Konto erstellen</button>
          <a style="margin-left: 1em;" href="{% url 'accounts:login' %}" id="cancel" name="cancel" class="btn btn-default">Zurück</button></a>
        </div>
    </form>
  </div>
</div>
{% endblock %}

这是我的forms.py(RegistrationForm)

class RegistrationForm(UserCreationForm):
username = forms.CharField(max_length=30, required=True,
widget=forms.TextInput(
        attrs={
            'class': 'form-control',
            'type': 'text',
            'name': 'username',
            'autofocus': 'autofocus'
        }
    )
)

first_name = forms.CharField(max_length=30, required=False,
widget=forms.TextInput(
        attrs={
            'class': 'form-control',
            'type': 'text',
            'name': 'first_name',
        }
    )
)

last_name = forms.CharField(max_length=30, required=False,
widget=forms.TextInput(
        attrs={
            'class': 'form-control',
            'type': 'text',
            'name': 'last_name',
        }
    )
)

email = forms.EmailField(max_length=30, required=True,
widget=forms.TextInput(
        attrs={
            'class': 'form-control',
            'type': 'email',
            'name': 'email',
        }
    )
)

password1 = forms.CharField(label=("Passwort*"), required=True,
widget=forms.PasswordInput(
        attrs={
            'class': 'form-control',
            'type': 'password',
            'name': 'password1',
        }
    )
)

password2 = forms.CharField(label=("Passwort bestaetigen*"), required=True,
widget=forms.PasswordInput(
        attrs={
            'class': 'form-control',
            'type': 'password',
            'name': 'password2',
        }
    )
)

class Meta:
    model = User
    fields = (
        'username',
        'first_name',
        'last_name',
        'email',
        'password1',
        'password2'
    )

def clean_username(self):
    existing = User.objects.filter(username__iexact=self.cleaned_data['username'])
    if existing.exists():
        raise forms.ValidationError(("A user with that username already exists."))
    else:
        return self.cleaned_data['username']

def clean(self):
    if 'password1' in self.cleaned_data and 'password2' in self.cleaned_data:
        if self.cleaned_data['password1'] != self.cleaned_data['password2']:
            raise forms.ValidationError(("The two password fields didn't match."))
    return self.cleaned_data

def clean_email(self):
    if User.objects.filter(email__iexact=self.cleaned_data['email']):
        raise forms.ValidationError(("This email address is already in use. Please supply a different email address."))
    return self.cleaned_data['email']

def save(self, commit=True):
    user = super(RegistrationForm, self).save(commit=False)
    user.first_name = self.cleaned_data['first_name']
    user.last_name = self.cleaned_data['last_name']
    user.email = self.cleaned_data['email']

    if commit:
        user.save()
    return user

我不确定这是否是创建用户的正确方法,因为我对Django来说相当新。

Views.py

def register(request):
    if request.method == 'POST':
        form = RegistrationForm(request.POST)

        if form.is_valid():
            form.save()
            username = form.cleaned_data.get('username')
            raw_password = form.cleaned_data.get('password1')
            user = authenticate(username=username, password=raw_password)
            login(request, user)
        return redirect('accounts:view_profile')
    else:
        form = RegistrationForm()
        args = {'form': form}
    return render(request, 'accounts/registration.html', args)

1 个答案:

答案 0 :(得分:1)

尝试更新您的观点:

def register(request):
    form = RegistrationForm()

    if request.method == 'POST':
        form = RegistrationForm(request.POST)

        if form.is_valid():
            form.save()
            username = form.cleaned_data.get('username')
            raw_password = form.cleaned_data.get('password1')
            user = authenticate(username=username, password=raw_password)
            login(request, user)
            return redirect('accounts:view_profile')

    args = {'form': form}
    return render(request, 'accounts/registration.html', args)