簡體   English   中英

將成功消息添加到 Django 中的通用重定向視圖

[英]Adding a success message to a generic redirect view in Django

我目前有一個項目,人們可以在其中創建帖子。 我想顯示一條消息,說明帖子已成功投票,但 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)

這里的關鍵是要意識到

SuccessMessageMixin 掛鈎到 form_valid,它在 RedirectView 上不存在,以將其消息推送給用戶。

這正是它在其他方法中起作用的原因,因為這些類支持form_valid()功能。

您可以在此處看到這個寫得很好的答案,了解如何使用RedirectView - Success_url in django RedirectView啟用它

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消息框架

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM