how to auto set the topic of a comment to the same topic with the post

76 views Asked by At

i want to be able to create comments by clicking on the comment link under the post, every post has a topic, but i'm unable to get the comments under a specific post, so i thought to add the topic as well for more functionality, but i'm finding it hard to automatically assign the topic based on what post i'm commenting on

my views.py the pk is set as the post.id

def comment(request, pk):
     form = commentform()
     context = {
          'form' : form
     }
     if request.method == 'POST':
          form = commentform(request.POST)
          if form.is_valid():
               forms = form.save(commit=False)
               forms.posts = post.objects.get(id=pk)
               forms.owner = request.user
               forms.topics = topic.objects.get(id=pk)
               forms.save()
               return redirect('home')
     return render(request, 'base/comment.html', context)

my models.py

class comments(models.Model):
    topics = models.ForeignKey(topic, on_delete=models.CASCADE, SET_NULL=True, null=True)
    created = models.DateTimeField(auto_now=True)
    posts = models.ForeignKey(post, on_delete=models.CASCADE)
    owner = models.ForeignKey(User, on_delete=CASCADE)
    comment = models.TextField(max_length= 500)

    def __str__(self):
        return str(self.comment)


class post(models.Model):
    author = models.ForeignKey(User, on_delete=models.CASCADE)
    Topic = models.ForeignKey(topic, on_delete=models.CASCADE)
    post = models.TextField(max_length=500)
    created = models.DateTimeField(auto_now=True)
    def __str__(self):
        return f'{self.post}'

my forms.py

class commentform(ModelForm):
    class Meta:
        model = comments
        fields = ['comment']
1

There are 1 answers

0
cabesuon On

If I understand you correctly, what you need is just to navigate the instances.

Now, if the comments on the post are under the same topic you should not include the topic also in the comment. In that way you are just duplicating information, and it will be extra effort to keep it sync. Just relate the topic with the post and then traverse through it to get it.

class comments(models.Model):
    created = models.DateTimeField(auto_now=True)
    posts = models.ForeignKey(post, on_delete=models.CASCADE)
    owner = models.ForeignKey(User, on_delete=CASCADE)
    comment = models.TextField(max_length= 500)


class post(models.Model):
    author = models.ForeignKey(User, on_delete=models.CASCADE)
    topic = models.ForeignKey(Topic, on_delete=models.CASCADE)
    post = models.TextField(max_length=500)
    created = models.DateTimeField(auto_now=True)

To access the topic just go thought the post,

post = post.objects.get(pk)
post.topic