Skip to content

Instantly share code, notes, and snippets.

@adamghill
Created January 3, 2014 21:20
Show Gist options
  • Star 27 You must be signed in to star a gist
  • Fork 5 You must be signed in to fork a gist
  • Save adamghill/8246816 to your computer and use it in GitHub Desktop.
Save adamghill/8246816 to your computer and use it in GitHub Desktop.
Show messages and errors in Django templates. Useful to just throw in a base template.
{% if messages %}
{% for message in messages %}
<div class="alert {% if message.tags %} alert-{{ message.tags }}{% endif %}">{{ message|safe }}</div>
{% endfor %}
{% endif %}
{% if form.errors %}
<div class="alert alert-error">
<h4>Please fix the following errors</h4>
<ul>
{% for field in form %}
{% if field.errors %}
{% for error in field.errors %}
<li><a href="#id_{{ field.name }}" class="error">{{ error|escape }}</a></li>
{% endfor %}
{% endif %}
{% endfor %}
</ul>
{% if form.non_field_errors %}
{{ form.non_field_errors }}
{% endif %}
</div>
{% endif %}
@deshwalmahesh
Copy link

What is the Views.py file for that?

def signup(request):
    if request.method=='POST':
        #form=UserCreationForm(request.POST)
        form =SignupForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect('login')
        else:
            err=form.errors
            return reverse('signup',{'err':err})
    else:
        form = SignupForm()
        #form=UserCreationForm()
    return render(request,'registration/signup.html',{'form':form})

there are errors on my webpage
either Unhashable type dict if I try passing the ```err`` dict

or the

'str' object has no attribute 'get' 

if I pass the simple return redirect ('signup')

@deshwalmahesh
Copy link

Found the template somewhere

{% extends 'blog/base.html' %}
{% block content %}
  <h2>Sign up</h2>
  <form method="post" >
    {% csrf_token %}
    {% 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 %}
    {{ form.as_p }}
      <button type="submit">Sign up</button>
  </form>
{% endblock %}

@MarceloPincheira
Copy link

what makes escape?

@adamghill
Copy link
Author

what makes escape?

It is a built-in filter: https://docs.djangoproject.com/en/3.1/ref/templates/builtins/#escape.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment