Instagram
youtube
Facebook
Twitter

Django Templates

In Django, Templates is the file where the whole HTML content of our web application is stored. Most of the things we want to display to our users can be done through Django templates. So, let's understand the whole concept practically. 

First, we have to create a template file inside our app folder. After creating it we have to configure it in our settings.py file. Add “ 'DIRS': [ BASE_DIR / "templates"],” in your settings.py templates to do that.

TEMPLATES = [
    {
        'BACKEND': 'Django.template.backends.Django.DjangoTemplates',
        'DIRS': [ BASE_DIR / "templates"],
        'APP_DIRS': True,
        'OPTIONS': {
        'context_processors': [
                'Django.template.context_processors.debug',              'Django.template.context_processors.request',             'Django.contrib.auth.context_processors.auth',            'Django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

Here, we have named our template files as templates. Because by default, Django templates search for a template file in each of the INSTALLED_APPS.

After doing this creates an HTML file inside your templates folder. I’m naming it contact.html. Add your HTML code in this folder. As I have already created a contact model, I will make a contact form in contact.html. I am using bootstrap to create this.

<!doctype html>
<html lang="en">
  <head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.2.1/dist/css/bootstrap.min.css" integrity="sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS" crossorigin="anonymous">

    <title>Codersdaily</title>
  </head>
  <body>
    <section id="services" class="services_wrapper">
        <div class="container contact-form">
                    <div class="contact-image">
                     
                    </div>
                    <form method="post" action="/contact"> {% csrf_token% }


                        <h3>Drop Us a Message</h3>
                      <div class="row">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <input type="text" name="name" class="form-control" placeholder="Your Name *" value="" />
                                </div>
                                <div class="form-group">
                                    <input type="text" name="email" class="form-control" placeholder="Your Email *" value="" />
                                </div>
                                <div class="form-group">
                                    <input type="text" name="phone" class="form-control" placeholder="Your Phone Number *" value="" />
                                </div>
                                <div class="form-group">
                                    <input type="submit" name="btnSubmit" class="btnContact" value="Send Message" />
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group">
                                    <textarea name="message" class="form-control" placeholder="Your Message *" style="width: 100%; height: 150px;"></textarea>
                                </div>
                            </div>
                        </div>
                    </form>
                   
        </div>
        <section/>

    <!-- Optional JavaScript -->
    <!-- jQuery first, then Popper.js, then Bootstrap JS -->
    <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/popper.js@1.14.6/dist/umd/popper.min.js" integrity="sha384-wHAiFfRlMFy6i5SRaxvfOCifBUQy1xHdJ/yoi7FRNXMRBu5WHdZYu1hA6ZOblgut" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.2.1/dist/js/bootstrap.min.js" integrity="sha384-B0UglyR+jN6CkvvICOB2joaf5I4l3gm9GU6Hc1og6Ls7i6U/mkkaduKaBhlAXv9k" crossorigin="anonymous"></script>
  </body>
</html>

Make sure that you have named your Diango model elements and HTML input the same. And, also don't forget to add the method type in your Html.

In this tutorial, I’m using the method = “post” attribute which means our form will handle only post requests. Django also provides an in-built csrf security feature. Use csrf template tag ({% csrf_token% }) to add this feature.

Now, our template file is almost ready. But, Django needs to know what to do with the data after the user hits the submit button. We can add those instructions by editing our views.py file. These are the following instructions.

def contact(request) :
    if request.method == "POST":
        name = request.POST('name')
        email = request.POST('email')
        phone = request.POST('phone')
        message = request.POST('message')
        contact = Contact(name=name, email=email, phone=phone, message=message)
        contact.save()
    return render(request, 'contact.html',)

 

From the above code, Django will first check request.method after form submission. If it is a post method then Django will forward the validation process otherwise it will throw an error. After this Django will check all the information. If all the information is found to be valid then Django will save all the information via contact.save() and will render the same page again.

Let's check if our contact form is working or not by using the command “python manage.py runserver”.

 

So, our page is rendered successfully, now lets check if it is working or not by filling in some information.

Let's check if the information is stored in the database or not.

So, our data is stored in the database successfully.