V
V
Vitaly2017-01-25 18:43:03
Django
Vitaly, 2017-01-25 18:43:03

How to display valid fields on form after validation check?

Welcome all.
I am making a registration form in Django, how can I make it so that after reloading the page, when errors are displayed, valid fields remain on the form.
forms.py

def signup(request):

    if request.method == 'GET':

        signup_fm = SignUpForm()

        return render(request, 'core/registration.html', context={'form': signup_fm})

    if request.method == 'POST':

        signup_fm = SignUpForm(request.POST)

        if signup_fm.is_valid():

            username = signup_fm.cleaned_data.get('username')
            first_name = signup_fm.cleaned_data.get('first_name')
            last_name = signup_fm.cleaned_data.get('last_name')
            email = signup_fm.cleaned_data.get('email')
            password = signup_fm.cleaned_data.get('password1')

            birthday = signup_fm.cleaned_data.get('birthday')
            location = signup_fm.cleaned_data.get('location')

            u = User.objects.create_user(username=username, first_name=first_name,
                                         last_name=last_name, email=email, password=password)

            u.profile.birthday = birthday
            u.profile.location = location
            u.profile.save()

            user = authenticate(username=username, password=password)
            login(request, user)

            return redirect(reverse('profile', args=[username]))

        else:
            return render(request, 'core/registration.html', context={'form': signup_fm})

Now, for example, when the user enters everything correctly, but makes a mistake in entering the date, the page is reloaded and a list of validation errors is displayed. In this case, the date field validation error. And the rest of the fields that were entered correctly remain empty, and they have to be entered again.
How to solve this situation? Thank you!
registration.html
{% for field in form %}
      {% if field.errors %}
      <div class="alert alert-dismissible alert-danger" role="alert">
        <button type="button" class="close" data-dismiss="alert" aria-label="Close">
        <span aria-hidden="true">&times;</span>
        </button>
        {{ field.label }}
        {{ field.errors }}
      </div>
      {% endif %}
    {% endfor %}

  <form action="{% url 'signup' %}" method="post">
....
</form>

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question