如何为基于Django类的视图的所有方法声明公共变量?

问题描述 投票:0回答:1

我在Django应用程序中有一个基于类的视图,它可以正常工作。但是我猜它的编码不正确,因为它违反了DRY原理。具体来说,我在posts_listget()方法中有两个绝对相似的post()变量声明:

class TopicView(View):
    def get(self, request, topic_id):
        post_form = PostForm()
        posts_list = Post.objects.filter(topic_id=self.kwargs['topic_id']).order_by('-creation_date')
        return render(request, 'discussions/topic.html', {'posts_list': posts_list,
                                                          'post_form': post_form,
                                                          'topic_id': topic_id})

    def post(self, request, topic_id):
        post_form = PostForm(request.POST)

        if post_form.is_valid():
            post = post_form.save(commit=False)
            post.author = request.user
            post.topic = Topic.objects.get(pk=topic_id)
            post.save()
            return redirect('discussions:topic', topic_id=topic_id)

        posts_list = Post.objects.filter(topic_id=self.kwargs['topic_id']).order_by('-creation_date')
        return render(request, 'discussions/topic.html', {'posts_list': posts_list,
                                                          'post_form': post_form,
                                                          'topic_id': topic_id})

是否有一种方法可以将这个变量声明为类属性,而不是在每个方法中将其声明为简单变量?声明时,将topic_id用作对象的过滤器,并从URL中提取topic_idself.kwargs对象,self作为输入参数传递给get()post()) 。这是主要问题。

django oop django-views
1个回答
0
投票

您可以通过几种方法来进行重组。但是一种简单的方法是将通用代码放入自己的方法中,然后在需要时调用它。

class TopicView(View):
    def get(self, request, topic_id):
        return self.post_list_response(PostForm())

    def post(self, request, topic_id):
        post_form = PostForm(request.POST)

        if post_form.is_valid():
            post = post_form.save(commit=False)
            post.author = request.user
            post.topic = Topic.objects.get(pk=topic_id)
            post.save()
            return redirect('discussions:topic', topic_id=topic_id)

        return self.post_list_response(post_form)

    def post_list_response(self, post_form):
        topic_id = self.kwargs['topic_id']
        posts_list = Post.objects.filter(topic_id=topic_id).order_by('-creation_date')
        return render(request, 'discussions/topic.html', {
            'posts_list': posts_list,
            'post_form': post_form,
            'topic_id': topic_id
        })

您还可以通过使用Django的FormView类而不是简单的View来更好地/以不同的方式构建此结构。

© www.soinside.com 2019 - 2024. All rights reserved.