Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>ContentType and GenericForeignKey comes in picture when you want to associate your model with many different models. Suppose you have store and you sell Clothes and Utensils. You have separate model for these two. You have a detail page for Cloth and a detail page for Utensil.</p> <p>You want anyone who visits the detail page of Cloth to comment on Cloth. Similarly, you want anyone who visits the detail page of Utensil to comment on this particular Utensil. So, comment can be associated to any of these, and so you need a GenericForeignKey.</p> <p>When user comments on Cloth detail page, object_id will be the id of cloth instance and content_type will be model <code>Cloth</code>. </p> <p>When user comments on Utensil detail page, object_id will be the id of utensil instance and content_type will be model <code>Utensil</code>.</p> <p>A comment can't exist by itself. It has to be related to something.</p> <p>Read <a href="https://docs.djangoproject.com/en/dev/ref/contrib/contenttypes/" rel="nofollow">https://docs.djangoproject.com/en/dev/ref/contrib/contenttypes/</a> again to get a better understanding of why ContentType and GFK exists.</p> <p>Suppose you are in Cloth detail view, so when sending the user to cloth detail page, you know the cloth id. Send this cloth id in the context as <code>object_id</code> and use it in the comment form</p> <p>So, your comment form looks like:</p> <pre><code>{% load i18n %} &lt;div class="comment"&gt; &lt;form action="{% url "comment.views.create" %}" method="post"&gt; {% csrf_token %} {% for field in form %} {{ field.label_tag }} {{ field }}&lt;p&gt; {% endfor %} &lt;input type="hidden" value="{{object_id}}" name="object_id"/&gt; &lt;input type="submit" value="{% trans "Submit" %}"&gt; &lt;/form&gt; &lt;/div&gt; </code></pre> <p>And in Comment create view, read this object id and use it. So, in view, you say:</p> <pre><code>object_id = request.POST['object_id'] </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload