By admin on

Django Form Template

When creating forms. Django makes it easier and quicker by allowing one to just extending the modelForm class.

To output and display the form in the template, one just need to form.as_p

This is great but you might need to customize how the form fields are output

The customization might be because of using custom elements or a custom lib to show a field and so you need freedom on how the html tags and properties are decleared

This post explains how you could do the customizations based on the form field type.

This post is a based on how Django admin create and edit forms are generated


  • Single Select Choices Field
  • <form action="{% url 'some_view' %}" method="post">
        {% csrf_token %}
        {% if form.non_field_errors %}
            {{ form.non_field_errors }}
        {% endif %}
    
        {% for field in form %}
            {{ field.label }}
    
            {% if field.field.choices %}
              {% for model_instance in field.field.choices.queryset %}
                {{ model_instance.id }}
              {% endfor %}
            {% else %}
              {{ field }}
            {% endif %}
    
            {% if field.errors %}
                {{ field.errors|striptags }}
            {% endif %}
    
        {% endfor %}
    
        <button type="submit">Submit</button>
    </form>
    

    2.Multi Select Choices Field

    
    


    1. Input Fields. for text, number, email, password
    
    



    0 comments

    Write a response
    Publish