简体   繁体   English

Django:如何从UpdateView(CBV)返回上下文?

[英]Django: How to return with context from UpdateView (CBV)?

The following view works as expected 以下视图按预期工作

class BrandEditView(PermissionRequiredMixin ,generic.UpdateView):
    permission_required = 'change_brand'

    template_name = 'brand_update_form.pug'
    model = Brand
    fields = ['name']

    def get_object(self, queryset=None):
        print(self.request.user)
        self.object = Brand.objects.get(id=self.kwargs['pk'])
        obj = Brand.objects.get(id=self.kwargs['pk'])
        return obj

After form submission, how do I return to the same view (with the same object), but with context, like a message: "brand edited successfully"/"you can't do that"? 提交表单后,如何返回相同的视图(具有相同的对象),但又具有上下文,如消息:“品牌编辑成功” /“您不能这样做”? I've found a way to redirect to the same view, but not with context. 我找到了一种重定向到同一视图的方法,但是没有上下文。

to use the message framework in class based view we use the SuccessMessageMixin 要在基于类的视图中使用消息框架,我们使用SuccessMessageMixin

so update your view to be like this: 因此,将您的视图更新为:

from django.contrib.messages.views import SuccessMessageMixin
class BrandEditView(SuccessMessageMixin, PermissionRequiredMixin ,generic.UpdateView):
    permission_required = 'change_brand'
    success_url = reverse_lazy('your redirect url')
    template_name = 'brand_update_form.pug'
    model = Brand
    fields = ['name']
    success_message = "created successfully!"
    def get_object(self, queryset=None):
        print(self.request.user)
        self.object = Brand.objects.get(id=self.kwargs['pk'])
        obj = Brand.objects.get(id=self.kwargs['pk'])
        return obj

and in the base template or any template add this: 并在基本模板或任何模板中添加以下内容:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM