Form & ModelForm

.order_by()

Sort in reverse order by pk

articles = Article.objects.order_by('-pk')

ModelForm

Defining ModelForm

forms.py

from django import forms
from .models import Article

class ArticleForm(forms.ModelForm):
    title = forms.CharField(
        max_length=100,
        label='Title',
        help_text='Your title must be no more than 100 characters in length',
        widget=forms.TextInput(
            attrs={
                'class':'my_input',
                'placeholder': "What's on your mind?"
            }
        )
    )
    content = forms.CharField(
        label='Content',
        help_text='Jot down random musings and thoughts',
        widget=forms.Textarea(
            attrs={
                'row':5,
                'col':50,
            }
        )
    )
    class Meta:
        model = Article
        # Include all fields
        fields = '__all__'

Using ModelForm in View

view.py

Conditional processing with request.resolver_match.url_name

form.html

  • The basis for branching is url_name

  • If you use path, you have to change it every time the url changes!

Output using loop or bootstrap4

form.html

Enter shell

shell

Collection of inputs composed of p tags

Collection of inputs composed of table

Looping over the form's fields

If you're using the same HTML for each of your form fields, you can reduce duplicate code by looping through each field in turn using a {% for %} loop:

Form rendering options

There are other output options though for the <label>/<input> pairs:

  • {{ form.as_table }} will render them as table cells wrapped in <tr> tags

  • {{ form.as_p }} will render them wrapped in <p> tags

  • {{ form.as_ul }} will render them wrapped in <li> tags

Note that you'll have to provide the surrounding <table> or <ul> elements yourself.

Here's the output of {{ form.as_p }} for our ContactForm instance:

Using Django Bootstrap

Install

Modify settings.py

Declare that you will use bootstrap in base.html

detail.html - Also declare in templates where bootstrap is applied

+

Git

Go back to specific commit

Create test branch and move

Check reference log

Check where head is

Go back to test branch

Last updated