如何在 Django 通用视图中使用 format() 设置 success_mesasge?
How can I set success_mesasge with format() in django generic view?
我想实现的是这样的:
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)
但是出现错误。有什么想法吗?
这不是 format()
的问题,而是试图引用当时不存在的属性的问题。 class 级别的属性在导入时进行评估,但 self.title
仅在运行时存在,并且仅存在于方法中。
与其在该级别设置消息,不如使用 get_success_message
方法:
def get_success_message(self, cleaned_data):
return "{} has been created successfully".format(cleaned_data['title'])
我想实现的是这样的:
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)
但是出现错误。有什么想法吗?
这不是 format()
的问题,而是试图引用当时不存在的属性的问题。 class 级别的属性在导入时进行评估,但 self.title
仅在运行时存在,并且仅存在于方法中。
与其在该级别设置消息,不如使用 get_success_message
方法:
def get_success_message(self, cleaned_data):
return "{} has been created successfully".format(cleaned_data['title'])