title: How to declare common variables for all methods of a Django class-based view?
body: <p>I have a class-based view in my Django application and it works fine. But I guess it is not coded well, because it violates the DRY principle. Specifically, I have two absolutely similar declarations of the <code>posts_list</code> variable inside <code>get()</code> and <code>post()</code> methods:</p>
  
  <pre><code>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})
  </code></pre>
  
  <p>Is there a way how I can declare this variable as a class attribute instead of a simple variable inside each of the methods? When I declaring it, I use <code>topic_id</code> as a filter for objects, and I extract <code>topic_id</code> from the URL (<code>self.kwargs</code> object, <code>self</code> is passed to both <code>get()</code> and <code>post()</code> as an input parameter). This is the main issue.</p>