处理视图后调用Django Post

时间:2017-09-06 05:23:43

标签: python django

我正在创建一个用户可以编辑主题的论坛。当用户更改主题标题时,主题的slug会发生变化。当我发布对主题的更改时,slug纠正中间件会触发并重定向我回到相同的编辑页面,而不是让我重定向到主题本身。似乎django首先处理视图,然后使用旧URL调用post,导致我的更改被保存,但我没有在正确的位置结束。例如,如果我在不改变任何内容的情况下点击帖子,我会被重定向到应该去的地方。我该如何解决这个问题?

# middleware.py
class TopicSlugMiddleware(object):
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        response = self.get_response(request)
        if (request.resolver_match and 'topic_slug' in request.resolver_match.kwargs):
            try:
                topic_slug = request.resolver_match.kwargs['topic_slug']

                topic_pk = int(topic_slug.split('-')[0])
                topic = Topic.objects.get(pk=topic_pk)

                if (topic.slug != topic_slug):
                    return redirect(reverse(request.resolver_match.url_name, kwargs={'topic_slug': topic.slug}))
            except:
                raise Http404('The topic you are looking for does not exist')

        return response

# views.py
class EditTopicView(View):
    template_name = 'forums/edit_topic.html'

    def get(self, request, topic_slug):
        topic = Topic.objects.get(slug=topic_slug)

        if (request.user.profile.role.can_modify_topics or request.user == topic.started_by):
            if (request.user.profile.role.can_modify_topics):
                form = EditMoveTopicForm(instance=topic)
            else:
                form = NewTopicForm(instance=topic)
            return render(request, self.template_name, {'topic': topic, 'form': form})
        else:
            raise PermissionDenied('You do not have permission to modify this topic')

    def post(self, request, topic_slug):
        topic = Topic.objects.get(slug=topic_slug)

        if (request.user.profile.role.can_modify_topics or request.user == topic.started_by):
            if (request.user.profile.role.can_modify_topics):
                form = EditMoveTopicForm(request.POST)
            else:
                form = NewTopicForm(request.POST)

            if (form.is_valid()):
                topic.title = form.cleaned_data['title']
                topic.tags = form.cleaned_data['tags']
                topic.save()
                return redirect('/topics/' + topic.slug)
            else:
                return render(request, self.template_name, {'topic': topic, 'form': form})
        else:
            raise PermissionDenied('You do not have permission to modify this topic')

0 个答案:

没有答案