Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to send success message if we use django generic views

I am new to django (1.2.4). I have created some crud with generic views. But How can I show something like "The student was added successfully" when student is created using django's messaging framework?

like image 374
Myth Avatar asked Jan 26 '11 08:01

Myth


People also ask

Should I use generic views Django?

The intention of Generic Views is to reduce boilerplate code when you repeatedly use similar code in several views. You should really use it just for that. Basically, just because django allows something you are doing generically you shouldn't do it, particularly not when your code becomes not to your like.

How do you use messages in class-based view of Django?

models import CreateEmployer from django. views. generic import CreateView class SignUpView(CreateView): model = CreateEmployer template_name = 'employee/register_employee. html' fields = '__all__' # this method will enable your message to display # you can also use it to overwrite form data.

How do I send a message in Django?

Adding a message To add a message, call: from django. contrib import messages messages. add_message(request, messages.INFO, 'Hello world.

How do I show messages in Django template?

To display alert messages in Django, (1) check that the settings are configured properly, (2) add a message to a view function, and (3) display the message in a template. INSTALLED_APPS = [ ... 'django. contrib. messages', ... ]


2 Answers

As of Django 1.6+, using any class-based generic views, you can rely on the successMessageMixin. It's as simple as adding the mixin to your class definition and setting success_message attribute to whatever you want.

As Olivier Verdier mentioned, please remember to display messages in your main template!

a simple example from the docs:

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"

a more complex example:

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

class ComplicatedCreate(SuccessMessageMixin, CreateView):
    model = ComplicatedModel
    success_url = '/success/'
    success_message = "%(calculated_field)s was created successfully"

    def get_success_message(self, cleaned_data):
        #  cleaned_data is the cleaned data from the form which is used for string formatting
        return self.success_message % dict(cleaned_data,
                                           calculated_field=self.object.calculated_field)
like image 119
furins Avatar answered Sep 28 '22 00:09

furins


As far as I know, there isn't a straightforward way of doing this using traditional generic views. I've always felt that the documentation on generic views was pretty lacking and so never used them.

In theory you could use a decorator by making the assumption that a redirect meant a successful submission.

So you could write something like this (none of this code has been tested):

urls.py:

try:
    from functools import wraps
except ImportError:
    from django.utils.functional import wraps
from django.http import HttpRedirectResponse
from django.contrib import messages
from django.views.generic import * 

def add_message(success_message=None):
    def decorator(func):
        def inner(request, *args, **kwargs):
            resp = func(request, *args, **kwargs)
            if isinstance(resp, HttpRedirectResponse):
                messages.success(request, message)
            return resp
        return wraps(func)(inner)
    return decorator



student_info_edit = {
  'template_name': 'myapp/student/form.html',
  'template_object_name': 'student',
  'form_class':  studentForm,
}

student_info_new = {
  'template_name': 'myapp/student/form.html',
  'form_class':  studentForm,
  'post_save_redirect': '/myapp/students/',
}

urlpatterns += patterns('',
  url(r'^students/$', list_detail.object_list, { 'queryset': Student.objects.all() }, name="students"),
  url(r'^students/(?P<object_id>\d+)/$', add_message("Student record updated successfully")(create_update.update_object), student_info_edit, name="student_detail"),
  url(r'^students/new$', add_message("The student was added successfully.")(create_update.create_object), student_info_new, name="student_new"),
)

All that said and coded, Django 1.3 introduced class-based generic views, so if you're interested in moving onto Django 1.3 you should look into those. They may allow more customization, not sure.

In the long run I rarely see the benefit form using generic views, and this goes double for things like add/update.

like image 28
Jordan Reiter Avatar answered Sep 28 '22 00:09

Jordan Reiter