0

I'm learning Django 1.11 and I'm creating a form with widget_tweaks tools.

I have a variable "code" which is supposed to inform the template if the form is sent or not. If it's not sent, code = 1 and the form is displayed If the form is displayed, I just would like to display another form (not developed for now)

The problem is, code is always = 1

Why ?

Many Thanks

view.py

#-*- coding: utf-8 -*-
from django.shortcuts import render
from .forms import MinimumRegisterForm

# Create your views here.
def view_about(request):
 return render(request, 'about.html', locals())

def view_first(request):
 return render(request, 'first.html', locals())

def view_second(request):
 form = MinimumRegisterForm()
 if request.method == 'POST':
  form = MinimumRegisterForm(request.POST)
  if form.is_valid():
   identifiant = form.cleaned_data['identifiant']
   email = form.cleaned_data['email']
   password = form.cleaned_data['password']
   confirm_password = form.cleaned_data['confirm_password']
   code = "2"
 else:
  code = "1"
  return render(request, 'second.html', locals())
 return render(request, 'second.html', locals())

Template html

          <div class="inner cover">
            <h1 class="cover-heading">Parlons un peu de vous ...</h1>
            <div class="MinimumRegisterForm">
              {% if form.errors %}
                Les erreurs suivantes sont survenues:
              {{ form.errors }}
              {% endif %}
              {% if code == "1" %}
                <form action="{% url 'second' %}" action="POST">
                  {% csrf_token %}
                  <p>{{ form.identifiant|add_class:"form-control"|attr:"placeholder:Quel sera votre identifiant unique ?" }}</p>
                  <p>{{ form.email|add_class:"form-control"|attr:"placeholder:Indiquez-y votre email !" }}</p>
                  <p>{{ form.password|add_class:"form-control"|attr:"placeholder:Créer votre mot de passe ici." }}</p>
                  <p>{{ form.confirm_password|add_class:"form-control"|attr:"placeholder:Retaper votre mot de passe." }}</p>
                  <input class="btn btn-lg btn-primary" type="submit" value="Continuer">
                </form>
              {% elif code == "2" %}
                 <p>Formulaire suivant</p>
              {% endif %}
              {{ code }}              
            </div>
          </div>

Forms.py

from django import forms

class MinimumRegisterForm(forms.Form):
    identifiant = forms.CharField(
        max_length=50, 
        label="Choisissez un identifiant unique",
    )
    email = forms.EmailField(
        label="Votre adresse mail",
    )
    password = forms.CharField(
        widget=forms.PasswordInput, 
        label="Entrer un mot de passe",
    )
    confirm_password = forms.CharField(
        widget=forms.PasswordInput, 
        label="Confirmer votre mot de passe",
    )

2 Answers2

4

The point of using a Django form is that it will tell you itself what the problems are. Rather than using a pointless "code" variable that only gives you 0 or 1, you should get the form to show its errors in the template. Redisplaying the form gives your users the chance to fix those errors.

 <div class="MinimumRegisterForm">
      <p>Formulaire suivant</p>
      {% if form.errors %}
         Les erreurs suivantes sont survenues:
         {{ form.errors }}
      {% endif %}
      <form action="{% url 'second' %}" action="POST">
          {% csrf_token %}
          <p>{{ form.identifiant|add_class:"form-control"|attr:"placeholder:Quel sera votre identifiant unique ?" }}</p>
          <p>{{ form.email|add_class:"form-control"|attr:"placeholder:Indiquez-y votre email !" }}</p>
          <p>{{ form.password|add_class:"form-control"|attr:"placeholder:Créer votre mot de passe ici." }}</p>
          <p>{{ form.confirm_password|add_class:"form-control"|attr:"placeholder:Retaper votre mot de passe." }}</p>
          <input class="btn btn-lg btn-primary" type="submit" value="Continuer">
       </form>
  </div>
Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
  • This could be helpfull. I have updated my code above. Could you tell me why code always = "1" ? You can take a look : http://jaouani.dyndns.pro/start/inscription –  May 24 '17 at 08:32
0

Firstly, add form = MinimumRegisterForm() right bellow your view def and, secondly, you have to check if is a POST request if request.method == 'POST' and, only if it's POST, to bind the data to the form ohterwise the first time the form is rendered you'll get errors because the form is empty but you try to get POST data which hasn't been introduced yet.

from django.shortcuts import render
from .forms import MinimumRegisterForm

def view_second(request):

    if request.method == 'POST':
        form = MinimumRegisterForm(request.POST)
        if form.is_valid():
            identifiant = form.cleaned_data['identifiant']
            email = form.cleaned_data['email']
            password = form.cleaned_data['password']
            confirm_password = form.cleaned_data['confirm_password']
            code = "2"
            form = MinimumRegisterForm()
            return render(request, 'second.html', {'code': code, 'form': form})
    else:
        form = MinimumRegisterForm()
        code = "1"
        return render(request, 'second.html', {'code': code, 'form': form})

BUT, in a real app you don't use code = "1" and code = "2", instead you only display the errors (if any) in the template like @Daniel Roseman shows in his response.

doru
  • 9,022
  • 2
  • 33
  • 43
  • Ok I understand the logic of this code. However, now my variable code is not used to report an error but to report if the form is sent or not. If it's sent, code = 2 and the template display another form, if not, code = 1 and MinimumRegisterForm is displayed. The problem is, even if I sent the form, code is always = 1. Why ? –  May 24 '17 at 10:20
  • @GrandGTO I've updated answer and, bty, for sending messages you should/could use the [`messages`](https://docs.djangoproject.com/en/1.11/ref/contrib/messages/) framework. – doru May 24 '17 at 10:43
  • messages is to send message to a user. I just want to turn my var "code" to 2 inspite of "1". –  May 24 '17 at 12:11