I needed some validation on a Django ModelForm field. So I changed 2 lines in my models.py (just below). The validation is blocking as necessary, but I can't find the proper way to display the ValidationError. Maybe there is a cleaner way to do this in the model form ?
models.py
class Lexicon(models.Model):
[...]
alphanumeric = RegexValidator(r'^[0-9a-zA-Z]*$', _('Only alphanumeric characters are allowed'))
filename = models.CharField(_("Filename"), max_length=40, validators=[alphanumeric])
forms.py
class LexiconForm(forms.ModelForm):
class Meta:
model = Lexicon
fields = ['filename', 'language', 'comment', 'alphabet', 'case_sensitive', 'diacritics']
views.py
#login_required
def new_pls_view(request):
if request.method == 'POST':
form = LexiconForm(request.POST)
if form.is_valid():
obj = form.save(commit=False)
obj.user = request.user
obj.save()
return redirect('pls_edit')
else:
form = LexiconForm()
return render(request, 'main/new_pls.html', {
'form': form,
})
template.html
<form class="form-horizontal" method="post" action="{% url 'new_pls' %}">
{% csrf_token %}
{% if form.non_field_errors %}
<div class="alert alert-danger" role="alert">
{% for error in form.non_field_errors %}
{{ error }}
{% endfor %}
</div>
{% endif %}
[...]
{% if form.is_bound %}
{% if form.filename.errors %}
{% for error in form.filename.errors %}
<div class="invalid-feedback">
{{ error }}
</div>
{% endfor %}
{% endif %}
{% if form.filename.help_text %}
<small class="form-text text-muted">{{ form.filename.help_text }}</small>
{% endif %}
{% endif %}
{% render_field form.filename type="text" class+="form-control" id="plsFilename" placeholder=form.filename.label %}
Replacing my entire form by {{ form }} as #Alasdair suggested is working, so I guess something is wrong with my template rendering.
I've simply replaced my error printing by this and the error prints!
<form class="form-horizontal" method="post" action="{% url 'new_pls' %}">
{% csrf_token %}
{{ form.non_field_errors }}
[...]
{{ form.filename.errors }}
{% render_field form.filename type="text" class+="form-control" id="plsFilename" placeholder=form.filename.label %}
Related
In Django forms, it can check whether the form is valid:
if form.is_valid():
return HttpResponseRedirect('/thanks/')
But I'm missing what to do if it isn't valid? How do I return the form with the error messages? I'm not seeing the "else" in any of the examples.
If you render the same view when the form is not valid then in template you can access the form errors using form.errors.
{% if form.errors %}
{% for field in form %}
{% for error in field.errors %}
<div class="alert alert-danger">
<strong>{{ error|escape }}</strong>
</div>
{% endfor %}
{% endfor %}
{% for error in form.non_field_errors %}
<div class="alert alert-danger">
<strong>{{ error|escape }}</strong>
</div>
{% endfor %}
{% endif %}
An example:
def myView(request):
form = myForm(request.POST or None, request.FILES or None)
if request.method == 'POST':
if form.is_valid():
return HttpResponseRedirect('/thanks/')
return render(request, 'my_template.html', {'form': form})
views.py
from django.contrib import messages
def view_name(request):
if request.method == 'POST':
form = form_class(request.POST)
if form.is_valid():
return HttpResponseRedirect('/thanks'/)
else:
messages.error(request, "Error")
return render(request, 'page.html', {'form':form_class()})
If you want to show the errors of the form other than that not valid just put {{form.as_p}} like what I did below
page.html
<html>
<head>
<script>
{% if messages %}
{% for message in messages %}
alert('{{message}}')
{% endfor %}
{% endif %}
</script>
</head>
<body>
{{form.as_p}}
</body>
</html>
UPDATE:
Added a more detailed description of the formset errors.
Form.errors combines all field and non_field_errors. Therefore you can simplify the html to this:
template
{% load form_tags %}
{% if form.errors %}
<div class="alert alert-danger alert-dismissible col-12 mx-1" role="alert">
<div id="form_errors">
{% for key, value in form.errors.items %}
<span class="fieldWrapper">
{{ key }}:{{ value }}
</span>
{% endfor %}
</div>
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
{% endif %}
If you want to generalise it you can create a list_errors.html which you include in every form template. It handles form and formset errors:
{% if form.errors %}
<div class="alert alert-danger alert-dismissible col-12 mx-1" role="alert">
<div id="form_errors">
{% for key, value in form.errors.items %}
<span class="fieldWrapper">
{{ key }}:{{ value }}
</span>
{% endfor %}
</div>
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
{% elif formset.total_error_count %}
<div class="alert alert-danger alert-dismissible col-12 mx-1" role="alert">
<div id="form_errors">
{% if formset.non_form_errors %}
{{ formset.non_form_errors }}
{% endif %}
{% for form in formset.forms %}
{% if form.errors %}
Form number {{ forloop.counter }}:
<ul class="errorlist">
{% for key, error in form.errors.items %}
<li>{{form.fields|get_label:key}}
<ul class="errorlist">
<li>{{error}}</li>
</ul>
</li>
{% endfor %}
</ul>
{% endif %}
{% endfor %}
</div>
</div>
{% endif %}
form_tags.py
from django import template
register = template.Library()
def get_label(a_dict, key):
return getattr(a_dict.get(key), 'label', 'No label')
register.filter("get_label", get_label)
One caveat: In contrast to forms Formset.errors does not include non_field_errors.
def some_view(request):
if request.method == 'POST':
form = SomeForm(request.POST)
if form.is_valid():
return HttpResponseRedirect('/thanks'/)
else:
form = SomeForm()
return render(request, 'some_form.html', {'form': form})
This answer is correct but has a problem: fields not defined.
If you have more then one field, you can not recognize which one has error.
with this change you can display field name:
{% if form.errors %}
{% for field in form %}
{% for error in field.errors %}
<div class="alert alert-danger">
<strong>{{ field.label }}</strong><span>{{ error|escape }}</strong>
</div>
{% endfor %}
{% endfor %}
{% for error in form.non_field_errors %}
<div class="alert alert-danger">
<strong>{{ error|escape }}</strong>
</div>
{% endfor %}
{% endif %}
#AamirAdnan's answer missing field.label; the other way to show the errors in few lines.
{% if form.errors %}
<!-- Error messaging -->
<div id="errors">
<div class="inner">
<p>There were some errors in the information you entered. Please correct the following:</p>
<ul>
{% for field in form %}
{% if field.errors %}<li>{{ field.label }}: {{ field.errors|striptags }}</li>{% endif %}
{% endfor %}
</ul>
</div>
</div>
<!-- /Error messaging -->
{% endif %}
simply you can do like this because when you initialized the form in contains form data and invalid data as well:
def some_func(request):
form = MyForm(request.POST)
if form.is_valid():
//other stuff
return render(request,template_name,{'form':form})
if will raise the error in the template if have any but the form data will still remain as :
error_demo_here
You can put simply a flag variable, in this case is_successed.
def preorder_view(request, pk, template_name='preorders/preorder_form.html'):
is_successed=0
formset = PreorderHasProductsForm(request.POST)
client= get_object_or_404(Client, pk=pk)
if request.method=='POST':
#populate the form with data from the request
# formset = PreorderHasProductsForm(request.POST)
if formset.is_valid():
is_successed=1
preorder_date=formset.cleaned_data['preorder_date']
product=formset.cleaned_data['preorder_has_products']
return render(request, template_name, {'preorder_date':preorder_date,'product':product,'is_successed':is_successed,'formset':formset})
return render(request, template_name, {'object':client,'formset':formset})
afterwards in your template you can just put the code below
{%if is_successed == 1 %}
<h1>{{preorder_date}}</h1>
<h2> {{product}}</h2>
{%endif %}
I got a question regarding the validation of a dynamically added inline formset in Django. It seems like I am missing something in my implementation.
Here is my case:
My project is a team management platform. A team is called Crew and can have several time Schedules. Each Schedule can have several Shifts. Please take a look at my code. At the moment I am able to create a schedule with several, dynamically added forms of the formset for the Shifts, if all fields are valid.
If not, the error for the Shift forms is not displayed and it is filled with the initial data again. It looks like the data of the shift forms is not bound after sending the POST request (because form.is_bound() is false). Moreover the data of Shift forms is not populated again after the POST request.
What do you think is the cause of this behaviour? Do I have to overwrite the is_valid function? I dont know, because it looks like the function works fine - the data is just not bound correctly to the new forms.
Views.py
def schedule_add(request, crew_id):
if request.method == "GET":
form = ScheduleForm()
ShiftFormSet = formset_factory(ShiftForm)
return render(request, 'schedule_add2.html', {'form': form, 'formset': ShiftFormSet, 'title':"Zeitplan hinzufügen"})
elif request.method == "POST":
form = ScheduleForm(request.POST)
numberOfShifts = int(request.POST['form-TOTAL_FORMS'])
ShiftFormSet = formset_factory(ShiftForm, extra=numberOfShifts)
shift_formset = ShiftFormSet(request.POST, prefix='form')
print(request.POST)
if form.is_valid() and shift_formset.is_valid():
schedule = Schedule()
schedule.name = form.cleaned_data.get('name')
schedule.crew = Crew.objects.get(pk=crew_id)
schedule.location = form.cleaned_data.get('location')
schedule.subperiod = form.cleaned_data.get('sub_period')
schedule.save()
for shift_form in shift_formset:
if shift_form.is_valid():
shift = Shift()
shift.min_user_count = shift_form.cleaned_data.get('min_user_count')
shift.max_user_count = shift_form.cleaned_data.get('max_user_count')
shift.start_datetime = shift_form.cleaned_data.get('start_time')
shift.end_datetime = shift_form.cleaned_data.get('end_time')
shift.schedule = schedule
shift.save()
messages.success(request, 'Zeitplan & Schichten angelegt.')
return redirect('shifter:crew_view', crew_id=crew_id)
else:
messages.error(request, 'Fehler')
return render(request, 'schedule_add2.html', {'form': form, 'formset': ShiftFormSet, 'title':"Zeitplan hinzufügen"})
else:
return redirect('shifter:index')
forms.py
class ScheduleForm(forms.ModelForm):
name = forms.CharField(max_length=30, required=True, help_text='', label="Name")
sub_period = forms.ModelChoiceField(queryset=SubPeriod.objects.all(), empty_label=None, label="Tag")
location = forms.ModelChoiceField(queryset=Location.objects.all(), empty_label=None, label="Einsatzort")
class Meta:
model = Schedule
fields = ('name', 'sub_period', 'location',)
class ShiftForm(forms.ModelForm):
min_user_count = forms.IntegerField(required=True, help_text='', label="Min Count", initial=2)
max_user_count = forms.IntegerField(required=True, help_text='', label="Max Count", initial=4)
start_time = forms.DateTimeField(required=True, help_text='', label="Shift start", initial=datetime.now)
end_time = forms.DateTimeField(required=True, help_text='', label="Shift end", initial=datetime.now)
class Meta:
model = Shift
fields = ('start_time','end_time','min_user_count','max_user_count',)
Template
<form method="post">
{% csrf_token %}
{% if form.non_field_errors %}
<div class="alert alert-danger" role="alert">
{% for error in form.non_field_errors %}
{{ error }}
{% endfor %}
</div>
{% endif %}
{% for field in form.visible_fields %}
{{ field.label_tag }}
{% if form.is_bound %}
{% if field.errors %}
{% render_field field class="form-control is-invalid" %}
{% for error in field.errors %}
<div class="invalid-feedback">
{{ error }}
</div>
{% endfor %}
{% else %}
{% render_field field class="form-control is-valid" %}
{% endif %}
{% else %}
{% render_field field class="form-control" %}
{% endif %}
{% if field.help_text %}
<small class="form-text text-muted">{{ field.help_text }}</small>
{% endif %}
{% endfor %}
<h2 class="mt-5">Shifts</h2>
<table class="table">
{{ formset.management_form }}
{% for form in formset.forms %}
{% if forloop.first %}
<thead>
<tr>
{% for field in form.visible_fields %}
<th>{{ field.label|capfirst }}</th>
{% endfor %}
<th></th>
</tr>
</thead>
{% endif %}
<tr class="formset_row">
{% for field in form.visible_fields %}
<td>
{# Include the hidden fields in the form #}
{% if forloop.first %}
{% for hidden in form.hidden_fields %}
{{ hidden }}
{% endfor %}
{% endif %}
{% if form.is_bound %}
{% if form.errors %}
{% render_field field class="form-control is-invalid" %}
{% for error in form.errors %}
<div class="invalid-feedback">
{{ error }}
</div>
{% endfor %}
{% else %}
{% render_field field class="form-control is-valid" %}
{% endif %}
{% else %}
{% render_field field class="form-control" %}
{% endif %}
</td>
{% endfor %}
<td></td>
</tr>
{% endfor %}
</table>
<button type="submit" class="btn btn-primary">Save</button>
</form>
Thanks in advance,
Christopher
You're returning the class, ShiftFormSet, to the template (in the third-from-last line of your code) instead of the instance, shift_formset.
I'm trying to rewrite my function based view to class based view. It raises this error:
.../test/User1
'UserDetailView' object has no attribute 'rindex'
The problem is probably obvious, I'm new in class based views.
So what to do to be able get any profile using url .../test/username?
My new view:
class UserDetailView(DetailView):
model = User
def get_object(self, queryset=None):
return get_object_or_404(self.model, pk=self.kwargs["pk"])
URLS.PY:
url(r'^test/(?P<username>[a-zA-Z0-9]+)/$', views.UserDetailView(),name="user_detail"),
And template:
{% extends "base.html" %}
{% block content %}
{{ userprofile.as_p }}
{% endblock %}
My old view is this:
def get_user_profile(request, username):
user = User.objects.get(username=username)
jobs = user.jobs.all()
table = MyJobsTable(jobs)
context = {
'my_jobs': table,
"user": user
}
return render(request, 'auth/profiles/my-profile.html', context=context)
And HTML:
{% extends 'base.html' %}
{% load crispy_forms_tags %}
{% load render_table from django_tables2 %}
{% block content %}
{% if user.is_authenticated %}
<h3>{% if user.userprofile.is_translator %} Prekladateľský účet: {% else %} Štandardný
účet: {% endif %}{{ user.username }} </h3>
<ul>
<li>Username: {{ user.username }}</li>
<li>First name: {{ user.first_name }}</li>
<li>Last name: {{ user.last_name }}</li>
<li>Email: {{ user.email }}</li>
<li>Telephone: {{ user.userprofile.telephone }}</li>
<li>Languages: {{ user.userprofile.languages.as_p }}</li>
{# TODO: DOPLNIT ATRIBUTY + ked je aj translator#}
</ul>
{% if user.jobs %}
<p>My Jobs</p>
{% render_table my_jobs %}
{% else %}
<p>You have no jobs</p>
{% endif %}
<form class="navbar-form navbar-right" action="/edit-profile" method="get">
<button type="submit" class="btn btn-success">Edit Your Profile</button>
</form>
<form class="navbar-form navbar-right" action="/register-as-translator" method="get">
<button type="submit" class="btn btn-success">Become A Translator</button>
</form>
{% endif %}
{% endblock %}
URLS.PY:
url(r'^profile/(?P<username>[a-zA-Z0-9]+)/$', views.get_user_profile)
The issue is in your urls.py. With a class-based view, you always need to use the as_view classmethod:
url(r'^test/(?P<username>[a-zA-Z0-9]+)/$', views.UserDetailView.as_view(), name="user_detail"),
I'm attempting to set up a Django Form Wizard, but I'm having trouble getting it to work. I've followed the example, from the Django website, but can't get anything to work. When I go to the URL that should have my multistep form, only the template html thats extended shows up. What am I doing wrong here?
FORMS.PY
class ScheduleDate(forms.Form):
date = forms.CharField()
class ScheduleTime(forms.Form):
time = forms.CharField()
VIEWS.PY
FORMS =[('date', ScheduleDate),
('time', ScheduleTime)]
TEMPLATES = [('date', 'main/schedule_date2.html'),
('time', 'main/schedule_time.html')]
class ContactWizard(SessionWizardView):
def get_template_name(self):
return TEMPLATES[self.steps.current]
def done(self, form_list, **kwargs):
print 'testing'
return HttpResponseRedirect('main/home.html')
URLS.PY
urlpatterns = patterns('',
url(r'^checkout/$', views.ContactWizard.as_view([ScheduleDate, ScheduleTime]), name='checkout'))
SCHEDULE_DATE2.HTML(From the Django Website)
{% extends "base.html" %}
{% load i18n %}
{% block head %}
{{ wizard.form.media }}
{% endblock %}
{% block content %}
<p>Step {{ wizard.steps.step1 }} of {{ wizard.steps.count }}</p>
<form action="" method="post">{% csrf_token %}
<table>
{{ wizard.management_form }}
{% if wizard.form.forms %}
{{ wizard.form.management_form }}
{% for form in wizard.form.forms %}
{{ form }}
{% endfor %}
{% else %}
{{ wizard.form }}
{% endif %}
</table>
{% if wizard.steps.prev %}
<button name="wizard_goto_step" type="submit" value="{{ wizard.steps.first }}">{% trans "first step" %}</button>
<button name="wizard_goto_step" type="submit" value="{{ wizard.steps.prev }}">{% trans "prev step" %}</button>
{% endif %}
<input type="submit" value="{% trans "submit" %}"/>
</form>
{% endblock %}
Thanks!
I have a single HTML page with 2 Django Forms in it, all in the same <form>..</form> tag. Everything works great, except when I try to upload multiple files.
Each form has their own image, and for some reason I can only save the image from the first form. Other data from the second form still gets saved, but without any image. I don't see any errors or exception raised, so I don't know what's going wrong :s.
Here's my views.py
def display_form(request):
if request.method == 'POST':
form_team = TeamForm(request.POST, request.FILES, prefix="team")
form_player = PlayerForm(request.POST, request.FILES, prefix="play")
#form_ketua = KetuaForm(request.POST, request.FILES, prefix="ketua")
if all([form.is_valid() for form in [form_team, form_player]]):
# save Team data first, overwrite if exists
try:
team = Team.objects.get(kota=form_Team.cleaned_data['name'])
team.profil = form_Team.cleaned_data['profil']
team.save()
except Team.DoesNotExist:
team = Team(**form_Team.cleaned_data)
team.save()
play = form_Player.save(commit=False)
play.name = team
play.save()
else:
form_team = TeamForm(prefix="team")
form_player = PlayerForm(prefix="play")
#form_ketua = KetuaForm(prefix="ketua")
print "a"
# list with tuple (form, legend) to pass as context
forms = [(form_Team, 'Team Data'),
(form_Player, 'Player Profile'),
]
return render_to_response(
'form/team.html',
{
'formlist': forms,
},
)
What am I doing wrong?
EDIT: Here's my template
{% extends "base.html" %}
{% block title %}Form - {{ title }}{% endblock %}
{% block content %}
<form action="." method="POST" enctype="multipart/form-data">{% csrf_token %}
{% for formitem in formlist %}
{% if formitem.1 %}
<fieldset>
<legend>{{ formitem.1 }}</legend>
{% endif %}
{{ formitem.0.non_field_errors }}
{% for field in formitem.0.visible_fields %}
<div class="formfield">
{{ field.errors }}
{{ field.label_tag }} {{ field }}
</div>
{% endfor %}
{% if formitem.1 %}
</fieldset>
{% endif %}
{% endfor %}
<div id="formbuttons">
<input type="submit" value="Submit" class="button">
<input type="reset" value="Reset" class="button">
</div>
</form>
{% endblock %}
looks like you are missing a play.save() (you save the form with commit=False)