简体   繁体   中英

Django 1.6: form not showing errors

I've a signup form that doesn't show any validation errors in the template. If submitted incorrect form it just renders the page again with blank fields. I'd like it to show the errors made by person signing up the form.

Here is the template where I've the form

 <form action="" method="post" id="user_uploader" enctype="multipart/form-data"> {% csrf_token %}
{{ form.non_field_errors }}
<div class="">
    {{ form.name }}
</div>

{{ form.error_messages }}
{{ form.help_text }}
<div class="">
    {{ form.username }}
</div>

{{ form.non_field_errors }}
<div class="">
    {{ form.email}}
</div>

{{ form.non_field_errors }} 
<div class="">
    {{ form.password1 }}
</div>

{{ form.non_field_errors }}
{{ form.error_messages }}
<div class="">
    {{ form.password2 }}
</div>

<button class="btn btn-primary" type="submit" name="submit" id="ss-submit">SIGN UP</button>

here is my forms.py

class UserCreationForm(forms.ModelForm):
    """
    A form that creates a user, with no privileges, from the given username and
    password.
    """
    error_messages = {
        'duplicate_username': _("A user with that username already exists."),
        'password_mismatch': _("The two password fields didn't match."),
    }
    name = forms.CharField(max_length=200, widget=forms.TextInput(attrs={'class': 'form-control','placeholder':'FirstName LastName'}))
    email = forms.EmailField(required=True, widget=forms.TextInput(attrs={'class': 'form-control','placeholder':'Please enter a valid email address so we can reach you.'}))
    username = forms.RegexField(label=_("Username"), max_length=50,
        regex=r'^[\w.@+-]+$',
        help_text=_("Required. 30 characters or fewer. Letters, digits and "
                    "@/./+/-/_ only."),
        error_messages={
            'invalid': _("This value may contain only letters, numbers and "
                         "@/./+/-/_ characters.")})
    password1 = forms.CharField(label=_("Password"),
        widget=forms.PasswordInput)
    password2 = forms.CharField(label=_("Password confirmation"),
        widget=forms.PasswordInput,
        help_text=_("Enter the same password as above, for verification."))

    class Meta:
        model = User
        fields = ("name","username","password1","password2","email")

    def clean_username(self):
        # Since User.username is unique, this check is redundant,
        # but it sets a nicer error message than the ORM. See #13147.
        username = self.cleaned_data["username"]
        try:
            User._default_manager.get(username=username)
        except User.DoesNotExist:
            return username
        raise forms.ValidationError(
            self.error_messages['duplicate_username'],
            code='duplicate_username',
        )

    def clean_password2(self):
        password1 = self.cleaned_data.get("password1")
        password2 = self.cleaned_data.get("password2")
        if password1 and password2 and password1 != password2:
            raise forms.ValidationError(
                self.error_messages['password_mismatch'],
                code='password_mismatch',
            )
        return password2

    def save(self, commit=True):
        user = super(UserCreationForm, self).save(commit=False)
        user.set_password(self.cleaned_data["password1"])
        fullName = self.cleaned_data["name"]
        Email = self.cleaned_data["email"]


        if commit:
            user.save()
            userProfile = DoctorSeeker(user=user, name=fullName, email=Email)
            userProfile.save()

        return user

Just to clarify I'm saving the signup information into two different models.

Here is my views.py

def signup_user(request):
    if request.method == 'POST':
        form = UserCreationForm(request.POST,request.FILES)
        if form.is_valid():
            new_user = form.save()
            new_user = authenticate(username=request.POST['username'],password=request.POST['password1'])
            login(request, new_user)

            return HttpResponseRedirect(reverse('index'))
    else:
        form = UserCreationForm()
    return render(request, "meddy1/signup.html", {'form': form,'usersignup':True})

You are not using the form passed from view in the template at all. You are manually rendering each form element. Rather you should use preferred way as shown in the docs here

From that doc

<form action="/contact/" method="post">
    {% for field in form %}
        <div class="fieldWrapper">
            {{ field.errors }}
            {{ field.label_tag }} {{ field }}
        </div>
    {% endfor %}
    <p><input type="submit" value="Send message" /></p>
</form>

You can add div s etc to create html as suits you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM