how to display form.errors message properly in django - django

here with this code the form errors are not displaying properly.The all error messages says, this field is required only.how can i define my custom form.error message in the template.
template
{% if form.errors %}
{% for field in form %}
{% for error in field.errors %}
<p> {{ error }} </p>
{% endfor %}
{% endfor %}
{% endif %}
<div class="form-group">
<h5>Full Name <span class="text-danger">*</span></h5>
<div class="controls">
<input type="text" name="name" class="form-control" title="Full Name is required" > </div>
</div>
<div class="form-group">
<h5>Courses<span class="text-danger">*</span></h5>
<div class="controls">
{% for course in courses %}
<input name ="courses" type="checkbox" id="course-{{course.id}}" value="{{course.id}}" autofocus title="Please Check at least one course">
<label for="course-{{course.id}}">{{course.title}}</label>
{% endfor %}
</div>
</div>
views.py
if request.method == 'POST':
form = AddStudentForm(request.POST, request.FILES)
if form.is_valid():
student = form.save(commit=True)
student.save()
messages.success(request, 'student with name {} added.'.format(student.name))
return redirect('admin:add_student')
else:
form = AddStudentForm()
return render(request, 'admin/add_student.html', {'form': form})

in your views.py pass the form with errors like this
if request.method == 'POST':
form = AddStudentForm(request.POST, request.FILES)
if form.is_valid():
student = form.save(commit=True)
student.save()
messages.success(request, 'student with name {} added.'.format(student.name))
return redirect('admin:add_student')
return render(request, 'admin/add_student.html', {'form': form})
else:
form = AddStudentForm()
return render(request, 'admin/add_student.html', {'form': form})
That means you should remove the else part
and in your template code
{% if form.errors %}
<div class="alert alert-danger">
{{ form.errors }}
</div>
{% endif %}
Updated the answer to get proper answer when you load the view first time

Related

Django Forms Invalid but no Errors

Maybe it might be an oversight but I do not know the point where I am getting it wrong.
My form is rendered correctly but it keeps failing without errors.
forms.py
from crispy_forms.helper import FormHelper
from django import forms
from django.utils.translation import ugettext as _
class BeneficiaryForm(forms.Form):
"""Add Beneficiary template form"""
# Form fields
account_currency = forms.ModelChoiceField(queryset=Currency.objects.all(), empty_label=_('Select account currency'))
bank_account_type = forms.CharField(max_length=50, required=False)
email = forms.CharField(max_length=150, required=False, help_text=_("We'll notify them when a transfer is made"))
name = forms.CharField(max_length=50, required=False)
swift_code = forms.CharField(max_length=11, required=False,
widget=forms.TextInput(attrs={'placeholder': 'MSBCCNBJ001'}))
iban = forms.CharField(max_length=34)
def __init__(self, *args, **kwargs):
super(BeneficiaryForm, self).__init__()
self.helper = FormHelper()
self.helper.form_show_labels = False
views.py
def beneficiaries(request):
"""View function for viewing Beneficiaries and adding a Beneficiary instance"""
if request.method == 'POST':
form = BeneficiaryForm(request.POST)
if form.is_valid():
print("Form is valid")
print(request.POST['bank_account_type'])
print(request.POST['email'])
print(request.POST['name'])
print(request.POST['iban'])
print(request.POST['swift_code'])
print("Form is invalid")
print(form.errors)
form = BeneficiaryForm()
context = {
'form': form
}
return render(request, 'dashboard/beneficiaries.html', context)
and in my rendered form. I have this block to show errors and nothing shows up
HTML
<form action="{% url 'beneficiary_index' %}" method="post">
{% csrf_token %}
{% if form.errors %}
{% for field in form %}
{% for error in field.errors %}
<div class="alert alert-danger">
{% if field != '__all__' %}
<strong>{{ field.label }}:</strong>
{% endif %}
{{ error|escape}}
</div>
{% endfor %}
{% endfor %}
{% endif %}
<div class="form-group">
<div class="form-label-group">
<label class="form-label" for="default-01">{% trans "Account currency" %}</label>'
</div>
{{ form.account_currency | as_crispy_field }}
</div>
<div class="form-group">
<div class="form-label-group">
<label class="form-label" for="default-01">{% trans "Bank Account type" %}</label>
</div>
{{ form.bank_account_type | as_crispy_field }}
</div>
<div class="form-group">
<div class="form-label-group">
<label class="form-label" for="default-01">Their email(optional)</label>
</div>
{{ form.email | as_crispy_field }}
</div>
<div class="form-group">
<div class="form-label-group">
<label class="form-label" for="default-01">Full name of account holder</label>
</div>
{{ form.name | as_crispy_field }}
</div>
<h6>{% trans "Recipient Bank Information" %}</h6>
<hr>
<div class="form-group">
<div class="form-label-group">
<label class="form-label" for="default-01">Swift code</label>
</div>
{{ form.swift_code | as_crispy_field }}
</div>
<div class="form-group">
<div class="form-label-group">
<label class="form-label" for="default-01">IBAN</label>
</div>
{{ form.iban | as_crispy_field }}
</div>
<div class="form-group">
<button class="btn btn-lg btn-primary btn-block">{% trans 'Add Beneficiary' %}</button>
</div>
</form>
This is the Html to the form. I have just tried all the suggestions and still without the errors.
Form is Invalid is the only thing printed on screen without the form.errors
You need to create the GET request empty form in the else block or return the request in the POST block.
You are re-creating an empty form before returning the response.
def beneficiaries(request):
"""View function for viewing Beneficiaries and adding a Beneficiary instance"""
if request.method == 'POST':
form = BeneficiaryForm(request.POST)
if form.is_valid():
print("Form is valid")
print(request.POST['bank_account_type'])
print(request.POST['email'])
print(request.POST['name'])
print(request.POST['iban'])
print(request.POST['swift_code'])
# do other stuff like saving to DB
# then redirect
else:
print("Form is invalid")
print(form.errors)
elif request.method == 'GET':
form = BeneficiaryForm()
else:
# maybe return 404
pass
context = {
'form': form
}
return render(request, 'dashboard/beneficiaries.html', context)
Or maybe you can try Class Based Views, to avoid the if-else block for GET and POST requests.
Try adding this to the place you want the error to appear (In the HTML file)
Better if you use it inside the tags.
{% if form.errors %}
<p>Form is invalid</p>
{% endif %}
I Hope this answers the question.

