Search code examples
djangodjango-messages

How can I set success_mesasge with format() in django generic view?


What I want to implement is like this :

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)

But it occurs error. Any ideas?


Solution

  • This isn't an issue with format(), but with trying to reference an attribute that doesn't exist at that point. Attributes at class level are evaluated at import time, but self.title only exists at runtime, and only within a method.

    Rather than setting the message at that level, you should use the get_success_message method:

    def get_success_message(self, cleaned_data):
        return "{} has been created successfully".format(cleaned_data['title'])