如何在django泛型视图中使用format()设置success_mesasge?

时间:2016-08-22 07:45:27

标签: django django-messages

我想要实现的是这样的:

from django.contrib.auth.mixins import LoginRequiredMixin
from django.contrib.messages.views import SuccessMessageMixin
from django.views.generic import CreateView

from posts.models import Post


class PostNewView(LoginRequiredMixin, SuccessMessageMixin, CreateView):

    model = Post
    fields = ['title', 'content', 'image']
    success_message = "{} has been created successfully".format(self.post.title) 

    def form_valid(self, form):
        form.instance.author = self.request.user
        return super().form_valid(form)

但它发生错误。有什么想法吗?

1 个答案:

答案 0 :(得分:3)

这不是format()的问题,但是尝试引用此时不存在的属性。类级别的属性在导入时计算,但self.title仅在运行时存在,并且仅在方法中存在。

您应该使用get_success_message方法:

,而不是在该级别设置消息
def get_success_message(self, cleaned_data):
    return "{} has been created successfully".format(cleaned_data['title'])