Introduction

Introduction

In our previous section, we discussed the basic concepts of Django web framework. We also built a simple web application using Django, where we saw how to return an HttpResponse. What if we want to respond to the user with an HTML file? Well, when it comes to building high-end web applications, HttpResponse is definitely not a convenient way of responding to a user request. Then, what is the solution?

Check out this Django vs Flask video from Intellipaat:

Build User Registration Using Django Template, Django Model, and Django Model Fields

Before going any further, here’s the table of contents for this Django tutorial in case you want to jump right into a particular topic.

Now, let’s get started.

Django Template

Django Template

Django template is a way to dynamically generate HTML, XML, and PDF files in Django web framework. Django template contains the static parts of a desired HTML output and some special syntax that describes how dynamic content will be inserted.

Let us see how we use Django template in a web application.

Django Course Page CTA

Using Django Template

All HTML files required in a project are stored inside a folder called template. But in order to tell Django to look for templates inside the directory, we have to perform some configuration. Let us see how to configure and use Django templates.

Using Django Template

Step 1: Create an empty directory inside our project directory with the conventional name, ‘template’.

Step 1

Step 2: Create an HTML page for our tutorial home inside the template directory. Let us name it ‘home.html’

Step 2

Step 3: Go to settings.py and make the following template configurations. Here, we are defining the directory path where Django should look for the template source files

Step 3

Alright, now that we have created and configured the template, let us go ahead and see how we can use the template in a view.

Step 4: Create a view that renders the request and maps to a template inside the template directory

step 4

This view or view function is created inside the ‘tutorial’ application. Here, this view function is taking the request and rendering a template called ‘home.html’, which is inside the template folder.

Step 5: Now, set the URL path that would map to the view that we have just created

step 5

We are all set now!

Step 6: Go to the following URL in our browser

step 6

Hurray! We have successfully rendered a template into a view.

But in a real-world web application, we would have many HTML files. Let us see how Django helps us create and maintain these templates in a smart way.

Watch this video on ‘Django Interview Questions’:

Build User Registration Using Django Template, Django Model, and Django Model Fields

Django DRY Concept and Template Tags

Repeating the same format to create each and every HTML page is against Django’s ‘Don’t Repeat Yourself’ (Django DRY) rule.

Django DRY Concept and Template Tags

To avoid repeating the same content, we maintain a Django base template file, from where we inherit the format using certain Django template tags.

Template tags are nothing but certain elements that help us in rendering variables and templates and in inheriting Django base template file in other templates. The typical format of a Django template tag looks like this:

{% tagname %}

Here’s a list of tags that help us follow Django’s DRY principle.

Django DRY Concept and Template Tags 2

We will use these Django template tags to render template files.

For any doubts or errors related to Django template tags, Django render template, or any other topic related to Django, join this online Community.

Now, let us go ahead and see how to deal with data and the database for the web application using Django web framework.

Watch this video on ‘Python Django Tutorial’:

Build User Registration Using Django Template, Django Model, and Django Model Fields

Django Model and Django Model Fields

Django model is the standard source of information about the data we are going to store in our database. It contains fields and behaviors of the data. Each model maps to a single table in the database.

Django Model and Django Model Fields

Things to remember:

  • Each model is a Python class that is a subclass of db.models.Model
  • Each attribute of the model represents a database field

Using Django Model

Follow the two steps to use Django model.

  • First, create a Django model
  • Second, activate the model by using migration

Model is created in the form of a class inside the models.py file. Say, the ‘tutorial’ model has three attributes, ‘tutorial_title’, ‘tutorial_content’, and ‘author_name’

Using Django Model

Once created, activate the Django model by the migration process. Every time the models.py file is modified, we need to perform migration with the help of the following commands:

python manage.py makemigrations
python manage.py migrate

Using Django Model 2
After migrating, we can see a table created for the model in the database.

Before moving ahead and discussing about Django model forms, let us take a look at the different Django model fields available.

Different Model Fields

