2

Originally I made a script in PHP and because I put html in .php file it was easy to show a message when adding data to database was done.

Now I'd like to do the same in Django. I have simple form, and view that add the data. And when adding is done I want to display some div with information below the "send" button, so I don't want to load any other template. I want to show message in the same template where is my form.

Is it possible to do without ajax? How to do this?

4 Answers 4

6

Django has inbuilt messaging support for this type of flash messages.

You can add a success message like this in the view:

messages.success(request, 'Profile details updated.')

In your template, you can render it as follows:

{% if messages %}
<ul class="messages">
    {% for message in messages %}
    <li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li>
    {% endfor %}
</ul>
{% endif %}

This is documented in this link: https://docs.djangoproject.com/en/1.8/ref/contrib/messages/

Sign up to request clarification or add additional context in comments.

2 Comments

Is it possible to show messages in different places? I mean positive message below send button, negative message above header, etc.
Messages have tags which can be got from {{ message.tags }} in the for loop. This will be the string like 'success' or 'failure'. You can use this to modify css styling in the template. More info here docs.djangoproject.com/en/1.8/ref/contrib/messages/…
2

If you are using class based views, then use the already implemented mixin

from django.contrib.messages.views import SuccessMessageMixin
from django.views.generic.edit import CreateView
from myapp.models import Author

class AuthorCreate(SuccessMessageMixin, CreateView):
    model = Author
    success_url = '/success/'
    success_message = "%(name)s was created successfully"

Comments

0

How about passing a variable to the template ?

(@ views.py)

return render(request, "some_app/some_template.html", context={
        'sent': True
    })

and then somewhere in (@ some_template.html)

{% if sent %}
<div> blah blah</div>
{% endif %}

Edit: fixed typos :/

Comments

0

Here's a basic version using a class based view for a contact page. It shows a success message above the original form.

mywebapp/forms.py

### forms.py
from django import forms

class ContactForm(forms.Form):
    contact_name = forms.CharField(label='Your Name', max_length=40, required=True)
    contact_email = forms.EmailField(label='Your E-Mail Address', required=True)
    content = forms.CharField(label='Message', widget=forms.Textarea, required=True)

mywebapp/views.py

### views.py
from django.contrib.messages.views import SuccessMessageMixin
from django.core.mail import EmailMessage
from django.core.urlresolvers import reverse_lazy
from django.template.loader import get_template
from django.views.generic import TemplateView, FormView
from mywebapp.forms import ContactForm

class ContactView(SuccessMessageMixin, FormView):
    form_class = ContactForm
    success_url = reverse_lazy('contact')
    success_message = "Your message was sent successfully."
    template_name = 'contact.html'

    def form_valid(self, form):
        contact_name = form.cleaned_data['contact_name']
        contact_email = form.cleaned_data['contact_email']
        form_content = form.cleaned_data['content']
        to_recipient  = ['Jane Doe <[email protected]>']
        from_email = 'John Smith <[email protected]>'
        subject = 'Website Contact'

        template = get_template('contact_template.txt')
        context = {
            'contact_name': contact_name,
            'contact_email': contact_email,
            'form_content': form_content
        }
        content = template.render(context)

        email = EmailMessage(
            subject,
            content,
            from_email,
            to_recipient,
            reply_to=[contact_name + ' <' +contact_email + '>'],
        )
        email.send()
        return super(ContactView, self).form_valid(form)

templates/contact.html

### templates/contact.html
{% extends 'base.html' %}
{% block title %}Contact{% endblock %}
{% block content %}

{% if messages %}
<ul class="messages">
    {% for message in messages %}
    <li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li>
    {% endfor %}
</ul>
{% endif %}

<form role="form" action="" method="post">
    {% csrf_token %}
    {{ form.as_p }}
    <button type="submit">Submit</button>
</form>
{% endblock %}

templates/contact_template.txt

### templates/contact_template.txt
### used to render the body of the email

Contact Name: {{contact_name}}
Email: {{contact_email}}
Content: {{form_content}}

config/urls.py

### config/urls.py
from mywebapp.views import *
urlpatterns = [
    url(r'^about/', AboutView.as_view(), name='about'),
    url(r'^contact/$', ContactView.as_view(), name='contact'),
    url(r'^$', IndexView.as_view()),
]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.