Form error doesnt display on template? - django

When I enter an invalid email adress I cant see an error message like "This is not an invalid email".
My comment_form.html:
{% load i18n %}
<form action="/comment/create/" method="post">
{% csrf_token %}
{{ form.errors }}
{% for field in form %}
<div class="fieldWrapper">
{{ field.label_tag }}
{{ field }}<p>
</div>
{% endfor %}
<input type="hidden" name = "object_id" value="{{object_id}}" />
<input type="hidden" name= "next" value="{{ next }}" />
<input type="submit" value="{% trans "Submit" %}">
</form>
my post_detail.html:
extends "base.html" %}
{% block content %}
<div id="exap">
{{ post.content }}
</div>
<div class="comment">
{% for comment in comments %}
<user>{{ comment.owner }}</user>
{{ comment.content}}
{% endfor %}
</div>
{% include "comment_form.html" %}
{% endblock %}
this is my comment.views
def create(request):
if request.method == 'POST':
form = CommentForm(request.POST)
email = request.POST.get('email')
next = request.POST.get('next')
if form.is_valid():
content_type = ContentType.objects.get(app_label="post", model="post")
object_id = request.POST["object_id"]
comment = Comment.objects.create(
content_type = content_type,
object_id = object_id,
content = request.POST.get('content'),
owner= request.POST.get('owner'),
email = request.POST.get('email')
)
else:
print form.errors
else:
form = CommentForm()
return HttpResponseRedirect(next)
Error message doesnt display in template ?
Where am I wrong ?

karthikr is trying to tell you what is wrong in the comments. You are not using the form to validate, so it won't show any errors. Instead of doing if validateEmail(email) you should have the email validation code inside the form class, and in the view you call if form.is_valid().
Plus, when you do write the form's clean_email method, you should not be catching ValidationError: that's the way that errors are passed on to the form's errors list.

Related

Unable to see error messages in registration template. Django

Good afternoon Community,
I hope you are all well.
I am building my first website and I have the following problem; when I try to create a new user, if the user enters the wrong data the template does not show the error. Any hints?
Template:
<form action= "" method='post'>
{% csrf_token %}
{% for field in form %}
<p>{{field.label}}{{field}}</p>
{% endfor %}
<button type="submit" class="btn btn-success">Create User</button>
Views.py:
def register_page(request):
form = UserForm
if request.method == 'POST':
form = UserForm(request.POST)
if form.is_valid():
form.save()
return HttpResponseRedirect('http://127.0.0.1:8000/login_user/')
context = {'form' : form}
return render(request, 'simple_investing/register.htm', context)
Forms.py:
class UserForm(UserCreationForm):
class Meta:
model = User
fields = ('username', 'email', 'password1', 'password2')
As is discussed in the rendering fields manually section of the documentation, for the fields you should also render {{ field.errors }}, and the {{ form.non_field_errors }} which deals with errors not specific to one form.
The template thus should look like:
<form action= "" method="post">
{% csrf_token %}
{{ form.non_field_errors }}
{% for field in form %}
<p>
{{ field.errors }}
{{ field.label }}
{{ field }}
</p>
{% endfor %}
<button type="submit" class="btn btn-success">Create User</button>
</form>
The section also discusses how to enumerate over the errors, and apply certain styling to these errors.

How to show django form in django template?

I am trying to create a form using django and css.
views.py
from django.shortcuts import render
from .forms import ContactForm
def home(request):
if request.method == 'POST':
form = ContactForm(request.POST)
if form.is_valid():
pass
else:
form = ContactForm()
return render(request, 'home.html', {'form':form})
forms.py
from django import forms
class ContactForm(forms.Form):
name = forms.CharField(max_length = 30)
email = forms.EmailField(max_length = 254)
message = forms.CharField(max_length = 2000, widget = forms.Textarea(),help_text = "Write Your Message here")
def clean(self):
cleaned_data = super(ContactForm, self).clean()
name = cleaned_data.get('name')
email = cleaned_data.get('email')
message = cleaned_data.get('message')
if not name and not email and not message:
raise forms.ValidationError('You have to write something!')
When I try to add the form to my html page like the following it doesn't show up. Just the button shows up, no form fields -
{% extends 'store/main.html' %}
{% load static %}
{% block content %}
<h3>Store</h3>
<form method = "post" novalidate>
{% csrf_token %}
{{ form }}
<button type='submit'>Submit</button>
</form>
{% endblock content %}
If I do css form instead it obviously show up the way it should.
{% extends 'store/main.html' %}
{% load static %}
{% block content %}
<h3>Store</h3>
<form>
<label for="fname">First Name</label>
<input type="text" id="fname" name="fname">
<button type='submit'>Submit</button>
</form>
{% endblock content %}
So I decided to add the form fields individually to the css form. Where does the {{form.name}} or {{form.email}} tag go?
EDIT:
Hey Vivek, the contact form code is this -
class ContactForm(forms.Form):
name = forms.CharField(max_length = 30)
email = forms.EmailField(max_length = 254)
message = forms.CharField(max_length = 2000, widget = forms.Textarea(),help_text = "Write Your Message here")
The html template looks like this-
{% extends 'store/main.html' %}
{% load static %}
{% block content %}
<h3>Store</h3>
<form method = "post" novalidate>
{% csrf_token %}
<label class="float-left" for="name">Name</label>
{{ form.name }}
<button type='submit'>Submit</button>
</form>
{% endblock content %}
Thanks for any input.
Accessing form fields individually will make you to render the form errors individually as well. {{form}} encapsulates everything:- Form fields , errors, non_field_errors..So if you have to access the fields individually do not forget to add the form errors.
I have written a sample code which will server the purpose.
{% csrf_token %}
{% if form.errors %}
<div class="alert alert-danger" style="text-align:left">
<ul>
{% for field in form %}
{% for error in field.errors %}
<li><strong>{{ error|escape }}</strong></li>
{% endfor %}
{% endfor %}
{% for error in form.non_field_errors %}
<li><strong>{{ error|escape }}</strong></li>
{% endfor %}
</ul>
</div>
{% endif %}
<div class="form-row">
<div class="col-md-4 mb-3">
<label class="float-left" for="id_name">Name</label>
{{ form.name }}
</div>
<div class="col-md-8 mb-3">
<label class="float-left" for="id_email">Email ID</label>
{{ form.email }}
</div>
</div>
<br>
<input type="submit" class="btn btn-primary" value="Pay" id="submit">
</form>

django form error messages not showing

So I have my view:
def home_page(request):
form = UsersForm()
if request.method == "POST":
form = UsersForm(request.POST)
if form.is_valid():
form.save()
c = {}
c.update(csrf(request))
c.update({'form':form})
return render_to_response('home_page.html', c)
my forms.py:
class UsersForm(forms.ModelForm):
class Meta:
model = Users
widgets = {'password':forms.PasswordInput()}
def __init__(self, *args, **kwargs):
super( UsersForm, self ).__init__(*args, **kwargs)
self.fields[ 'first_name' ].widget.attrs[ 'placeholder' ]="First Name"
self.fields[ 'last_name' ].widget.attrs[ 'placeholder' ]="Last Name"
self.fields[ 'password' ].widget.attrs[ 'placeholder' ]="Password"
and my template:
<html>
<body>
<form method="post" action="">{% csrf_token %}
{{ form.first_name }} {{form.last_name }} <br>
{{ form.password }} <br>
<input type="submit" value="Submit Form"/>
</form>
{% if form.errors %}
{% for field in form %}
{% for error in field.errors %}
<p> {{ errors }} </p>
{% endfor %}
{% endfor %}
{% for error in form.non_field_errors %}
<p> {{ error }} </p>
{% endfor %}
{% endif %}
</body>
</html>
Now, keep in mind that before I split the form field, my form just looked like this:
<form method="post" action="">{% csrf_token %}
{{ form }}
<input type="submit" value="Submit Form"/>
</form>
and if the form had a problem (like if one of the fields was missing) it would automatically give an error message. After I split up the form fields in the template (made {{ form.first_name }}, {{ form.last_name }} and {{ form.password }} their own section) it stopped automatically giving error messages. Is this normal?
But the main problem is, how come my {{ if form.errors }} statement is not working / displaying error messages if there are error messages? For example, if I purposely not fill out a field in the form and I click submit, the database does not get updates (which is a good thing) but it does not give any error messages. Any idea why?
I also tried remove the {{ forms.non_field_errors }} and tried to return just field errors like so:
{% if form.errors %}
{% for field in form %}
{% for error in field.errors %}
<p> {{ errors }} </p>
{% endfor %}
{% endfor %}
{% endif %}
but it still doesn't work.
I found the mistake (typo).
The snippet should be:
{% if form.errors %}
{% for field in form %}
{% for error in field.errors %}
<p> {{ error }} </p>
{% endfor %}
{% endfor %}
{% endif %}
I had errors instead of error.
you have to send your form context again if is_valid() isn't true,
if form.is_valid():
return redirect('/user/contact/')
else:
return render(request, 'users/contact.html', context={'form': form})
because your errors will display in your form
else: it will return ValueError
Add this snippets in views.py like this
if request.method == "POST":
fm = UserRegsitrationForm(request.POST)
if fm.is_valid():
fm.save()
else:
fm = UserRegsitrationForm()
context = {'fm':fm}
return render(request,'registration.html',context)
The error capture could very well have been done with:
{% for field in form %}
{{ field.errors }}
{% endfor %}

