I have a Comment Model that uses ContentType
and GenericForeignKey
so that a comment can be attached to an instance of an arbitrary model:
class Comment(models.Model):
...
text = models.TextField()
target_content_type = models.ForeignKey(ContentType, related_name='comment_target',
null=True, blank=True)
target_object_id = models.PositiveIntegerField(null=True, blank=True)
target_object = GenericForeignKey("target_content_type", "target_object_id")
And I have a form for creating Comments:
class CommentForm(forms.Form):
new_comment = forms.CharField(widget=forms.Textarea(attrs={'rows':2}))
The form is used like this:
<form method="POST" action="{% url 'comments:create' %}">{% csrf_token %}
{{ form | crispy }}
<input type='hidden' name = 'target_id' value='{{q.id}}' />
<input type='submit' class='btn btn-primary' value='Add reply' />
</form>
In my Create view, how can I get the model of the originating object, or the ContentType
& id, so that I can create a new Comment?
def comment_create(request):
if request.method == "POST":
if form.is_valid():
text = form.cleaned_data.get('new_comment')
target_object_id = request.POST.get('target_id')
target_content_type = ?
...