如果我们使用django通用视图,如何发送成功消息

时间:2011-01-26 08:19:20

标签: python django django-generic-views

我是django的新手(1.2.4)。我用通用视图创建了一些crud。但是,当使用django的消息传递框架创建学生时,我怎样才能显示“学生成功添加”这样的内容?

4 个答案:

答案 0 :(得分:37)

Django 1.6 + 开始,使用任何class-based generic views,您都可以依赖successMessageMixin。这就像将mixin添加到您的类定义并将success_message属性设置为您想要的任何内容一样简单。

正如Olivier Verdier所提到的,请记住你主模板中的display messages

来自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"

一个更复杂的例子:

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)

答案 1 :(得分:4)

据我所知,使用传统的通用视图并没有直接的方法。我一直认为关于通用视图的文档非常缺乏,因此从未使用它们。

理论上,您可以通过假设重定向意味着成功提交来使用装饰器。

所以你可以写这样的东西(这些代码都没有经过测试):

<强> 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"),
)

所有说和编码,Django 1.3引入class-based generic views,所以如果你有兴趣转向Django 1.3,你应该研究那些。它们可能允许更多自定义,但不确定。

从长远来看,我很少看到使用通用视图的好处形式,这对于添加/更新这样的事情来说是双倍的。

答案 2 :(得分:2)

您要求的功能已在Django通用视图中实现:

https://github.com/django/django/blob/1.2.X/django/views/generic/create_update.py#L115

您将在主模板中按displaying messages看到消息。

答案 3 :(得分:0)

实际上我认为文档很好地解释了基于通用/函数的视图: Link 1

它基本上将上下文传递给您的模板,并使用if语句显示该上下文。

查看:

specTitle

然后它将使用以下内容显示在您的模板中。请记住迭代'...因为否则将不会为下一个请求清除消息存储':

const spec1 = [
  { specTitle: <h1 className="specTitle">Size</h1>, ...},
  { specTitle: <h1 className="specTitle">Color</h1>, ...}
]

当它再次呈现页面时,只需在表单中添加一个锚标记并包含在表单中即可。

from django.contrib import messages
def home_page(request):
    if request.method == 'POST':
        messages.success(request, 'Student added successfully')
        context = {}
        return render(request, 'homepage/index.html', context)
    else:
        form =yourForm()
        return render(request, 'homepage/index.html', form)

如果您正在使用bootstrap,请添加类{% if messages %} <ul class="messages"> {% for message in messages %} <li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li> {% endfor %} </ul> {% endif %}