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

发布于 2024-10-14 00:04:11 字数 91 浏览 2 评论 0 原文

我是 django (1.2.4) 的新手。我用通用视图创建了一些粗略的内容。但是,当使用 django 的消息传递框架创建学生时,如何显示“学生添加成功”之类的信息?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

向地狱狂奔 2024-10-21 00:04:11

Django 1.6+ 开始,使用任何 类基于通用视图,您可以依赖 successMessageMixin。这就像将 mixin 添加到类定义中并将 success_message 属性设置为您想要的任何内容一样简单。

正如 Olivier Verdier 提到的,请记住显示消息在您的主模板中!

文档中的一个简单示例

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)

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)
枯寂 2024-10-21 00:04:11

The functionality that you are asking for is already implemented in Django generic views:

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

You will see the messages by displaying messages in your main template.

无戏配角 2024-10-21 00:04:11

实际上,我认为这些文档很好地解释了基于通用/函数的视图:
https://docs.djangoproject.com/en/2.0/ref/contrib /messages/

它基本上使用 if 语句将上下文传递到模板,以显示或不显示该上下文。

查看:

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)

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

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

当它再次呈现页面时,只需将锚标记添加到您的表单并包含在您的表单操作中,即

action="{% url 'home_page:index' %}#subscribe"

如果您使用引导添加类警报成功

Actually I think the documents explain it pretty well for generic/function based views:
https://docs.djangoproject.com/en/2.0/ref/contrib/messages/

It basically passes context to your template with an if statement to display that context or not.

View:

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)

And then it will be displayed in your template using the following. Remember to iterate '...because otherwise the message storage will not be cleared for the next request':

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

As it renders the page again just add an anchor tag to your form and include in your form action i.e.

action="{% url 'home_page:index' %}#subscribe"

If you're using bootstrap add class alert-success

浴红衣 2024-10-21 00:04:11

据我所知,使用传统的通用视图没有一种简单的方法可以做到这一点。我一直觉得通用视图的文档非常缺乏,所以从未使用过它们。

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

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

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/

综上所述,Django 1.3 引入了 基于类通用视图,所以如果您有兴趣转向 Django 1.3,您可以应该调查那些。他们可能允许更多定制,但不确定。

从长远来看,我很少看到使用通用视图的福利形式,而对于添加/更新之类的事情来说,这种情况会加倍。

, list_detail.object_list, { 'queryset': Student.objects.all() }, name="students"), url(r'^students/(?P<object_id>\d+)/

综上所述,Django 1.3 引入了 基于类通用视图,所以如果您有兴趣转向 Django 1.3,您可以应该调查那些。他们可能允许更多定制,但不确定。

从长远来看,我很少看到使用通用视图的福利形式,而对于添加/更新之类的事情来说,这种情况会加倍。

, add_message("Student record updated successfully")(create_update.update_object), student_info_edit, name="student_detail"), url(r'^students/new

综上所述,Django 1.3 引入了 基于类通用视图,所以如果您有兴趣转向 Django 1.3,您可以应该调查那些。他们可能允许更多定制,但不确定。

从长远来看,我很少看到使用通用视图的福利形式,而对于添加/更新之类的事情来说,这种情况会加倍。

, add_message("The student was added successfully.")(create_update.create_object), student_info_new, name="student_new"), )

综上所述,Django 1.3 引入了 基于类通用视图,所以如果您有兴趣转向 Django 1.3,您可以应该调查那些。他们可能允许更多定制,但不确定。

从长远来看,我很少看到使用通用视图的福利形式,而对于添加/更新之类的事情来说,这种情况会加倍。

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/

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.

, list_detail.object_list, { 'queryset': Student.objects.all() }, name="students"), url(r'^students/(?P<object_id>\d+)/

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.

, add_message("Student record updated successfully")(create_update.update_object), student_info_edit, name="student_detail"), url(r'^students/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.

, 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文