Django Tutorial

Django Create A Complete Project

Django Template

Django Database Query

Django Form

Django Authentication and Permission Management

Django unittest

Django Advanced

Django Form Built-in Fields

Django's Form API provides a variety of built-in form fields to handle different types of data input. In this tutorial, we'll go through some of the most common form fields and their attributes.

  1. CharField
  2. IntegerField
  3. DateField
  4. BooleanField
  5. ChoiceField
  6. EmailField
  7. URLField
  8. FileField
  9. ImageField
  10. ModelChoiceField

1. CharField

CharField is used for text input and has a few optional attributes:

  • max_length: The maximum length of the input.
  • min_length: The minimum length of the input.
  • strip: If set to True (default), leading and trailing whitespaces are removed.

Example:

name = forms.CharField(max_length=100)

2. IntegerField

IntegerField is used for integer input and has a few optional attributes:

  • max_value: The maximum allowed value.
  • min_value: The minimum allowed value.

Example:

age = forms.IntegerField(min_value=18, max_value=120)

3. DateField

DateField is used for date input and has a few optional attributes:

  • input_formats: A list of formats for parsing the input.
  • initial: The initial value of the field.

Example:

birthday = forms.DateField(input_formats=['%Y-%m-%d'])

4. BooleanField

BooleanField is used for boolean input (checkbox). There are no specific attributes for this field.

Example:

is_active = forms.BooleanField()

5. ChoiceField

ChoiceField is used for a selection of choices. It has one required attribute:

  • choices: A list of tuples with each tuple containing two items, the value, and the display label.

Example:

GENDER_CHOICES = (
    ('M', 'Male'),
    ('F', 'Female'),
)

gender = forms.ChoiceField(choices=GENDER_CHOICES)

6. EmailField

EmailField is used for email input. It inherits all attributes from CharField.

Example:

email = forms.EmailField()

7. URLField

URLField is used for URL input. It inherits all attributes from CharField.

Example:

website = forms.URLField()

8. FileField

FileField is used for file input. It has a few optional attributes:

  • max_length: The maximum length of the file path.
  • allow_empty_file: If set to True, allows empty files to be uploaded.

Example:

document = forms.FileField()

9. ImageField

ImageField is used for image input. It inherits all attributes from FileField and has an additional attribute:

  • required: If set to True (default), the field must be filled in.

Example:

avatar = forms.ImageField(required=False)

10. ModelChoiceField

ModelChoiceField is used for selecting an object from a queryset. It has a required attribute:

  • queryset: The queryset to use as choices.

Example:

from .models import Author

author = forms.ModelChoiceField(queryset=Author.objects.all())

This tutorial covered some of the most common Django built-in form fields.

  1. List of built-in form fields in Django:

    • Description: Explore the various built-in form fields provided by Django, such as CharField, IntegerField, DateField, and more.
    • Code Example:
      # forms.py in your app
      from django import forms
      
      class MyForm(forms.Form):
          char_field = forms.CharField()
          integer_field = forms.IntegerField()
          date_field = forms.DateField()
          # ... (other fields)
      
  2. Django CharField vs TextField in forms:

    • Description: Understand the differences between CharField and TextField in Django forms, considering character length and use cases.
    • Code Example:
      # forms.py in your app
      from django import forms
      
      class MyForm(forms.Form):
          char_field = forms.CharField(max_length=100)
          text_field = forms.CharField(widget=forms.Textarea)
      
  3. Using Django IntegerField in forms:

    • Description: Use the IntegerField in Django forms for handling integer values.
    • Code Example:
      # forms.py in your app
      from django import forms
      
      class MyForm(forms.Form):
          integer_field = forms.IntegerField()
      
  4. Django DateField and TimeField in forms:

    • Description: Utilize DateField and TimeField in Django forms to handle date and time input, respectively.
    • Code Example:
      # forms.py in your app
      from django import forms
      
      class MyForm(forms.Form):
          date_field = forms.DateField()
          time_field = forms.TimeField()
      
  5. Django EmailField in forms usage:

    • Description: Use the EmailField in Django forms to validate and handle email input.
    • Code Example:
      # forms.py in your app
      from django import forms
      
      class MyForm(forms.Form):
          email_field = forms.EmailField()
      
  6. Working with Django URLField in forms:

    • Description: Handle URLs in Django forms using the URLField, ensuring valid URL input.
    • Code Example:
      # forms.py in your app
      from django import forms
      
      class MyForm(forms.Form):
          url_field = forms.URLField()
      
  7. Handling choices with Django ChoiceField:

    • Description: Use the ChoiceField in Django forms for fields with predefined choices.
    • Code Example:
      # forms.py in your app
      from django import forms
      
      class MyForm(forms.Form):
          gender_choices = [('M', 'Male'), ('F', 'Female')]
          gender_field = forms.ChoiceField(choices=gender_choices)
      
  8. Django FileField and ImageField in forms:

    • Description: Handle file uploads and image uploads in Django forms using FileField and ImageField.
    • Code Example:
      # forms.py in your app
      from django import forms
      
      class MyForm(forms.Form):
          file_field = forms.FileField()
          image_field = forms.ImageField()
      
  9. Using Django FloatField and DecimalField in forms:

    • Description: Use FloatField and DecimalField in Django forms to handle floating-point and decimal number input.
    • Code Example:
      # forms.py in your app
      from django import forms
      
      class MyForm(forms.Form):
          float_field = forms.FloatField()
          decimal_field = forms.DecimalField()
      
  10. Customizing labels and help text in Django forms:

    • Description: Customize the labels and help text for form fields to provide additional information to users.
    • Code Example:
      # forms.py in your app
      from django import forms
      
      class MyForm(forms.Form):
          name = forms.CharField(label='Your Full Name', help_text='Enter your full name.')
      
  11. Django SlugField in forms examples:

    • Description: Use the SlugField in Django forms to handle slugs, which are URL-friendly versions of a string.
    • Code Example:
      # forms.py in your app
      from django import forms
      
      class MyForm(forms.Form):
          slug_field = forms.SlugField()
      
  12. Django form validation with RegexField:

    • Description: Implement custom form validation using RegexField to enforce patterns using regular expressions.
    • Code Example:
      # forms.py in your app
      from django import forms
      
      class MyForm(forms.Form):
          postal_code = forms.RegexField(regex=r'^\d{5}$', error_messages={'invalid': 'Enter a valid 5-digit postal code.'})
      
  13. Django URL validation with URLField:

    • Description: Utilize the URLField in Django forms to handle and validate URL input.
    • Code Example:
      # forms.py in your app
      from django import forms
      
      class MyForm(forms.Form):
          website_url = forms.URLField()
      
  14. Django form handling for DateTimeField:

    • Description: Handle date and time input together using DateTimeField in Django forms.
    • Code Example:
      # forms.py in your app
      from django import forms
      
      class MyForm(forms.Form):
          meeting_datetime = forms.DateTimeField()
      
  15. Django ModelChoiceField in forms:

    • Description: Use ModelChoiceField in Django forms to handle choices populated from a model's queryset.
    • Code Example:
      # forms.py in your app
      from django import forms
      from .models import Category
      
      class MyForm(forms.Form):
          category = forms.ModelChoiceField(queryset=Category.objects.all())
      
  16. Working with Django TimeField in forms:

    • Description: Use TimeField in Django forms to handle time input separately from date input.
    • Code Example:
      # forms.py in your app
      from django import forms
      
      class MyForm(forms.Form):
          meeting_time = forms.TimeField()