django modelformset_factory - management form data is missing

I am still fighting with formsets and I cant really understand why I am getting this error:
u'ManagementForm data is missing or has been tampered with
Thats my code:
Please point out my mistakes and help me with resolving this issue.
#csrf_protect
#transaction.commit_on_success
def signup(request):
form = NewUserCreationForm()
doc_form = NewDocRegisterForm()
SpecialityLicensesFormSet = modelformset_factory(SpecialityLicenses, extra=1, exclude = ('user'))
formset = SpecialityLicensesFormSet(queryset=SpecialityLicenses.objects.none())
if request.method == "POST":
form = NewUserCreationForm(request.POST or None)
doc_form = NewDocRegisterForm(request.POST or None)
formset = SpecialityLicensesFormSet(request.POST or None)
if form.is_valid() and doc_form.is_valid() and formset.is_valid():
user = form.save()
doc = doc_form.save(commit=False)
doc.user = user
doc.save()
print formset
fset = formset.save(commit=False)
for n in fset:
n.user = user
n.save()
return HttpResponse("Uzytkownik utowrzony")
return render_to_response("userena/signup_new.html", {'form': form,
'doc_form': doc_form,
'spec_form': formset,},
context_instance=RequestContex
t(request))
Template code:
<form action="/en/accounts/doc_register/" method="post">{% csrf_token %}
{% for field in form %}
<div>
{% if field.errors %}
{{ field.errors|striptags }} |
{% endif %}
{{field.label}} | {{ field}}
</div>
{% endfor %}
<hr>
{% for f in doc_form %}
<div>
{% if f.errors %}
{{f.errors|striptags}} |
{% endif %}
{{f.label}} : {{ f }}
</div>
{% endfor %}
<hr>
{{ spec_form.management_form }}
{{ spec_form }}
<hr>
<input type="submit" value="Submit"/>
</form>
{% endblock %}
you don't need to do {{ formset.management_form }} if you do {{ formset }}, just if you do
{{ formset.management_form }}
{% for form in formset %}
{{ form }}
{% endfor %}
try removing the {{ spec_form.management_form }} bit from your template. Look at the third example
add prefix for formset if prefix is missing for formset it will give error

django - form has no errors but form.is_valid() doesn't validate

I have a form that for some reason it it doesn't throw any errors (if user adds data in the text field) but form.is_valid() doesn't validate. Any ideas?
forms.py:
class MyForm(forms.Form):
title = forms.CharField(widget=forms.TextInput(attrs={'class':'titleField'))
mytemplate.html
<form action="" method="post" name="form">{% csrf_token %}
{{ form.title.errors }}
{{ form.title }}
<input type="submit" name='submit_button' value="Post" />
</form>
views.py:
if 'submit_button' in request.POST:
form = MyForm(request.POST)
if form.is_valid():
cd = form.cleaned_data
title = cd['title']
g = MyData(title='title')
g.save()
else:
form = MyForm()
From your template, add the following:
{{ form.errors }}
{{ form.non_field_errors }}
Do you see any errors from the above?
You can also print (or log) error at back end too, Similarly use this:
Like, to print error:
print(form.errors)
I'm using this block with bootstrap
{% if form.errors %}
<div class="alert alert-danger" role="alert">
{% for field, errors in form.errors.items %}
{% for error in errors %}
<b>{{ field }}</b>: {{ error }}
{% endfor %}
{% endfor %}
</div>
{% endif %}