在Django中向通用重定向视图添加成功消息

zkure5ic  于 2023-06-25  发布在  Go
关注(0)|答案(2)|浏览(110)

我目前有一个项目,人们可以创建职位。我想显示一条消息,说一个帖子已成功地被投票,但SuccessMessageMixin不起作用。我已经尝试了其他方法,这是包括在我的代码,我将张贴在下面。SuccessMessageMixin适用于其他视图。我不知道为什么它不适合这个视图。
重定向代码不起作用的视图

class PostUpvoteRedirect(SuccessMessageMixin, RedirectView):
    model = Post
    success_message = "Post was upvoted successfully"
    def get_redirect_url(self, *args, **kwargs):
        obj = get_object_or_404(
            Post,
            publish__year=self.kwargs['year'],
            publish__month=self.kwargs['month'],
            publish__day=self.kwargs['day'],
            slug=self.kwargs['post'],
        )
        url_ = obj.get_absolute_url()
        user = self.request.user
        if (user != None):
            if user in obj.Upvote.all():
                obj.Upvote.remove(user)
            else:
                obj.Upvote.add(user)
                if user in obj.Downvote.all():
                    obj.Downvote.remove(user)
            success_message = "Post was upvoted successfully"
        return url_

代码在哪里工作

class PostCreateView(SuccessMessageMixin, LoginRequiredMixin, CreateView):
    model = Post
    fields = ['title','body']
    success_message = "Post was created successfully"

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

axzmvihb1#

这里的关键是要认识到
SuccessMessageMixin挂钩到RedirectView上不存在的form_valid,以将其消息推送给用户。
这正是它在另一个方法中工作的原因,因为这些类支持form_valid()功能。
您可以在这里看到关于如何使用RedirectView-Success_url in django RedirectView启用它的这个写得很好的答案

j7dteeu8

j7dteeu82#

Redirect View dont have request access, for use django message class in CLASS VIEWS you need to use 'SuccessMessageMixin':

    class AnyView(LoginRequiredMixin, SuccessMessageMixin, RedirectView):
    """ LoginRequ... is for Login, SuccessMessage.. is for Message"""
    logging.basicConfig(format='%(levelname)s:%(asctime)s %(message)s')
    logging.debug('Sending message')
    permanent = False
    query_string = True
    somequery = ModelSome.objects.all().filter(activate=True)
    success_url = "/"
    success_message = "%(something)s was succefull"

请登录Django Message Framework了解更多详情!

相关问题