0

I'm building my own site with Django's Framework. I made a form for creating a new account. It works well but I have a problem with my errors messages.

All my errors are already display when I first arrive on the page. After submit, if a field is wrong, the page newly updated display only the wanted messages.

Here is a view of my page at my first arrival

So, my question is: How can I do for display the message only if a field is wrong ? I already succeed to personalize each messages.

I paste you my different django files:

views.py

@csrf_exempt
def create_new_user(request):
form = UserCreateForm(request.POST)
if request.method=="POST":
    if form.is_valid():
        user = form.save()
        messages.info(request, "Merci pour votre enregistrement, vous etes maintenant connecte")
        new_user = authenticate(username=form.cleaned_data['username'],
        password=form.cleaned_data['password1']
        )
        login(request, new_user)
        return HttpResponseRedirect('/')
    return render_to_response('lejeudesbars/register.html', RequestContext(request, {'form': form}))
else:
    return render(request, 'lejeudesbars/register.html', {'form': form})

forms.py

class UserCreateForm(UserCreationForm):
    captcha = ReCaptchaField(error_messages={'required': 'Captcha: Validation obligatoire'})
    email = forms.EmailField(required=True)
    username = forms.CharField(error_messages={'required': 'Pseudo: Champ obligatoire'})
    email = forms.EmailField(error_messages={'required': 'Email: Champ obligatoire'})
    password1 = forms.CharField(widget=forms.PasswordInput(), error_messages={'required': 'Mot de passe: Champ obligatoire'})
    password2 = forms.CharField(widget=forms.PasswordInput(), error_messages={'required': 'Mot de passe: Confirmation obligatoire'})


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

    def save(self, commit=True):
        user = super(UserCreateForm, self).save(commit=False)
        user.email = self.cleaned_data["email"]
        if commit:
            user.save()
        return user`

index.html

    <form method="post" action="/accounts/register/">
        {% csrf_token %}
        <h1>S'enregistrer</h1>

        {{ form.username }}
        {% if form.errors %}
        <p class="error-msg-register">{{ form.username.errors }}</p>
        {% endif %}

        {{ form.email }}
        {% if form.errors %}
        <p class="error-msg-register">{{ form.email.errors }}</p>
        {% endif %}

        {{ form.password1 }}
        {% if form.errors %}
        <p class="error-msg-register">{{ form.password1.errors }}</p>
        {% endif %}

        {{ form.password2 }}
        {% if form.errors %}
        <p class="error-msg-register">{{ form.password2.errors }}</p>
        {% endif %}

        {{ form.captcha }}
        {% if form.errors %}
        <p class="error-msg-register">{{ form.captcha.errors }}</p>
        {% endif %}

        <input style="padding: 10px" type="submit" value="Créer mon compte" />
        <input type="hidden" name="next" value="{{ next }}" />
  </form>`

Thank you in advance for helping me !

(sorry for my bad english)


Thanks to Daniel Roseman, I've resolved my problem. Here is my updated views.py:

views.py

@csrf_exempt
def create_new_user(request):
    if request.method=="POST":
        form = UserCreateForm(request.POST)
        if form.is_valid():
            user = form.save()
            messages.info(request, "Merci pour votre enregistrement, vous etes maintenant connecte")
            new_user = authenticate(username=form.cleaned_data['username'],
            password=form.cleaned_data['password1']
        )
            login(request, new_user)
    else:
         form = UserCreateForm()
    return render(request, 'lejeudesbars/register.html', {'form': form})

2 Answers 2

5

You should only pass request.POST into the field if it actually is a POST. So:

def create_new_user(request):
    if request.method=="POST":
        form = UserCreateForm(request.POST)
        if form.is_valid():
            ...
    else:
        form = UserCreateForm()
    return render(request, 'lejeudesbars/register.html', {'form': form})

You also don't need that intermediate return render_to_response(...).

Sign up to request clarification or add additional context in comments.

4 Comments

Thank you very much, it worked ! I'm beginner so this is a newbie error I guess :)
But I don't know how to pass my subject to resolved (First post in StackOverflow). If you can show me how to do it ! Thanks
There should be a tick icon next to the answer which you can click.
I'm sorry, I don't see it
0

In each field you have {% if form.errors %} - so when there is at least one error, you are going to display it everywhere.

change it to {% if form.field_name.errors %} and then html should render only the errors associated with that specific field

1 Comment

It didn't work.. But thanks to Daniel Roseman, I figured out my mistake :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.