Answer the question
In order to leave comments, you need to log in
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})
{% 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">×</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 questionAsk a Question
731 491 924 answers to any question