title: How to avoid repeating a chunk of code in Django views.py
body: <p>What is the best way to avoid repeating a chunk of code that is being used in more than one class view?</p>
  <p>I'm repeating these 2 lines in couple of classes.</p>
  <pre><code>moderator = ServerModerator.objects.get(user=request.user)
  server = Server.objects.get(Q(creator=request.user) | Q(moderators=moderator), Q(tag=server_tag))
  </code></pre>
  <p>I've tried to create a function inside <code>models.py</code> like this:</p>
  <pre><code>class Server(models.Model):
      ...
      creator = models.ForeignKey(User , on_delete=models.CASCADE, related_name='user_servers')
      moderators = models.ManyToManyField('ServerModerator', related_name='server')
  
      def moderator_checker(self, current_user):
          moderator = ServerModerator.objects.get(user=current_user)
          server = Server.objects.get(Q(creator=current_user) | Q(moderators=moderator),Q(tag=self.tag))
          return server
  </code></pre>
  <p>but this doesn't work.</p>
  <p><strong>views.py:</strong></p>
  <pre><code>class TagsAndFlairsView(LoginRequiredMixin, View):
  form_class = CreatePostTagForm
  form_class_2 = CreateUserTagForm
  
  def get(self, request, server_tag):
      ...
      # moderator = ServerModerator.objects.get(user=request.user)
      # server = Server.objects.get(Q(creator=request.user) | Q(moderators=moderator), Q(tag=server_tag))
      check = Server.moderator_checker(request.user)
      server_post_tags = check.post_tags.all()
      server_user_tags = check.user_tags.all()
      return render(request, 'servers/tags-flairs.html', {&quot;server&quot;:check, &quot;server_post_tags&quot;:server_post_tags, &quot;server_user_tags&quot;:server_user_tags, &quot;create_post_tag_form&quot;:create_post_tag_form, &quot;create_user_tag_form&quot;:create_user_tag_form})
  </code></pre>