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 posts_list variable inside get() and post() methods:
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})
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 topic_id as a filter for objects, and I extract topic_id from the URL (self.kwargs object, self is passed to both get() and post() as an input parameter). This is the main issue.