Search code examples
djangodjango-generic-views

DetailView and templates


Django 1.9.7

Could you help me with three questions about DetailView:

  1. Why DetailView doesn't put form into the context whereas CreateView does? I mean it is very cumbersome to write a template where every field is shown separately like object.headline or object.content. In case of CreateView we just place {{ form.as_p }} into the template. Much more convenient. So, there must be some logic behind the scene that I can't feel because of lack of experience.

  2. Is there a third party applications with ready to use template tags for DetailView? Or something else to automate this selection of fields to be displayed in the template.

  3. Or should I just put a form myself in get_context_data?


Solution

  • DetailView is not intended for editing. Use UpdateView for that purpose.

    If you want to display each field in the same format loop over them, you must pass your field names in the context as a list and then loop over this list:

    {% for field_name in field_names %}
      <tr>
        <th>{% get_field_label object field_name %}</th>
        <td>{% get_field_value object field_name %}</td>
      </tr>
    {% endfor %}
    

    And create custom template tags:

    @register.simple_tag
    def get_field_label(obj, name):
        return obj._meta.get_field(name).verbose_name
    
    @register.simple_tag
    def get_field_value(obj, name):
        return getattr(obj, value)