我想要实现的是这样的:
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)
但它发生错误。有什么想法吗?
答案 0 :(得分:3)
这不是format()
的问题,但是尝试引用此时不存在的属性。类级别的属性在导入时计算,但self.title
仅在运行时存在,并且仅在方法中存在。
您应该使用get_success_message
方法:
def get_success_message(self, cleaned_data):
return "{} has been created successfully".format(cleaned_data['title'])