User Register form not validating or returning errors.

419 views
Skip to first unread message

Kean

unread,
Aug 24, 2019, 12:33:53 PM8/24/19
to Django users
Hi,

New to Django.
I've created a user registration form, the issue is it does not run validations or report errors with the data entered. It simply routes to the redirect url.
Please can I ensure the user sees the correct error in a post case scenari for both a django form, and customsied django form.

forms.py

class UserRegisterForm(UserCreationForm):
    email = forms.EmailField()

    class Meta:
        model = User
        fields = 'username', 'email', 'password1', 'password2'

Views.py

def register(request):
    if request.method == 'POST':
        form = UserRegisterForm(request.POST)
        if form.is_valid():
            form.save()
            username = form.cleaned_data.get('username')
            messages.success(request, f'Account created for {username}')
        return HttpResponseRedirect('cprofile')
    else:
        form = UserRegisterForm()
    context = {'form': form}
    return render(request, "register.html", context,)

template.html

<head>
<title>Registration</title>
</head>
<body>
<br>
<div class = "container">
<form method = "POST">
{% csrf_token %}
<fieldset class="form">
<legend class="border-bottom mb-2">Register</legend>
{{ form|crispy }}
{% if messages %}
{% for messages in messages %}
<div class="alert alert{{ message.tag }}">
{{ messages }}
</div>
{% endfor %}
{% endif %}
</fieldset>
<br>
<div class = "form">
<button class ="btn btn-outline-info" type="submit">Register</button>

Any help would be much appreciated

Best,

K


Abu Yusuf

unread,
Aug 25, 2019, 1:21:30 AM8/25/19
to django...@googlegroups.com
Wher is the form action? If you don't provide the form action then how can it recognize which views should be called? 
Set the action here: <form action="{ % url 'register' %}" method = "POST">

Like this.

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/5a003506-de8d-4587-863d-3fc26e4c45c1%40googlegroups.com.

Ajeet Kumar Gupt

unread,
Aug 25, 2019, 3:53:52 AM8/25/19
to django...@googlegroups.com, kea...@gmail.com
Hi, 

Please use the below code.

views.py
__________________

def user_register(request):
# if this is a POST request we need to process the form data
template = 'mymodule/register.html'
# template = 'index.html'
if request.method == 'POST':
# create a form instance and populate it with data from the request:
form = RegisterForm(request.POST)
# check whether it's valid:
if form.is_valid():
if User.objects.filter(username=form.cleaned_data['username']).exists():
return render(request, template, {
'form': form,
'error_message': 'Username already exists.'
})
elif User.objects.filter(email=form.cleaned_data['email']).exists():
return render(request, template, {
'form': form,
'error_message': 'Email already exists.'
})
elif form.cleaned_data['password'] != form.cleaned_data['password_repeat']:
return render(request, template, {
'form': form,
'error_message': 'Passwords do not match.'
})
else:
# Create the user:
user = User.objects.create_user(
form.cleaned_data['username'],
form.cleaned_data['email'],
form.cleaned_data['password']
)
user.first_name = form.cleaned_data['first_name']
user.last_name = form.cleaned_data['last_name']
user.phone_number = form.cleaned_data['phone_number']
user.save()
return redirect('/login/')
# Login the user
#login(request, user)
#def user_login(request):
# redirect to accounts page:
#return render(request, '/login.html')
# return HttpResponseRedirect(return, '/login.html')
# No post data availabe, let's just show the page.
else:
form = RegisterForm()
return render(request, template, {'form': form})

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/5a003506-de8d-4587-863d-3fc26e4c45c1%40googlegroups.com.


--






Thanks & Regards
Ajeet Kumar Gupt
+91-9311232332

Kean

unread,
Aug 27, 2019, 11:30:28 AM8/27/19
to Ajeet Kumar Gupt, django...@googlegroups.com
Hi Ajeet, thanks for code, 
however after i press submit i get the

Forbidden (403)

CSRF verification failed. Request aborted.

Help

Reason given for failure:
    CSRF token missing or incorrect.
    
In general, this can occur when there is a genuine Cross Site Request Forgery, or when Django's CSRF mechanism has not been used correctly. For POST forms, you need to ensure:
  • Your browser is accepting cookies.
  • The view function passes a request to the template's render method.
  • In the template, there is a {% csrf_token %} template tag inside each POST form that targets an internal URL.
  • If you are not using CsrfViewMiddleware, then you must use csrf_protect on any views that use the csrf_token template tag, as well as those that accept the POST data.
  • The form has a valid CSRF token. After logging in in another browser tab or hitting the back button after a login, you may need to reload the page with the form, because the token is rotated after a login.
You're seeing the help section of this page because you have DEBUG = True in your Django settings file. Change that to False, and only the initial error message will be displayed.
You can customize this page using the CSRF_FAILURE_VIEW setting.