Django form keeps complaining required field

The form submits but immediately says this field is required... although it was filled out. What am I doing wrong
In my view:
def fileupload(request):
if request.user.is_authenticated and request.user.is_staff:
if request.method == 'POST':
form = UploadFileForm(request.POST, request.FILES)
if form.is_valid():
handle_uploaded_file(request.FILES.getlist('file_field'))
return HttpResponseRedirect('/fileupload/')
else:
form = UploadFileForm()
return render(request, 'fileupload.j2.html', {'form': form})
return HttpResponseForbidden('<h1>403 Forbidden</h1>')
with this form:
class UploadFileForm(forms.Form):
kit_number = forms.CharField(label="Kit number", max_length=100, required=True, help_text='Required.')
file_field = forms.FileField(label='Upload kit result')
and template:
{% extends "menu.j2.html" %}
{% block content %}
{% if request.user.is_authenticated and request.user.is_staff %}
<h3>File upload</h3><br><br>
<form action="/fileupload/" method="post">
{% csrf_token %}
<div class="form-group">
<table>
{{ form.as_table() }}
</table>
</div>
<input id="button" class="btn" type="submit" value="Sent">
</form>
{% else %}
You are not authorized to see this page
{% endif %}
{% endblock %}
You forgot to set the form enctype.
<form action="/fileupload/" method="post" enctype="multipart/form-data">

PasswordChangeForm with Abstractuser not responsive on submit

I have a custom user model
class User(AbstractUser):
company = models.CharField(max_length=30, blank=True)
When I try to change my password using the ChangePasswordForm, upon submit, nothing happens.
#login_required
def change_password(request):
if request.method == 'POST':
form = PasswordChangeForm(data=request.POST, user=request.user)
if form.is_valid():
form.save()
update_session_auth_hash(request, form.user)
return redirect('/account/profile')
else:
form = PasswordChangeForm(request.user)
args = {'form': form}
return render(request, 'accounts/change_password.html', args)
change_password.html
{% extends 'base.html' %}
{% block head %}
{% endblock %}
{% load crispy_forms_tags %}
{% crispy form form.helper %}
{% block body %}
<div class="container-fluid">
<div class="card">
<div class="card-body">
<h3>Change password</h3><br>
<form method="post">
{% csrf_token %}
{% crispy form %}
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</div>
</div>
</div>
{%endblock%}
This was working before with a regular usermodel
hope someone can help.

Validation errors not showing up

So I'm stuck on why validation errors aren't showing for this particular form. They are showing up fine on all my other forms, but not this one.
I can empirically see the validation at work because when office_street_address is none, the form is not saving. But the form.non_field_error doesn't seem to have any errors.
forms
class PremiumAgentForm(forms.ModelForm):
class Meta:
model = Agent
exclude = ['field1', 'field2', ...]
def __init__(self, *args, **kwargs):
super(PremiumAgentForm, self).__init__(*args, **kwargs)
for visible in self.visible_fields():
visible.field.widget.attrs['class'] = 'form-control'
def clean(self):
cd = super(PremiumAgentForm, self).clean()
a = cd.get('office_street_address')
if a == None:
raise forms.ValidationError("Error")
return cd
html
<form class="row justify-content-center" enctype="multipart/form-data" method="post">
{% csrf_token %}
{% for error in form.non_field_errors %}
<p style="color: red">{{ error }}</p>
{% endfor %}
{% if form.non_field_errors %}
<p style="color: red">there are errors</p>
{% else %}
<p>no errors</p> # This is always displayed.
{% endif %}
<div class="col-sm-4">
{% for field in form %}
<div class="form-group pb-3">
{% for error in field.errors %}
<p style="color: red">{{ error }}</p>
{% endfor %}
{{ field.label_tag }}
{{ field }}
{% if field.help_text %}
<small class="form-text text-muted">{{ field.help_text|safe }}</small>
{% endif %}
</div>
{% endfor %}
<button class="button2"><span>Submit</span></button>
</div>
</form>
views.py
def edit_profile(request):
if request.method == 'POST':
form = PremiumAgentForm(request.POST, request.FILES, instance=agent)
if form.is_valid():
form.save()
return HttpResponseRedirect(request.META['HTTP_REFERER'])
else:
agent = get_object_or_404(Agent, pk=request.user.agent.pk)
form = PremiumAgentForm(instance=agent)
return render(request, 'edit_profile.html', {'form': form})
In your case, you keep the form if it is valid, and after that you do a redirect, even if the form is not valid. This should help:
if not form.is_valid():
return render(request, 'edit_profile.html', {'form': form})
form.save()

Form error doesnt display on template?

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.