In our last example of Django model, we created CharField type and TextField type Django model fields already. Let us see how they work and what other Django model fields are available.

  • CharField is a Django model field used for string inputs. It must have the maximum length value of a string input. It is defined as below:
CharField(max_length=None)
  • TextField is also a Django model field used for string inputs but with no character limits. In this type of the model fields, a default value can be added to appear on the field. It is defined as:
TextField(default= ‘add_defualt_value_here’)
  • DateField is a Django model field used to get the date type input. It is defined as follows:
DateField(auto_now=False, auto_now_add=False)
  • URLField is another common Django model field used to get the URL type input from users. It verifies the input. For inputs that are not of the URL type, this field throws an error. It is defined as:
URLField(blank=True, null=False)

Alright, now let us go ahead and see how to create model forms using Django models

Django Model Forms

Django model form is an efficient way of creating forms using Django models without writing HTML codes. Let us see how to create model forms with the help of an example.

Step 1: Create a Python file called forms inside ‘tutorial’

Django Model Forms Step 1

Step 2: Import the built-in forms from Django and the model that we’ve created earlier. Also, import the Django model called ‘Page’ from the ‘models.py’ file. Inside Django ‘ModelForm’ class, create a ‘Meta’ class to instantiate Django model class.

Django Model Forms Step 2

The Meta class that is created inside will provide Meta data to the outer class. Inside the Meta class, define two Meta options, namely, model and fields. The Meta option, ‘model’ will provide a model class for creating the form, and ‘fields’ will list a field to include in the model field.

Step 3: Create a view for the model form using the ModelForm that we’ve just created. First, import the model form and then define a view function that takes requests. If the request is found to be the POST type, ModelForm is generated. Django validates the inputs of each field, and if found valid then the form will be saved and a template will be rendered with the form as context

Django Model Forms Step 3

Step 4: Create the template that needs to be rendered. Extend the base.html file. The form method needs to be defined as POST. Render the ‘form’ context {{ form }}. {{ form.as_p }} renders the form as paragraph inside the block content tag as shown below

Django Model Forms Step 4

We have the view and we have the template. The only thing that we are missing right now is the URL, which will lead us to the view that renders the template.

Step 5: Create a URL path as shown below

Django Model Forms Step 5

A model form is created as shown below.

model form

Wish to crack Django job interviews? Intellipaat’s ‘Top Django Interview Questions and Answers’ are meant only for you!

Django User Registration Form

We will build the user registration functionality in a separate app called ‘user’. Let us take a look at the steps to create users for our web application.

Django User Registration Form

Step 1: Open the command prompt and run the following command:

Django User Registration Form step 1

Step 2: Add the app in the INSTALLED_APPS list to let users know that we have created this app

Django User Registration Form step 2

Step 3: Create a view that maps to a template where we can display the user registration form. Import the UserCreationForm that is inherited from the ModelForm class to handle the creation of new users. UserCreationForm has three fields, namely, username, password1, and password2

Django User Registration Form step 3

If you want to learn the OOP concepts of Python programming language, head on to this tutorial. 

Step 4: Create a template for registration form as shown below

Django User Registration Form step 4

Step 5: Add the URL path that maps the view, which will render the template

Django User Registration Form step 5

Step 6: Check the changes by going to the URL path http://127.0.0.1:8000/register/

As we can see, the form takes any value, without performing any validation

Django User Registration Form step 6

Congratulations! We have successfully created a user registration form.

To learn more advanced concepts of Django, such as creating user login and logout system, user authentication using Django, rendering data from the database using Django, and building a full functioning web application in Django framework, refer to this ‘Python Django Training and Certification’.

In this Django tutorial, we have learned about Django template, Django template tags, Django model, Django model fields, Django model forms, and Django DRY principle. We have also created a user registration form using Django web framework. We will dive deeper into understanding and implementing Django framework in our next Django tutorial blog. See you there!

Recommended Videos

Leave a Reply

Your email address will not be published. Required fields are marked *