Create web application with Django and Python : Part III

in #utopian-io8 years ago (edited)

What will I learn?

This tutorial covers following topics:

  • Creating forms
  • POST method
  • Elaborating views function

Difficulty

Intermediate.

Requirements

  • A PC/laptop with any Operating system such as Linux, Mac OSX, Windows OS
  • Preinstalled Python
  • Preinstalled Code Editors such as Atom, Sublime text or Pycharm IDE

Note: This tutorial is performed in Pycharm IDE on the laptop with Ubuntu 17.1, 64 bit OS

Tutorial Contents

We have created our first template and displayed a message and then we created registration/models.py in our previous tutorial. Now we will create our registration/forms.py.
Forms are used to collect the data provided from the user interface and submit to our model in order to save it. We can create our customs form or use model forms provided by Django.
We will use model forms for now.

Creating forms

Now we will create our forms.py inside registration directory.
At first,, we will start by importing django forms and our model class from model.

from django import forms
from .models import SignUp

As we have created our model class Signup in earlier tutorial, we are importing it to forms.py
Now we will create our form class named SignupForm which takes forms.Modelforms as argument.

class SignupForm(forms.ModelForm):

Now we will create meta class for our class SignupForm. In this meta class,, we will describe what models to take for the respective class in order to save our data.
Under SignupForm we will create our meta class

class Meta:

Now inside meta class we will tell django that our model class for this form class is SignUp

model = SignUp

And also we will declare fields that need to be inserted from forms and saved to the the database.

filelds = ('first_name', 'last_name', 'email', 'password')

We will take first name, last name, email and a password from user interface. Ok, we created our first form.
Our final code looks like:

from django import forms
from .models import SignUp

class SignupForm(forms.ModelForm):

    class Meta:
        model = SignUp
        filelds = ('first_name', 'last_name', 'email', 'password')

Defining views according to forms.py

In previous tutorials,, we defined our view to print a message "Welcome to Signup Page" by creating sign_up function and rendering it with registration/sign_up.html.
Now we need to add more things to that sign_up function to get data from it and save to our database.
All imports remain as same in forms.py , moreover we will add

from django.http import HttpResponseRedirect
from .forms import SignupForm

Here we imported HttpResponseRedirect from django.http to return HttpResponseRedirect object which takes the path to redirect as argument. It helps us to redirect towards provided path
after saving forms.

Now inside sign_up function, we will add these line of codes:

def sign_up(request):
    if request.method == "POST":
        form = SignupForm(request.POST)
        if form.is_valid():
            user = form.save(commit=False)
            user.is_active = False
            user.save()
            return HttpResponseRedirect("/confirm_your_email/")

    else:
        form=SignupForm()
    return render(request, "registration/sign_up.html", {'form': form})

We used if else statements in above code to divide into two branches if our request.method == "POST" then the data is passed to database via form we created which means that we have
inserted our data into our HTML form which needs to be saved into database and we will be redirected toward URL confirm_your_email which we haven't created yet otherwise empty form will be
shown which is registration/sign_up.html. When we run our server and visit http://127.0.0.1:8000/ we will see an empty form which is registration/sign_up.html, then we fill up the form which needs

to be saved in our database which we check it's validity by calling method form.is_valid(). Here we want to add a user to our database after sign_up if data is received and user form is valid than immediately we won't save it, so we kept form.save(commit=False) and also we didn't make the user active by assigning user.is_active = False. Now we will save the data and redirect the user to
confirm_your_email to confirm the user email and we will make the user active else we will show again registration/sign_up.html

Now we need to extend our template sign_up.html to display it properly.

Extending template:

We may have many templates as per the size of application. It would be waste of time if we write all the tempaltes from scratch thus we need to create a base template in our
registration/templates directory as base.html
If you create this base.html from Pycharm IDE than you will see this inside base.html :

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

</body>
</html>

Now we will set our title to Mywebapplication which is diplayed as title in top of browser tab.
We will add

{% block content %}
      
{% endblock %}

Now we write our displaying components between {% block content %} {% endblock %} in child templates. By this, only components between blocks are changed and all other components remain
same.
Our final code in templates/registration/base.html looks like:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Mywebapplication</title>
</head>
<body>
{% block content %}

{% endblock %}
</body>
</html>

Now for our child template sign_up.html we need to extend it from base.html

{% extends 'base.html' %}

inside blocks we will write

{% block content %}
  <h2>Sign up Here</h2>
  <form method="POST">
    {% csrf_token %}
    {{ form.as_p }}
    <button type="submit">Sign up</button>
  </form>
{% endblock %}

Inside <h2></h2> we write our heading as "Sign up Here"
Our method is POST which is needed to get data from user and save into database, so we defined in our view that if only request.method is equall to POST we will extract data
inserted by user. csrf_token helps to get rid of malicious attack. It is a security feature provided by django for POST method. and than we imported our django form in the template.
Also we created a HTML button Sign up which will triger save function.

When we run server and visit http://127.0.0.1:8000/ we will see:

In upcoming tutorials we will add bootstrap in html files, confirm email to sign up, log in,etc.

All above codes can be found on my github link. Click here to download.

Curriculam

Create web application with Django and Python : Part I

Create web application with Django and Python : Part II



Posted on Utopian.io - Rewarding Open Source Contributors

Sort:  

Thank you for the contribution. It has been approved.

PS: please correct your typos, such as

Now we will create our form class named SignupForm which takes forms.Modelforrms as arguement.

You can contact us on Discord.
[utopian-moderator]

Hey @scipio, I just gave you a tip for your hard work on moderation. Upvote this comment to support the utopian moderators and increase your future rewards!

Thanks, Updated

Hey @programminghub I am @utopian-io. I have just upvoted you!

Achievements

  • You have less than 500 followers. Just gave you a gift to help you succeed!
  • Seems like you contribute quite often. AMAZING!

Community-Driven Witness!

I am the first and only Steem Community-Driven Witness. Participate on Discord. Lets GROW TOGETHER!

mooncryption-utopian-witness-gif

Up-vote this comment to grow my power and help Open Source contributions like this one. Want to chat? Join me on Discord https://discord.gg/Pc8HG9x

Coin Marketplace

STEEM 0.04
TRX 0.32
JST 0.083
BTC 60762.96
ETH 1565.09
USDT 1.00
SBD 0.47