my template is referencing csrf_token

template.html

<!DOCTYPE html>
<html>
<head>
<title>Customer</title>
</head>
<body>
<h8> "Customer register" </h8>
<div>
<div class = "container" >
<form method="POST"
{% csrf_token %}
{{ form.as_p }}
<input type="submit" />
</form>
</div>
</div>
</body>
</html>


Am i doing something wrong?

Best,
K

Ajeet Kumar Gupt

unread,
Aug 27, 2019, 12:31:56 PM8/27/19
to Kean, django...@googlegroups.com
Hi Kean,

First need to close the proper tags

I seen your code form tag is not closed properly. Once first form tag closed than write the code csrf token

Kean

unread,
Aug 27, 2019, 1:03:46 PM8/27/19
to Ajeet Kumar Gupt, django...@googlegroups.com
Thank you, this resolved issue.

best,

K

Gabriel Araya Garcia

unread,
Aug 27, 2019, 1:36:44 PM8/27/19
to django...@googlegroups.com
Only see the 'error_new' variable in my view
this variable has taken two values: "ok" or "error1" (true or false, error or not error,..etc)

def NuevoPac(request):
# Manda al formulario todos los campos vacios
variable1 = 'Agregando nueva Ficha de Paciente'
variable2 = "modifica_rut"
error_new = "ok"
form   =  PacientesForm(request.POST or None)
region    =  Param.objects.filter(tipo='REGI').order_by('descrip')
comuna    =  Param.objects.filter(tipo='COMU').order_by('descrip')
sexo      =  Param.objects.filter(tipo='SEXO').order_by('codigo')
context = {
'form':form,
'variable1':variable1,
'variable2':variable2,
'region':region,
'comuna':comuna,
'sexo':sexo,
'error_new':error_new,
}
if request.method == "POST":
paciente = Pacientes    # modelo
rut_x = request.POST.get('rut') # valor del template
existe = paciente.objects.filter(rut=rut_x).exists()
if existe == True:
error_new = 'error1'
context = {
'form':form,
'variable1':variable1,
'variable2':variable2,
'region':region,
'comuna':comuna,
'sexo':sexo,
'error_new':error_new,
}
else:
if form.is_valid():
paciente = Pacientes    # modelo
form.save()
return redirect('grid_pacientes')
return render(request, 'ficha_pacientes.html',context)

Remember that 'POST' is when you give a submit botton, and you must put this cod lines in your template:

{% if error_new == "error1" %}
     <p class="error1">R.U.T. de Paciente ya existe !!</p>
{% endif %}

You should put it before of the disply text fields in your template. Therefore the alert message will be showed at the top.
 
please tell me if your trouble has been fixed

Sorry for my english

Gabriel Araya Garcia
Chile


 

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/5a003506-de8d-4587-863d-3fc26e4c45c1%40googlegroups.com.


--
Gabriel Araya Garcia
GMI - Desarrollo de Sistemas Informáticos
99.7721.15.70

K. KOFFI

unread,
Aug 27, 2019, 4:42:22 PM8/27/19
to Ajeet Kumar Gupt, django...@googlegroups.com
please put « > » before the csrf tag


Tosin Ayoola

unread,
Aug 28, 2019, 2:23:26 AM8/28/19
to django...@googlegroups.com
You  didn't close the form tag that why you getting this error 

To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.


--






Thanks & Regards
Ajeet Kumar Gupt
+91-9311232332

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/a01e8d1e-7c99-4c26-a569-4ccd08daa12f%40Spark.

Amitesh Sahay

unread,
Aug 28, 2019, 4:12:43 AM8/28/19
to django...@googlegroups.com
May be you can try the below in-built django feature for the registration form creation:

from django.contrib.auth.forms import UserCreationForm
def register_user(request):
if request.method == 'POST':
form = UserCreationForm(request.POST)
if form.is_valid():
form.save()
username = form.cleaned_data['username']
password = form.cleaned_data['password1']
user = authenticate(request, username=username, password=password)
login(request, user)
messages.success(request, 'registration successfull....')
return redirect('home')
else:
form = UserCreationForm()
context = {'form': form}
return render(request, 'authenticate/register.html', context)
register.html

{% extends 'authenticate/base.html' %}
{% block content %}
<h2>Registration</h2>

<form method="POST" action="{% url 'register' %}">
{% csrf_token %}
{% if form.errors %}
<p>Your form has errors, please fix</p>
{% endif %}

{{ form }}
<input type="submit" value="Register" class="btn btn-secondary">
</form>
{% endblock %}
I think this should work like charm

Regards,
Amitesh Sahay


--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@ googlegroups.com.

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CAHLKn73wbZZiGubpZprphQt-ogdKVk-MKeabD4n3c5-8hDJhJg%40mail.gmail.com.
Reply all
Reply to author
Forward
0 new messages