我在Django应用程序中有一个基于类的视图,它可以正常工作。但是我猜它的编码不正确,因为它违反了DRY原理。具体来说,我在posts_list
和get()
方法中有两个绝对相似的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_id
(self.kwargs
对象,self
作为输入参数传递给get()
和post()
) 。这是主要问题。
您可以通过几种方法来进行重组。但是一种简单的方法是将通用代码放入自己的方法中,然后在需要时调用它。
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
来更好地/以不同的方式构建此结构。