Luis A. Borit Guitton Luis A. Borit Guitton - 1 year ago 47
Python Question

getting the id from a foreignkey relationship django

I want to get the id or pk of a ForeignKey relationship post_comment but I've tried many different ways to catch it and i do not have any good result, please guys give me a hand in this situation


class createComment(View):
form_class = CommentForm
template_name = "createComment.html"

def get(self, request):
form = self.form_class(None)
return render(request, self.template_name, {'form':form})

def post(self, request):
obj = self.form_class(None)
obj.title_comment = self.request.POST['title_comment']
obj.body_comment = self.request.POST['body_comment']
obj.post_comment =


class Comment(models.Model):
user_comment = models.ForeignKey("auth.User")
title_comment = models.CharField(max_length=50)
body_comment = models.TextField()
timestamp_comment = models.DateTimeField(auto_now=True)
post_comment = models.ForeignKey("Post", null=True)
status_comment = models.BooleanField(default=True)

def __unicode__(self):
return unicode(self.title_comment)

def __str__(self):
return self.title_comment

Answer Source

You can pass a primary key in the url, and then use it in your class as one way.

kwargs.get(pk name)

You could change post to:

def post(self, request, *args, **kwargs)

You then can't just assign obj.post_comment = kwargs.get(pk) you have to actually get the object.

Post.objects.get(pk = pk)

You might want to also consider renaming fieldname_comment to just fieldname for your models fields. Seems a bit redundant to have _comment on every single field in the Comment model.