Django File Upload using FileField Tutorial

Uploading files in web development is one of the key functionalities without which web developers can’t really digest their website. This functionality is used in various fields in their own unique ways. It could be used  for simple user registration which involves uploading images  as an avatar, for uploading videos as on youtube, for uploading favourite songs as on saavn and the list goes on. As a conclusion, we can say that it is immensely important for one to learn the uploading of files in order to be a good Django web developer. So here is the post explaining Django File Upload using FileField.

More specifically, in this example of Django File Upload, we’ll be doing a user registration webapp containing just two links which will be as follows

  • Since we just need to focus on upload of file, as an registration process, we’ll take input of user’s name and his/her profile picture which would  be uploaded on the local server.
  • Later the url of uploaded profile picture would be used to show the list of user with each user containing his/her name and profile picture.

Okay, here is the link description:-

  1. The first link would be where the user would input his/her name and profile picture.
  2. The second link would be where the list of registered users would be shown.

Now that you are aquainted with the aim of this Django File Upload example, let’s get started with code.

To accomplish the task of taking inputs in this example, ModelForms have been used which reduce the pain of defining forms. Don’t worry if you are not familiar with  ModelForms. Just go through the post on Modelforms for which the link has been given below.

Django ModelForm Example

[toc]

Django File Upload Tutorial

Creating a new Project

  • Run your Windows PowerShell in Administrator Mode and run the following command to navigate into the desktop directory :
cd ~/Desktop
  • Run the command below to start a project new django project:
 django-admin startproject website
  • As you do, you will see a  folder on your desktop containing the django files named website
  • Open the folder in any Django IDE or any text editor will work fine.
  • Run the command below to change the directory of PowerShell to the folder “website”:
cd website

Creating a new App inside the Project

  • Run the command below to start a new app into your project.
python manage.py startapp uploadfileapp
  • Here, uploadfileapp is the name of your app. As your run the above command, a folder named uploadfileapp will show up in the website folder.

Coding the App

Creating Model

  • We need to  create a model of the data which we are going to work upon i.e. the name and avatar of the user.
  • To do so, look for the file models.py in your app folder and add the code below:-
from django.db import models


# Create your models here.
from django.urls import reverse


class User(models.Model):

    #the variable to take the inputs
    user_name = models.CharField(max_length=100)
    user_avatar = models.FileField()

    # on submit click on the user entry page, it redirects to the url below.
    def get_absolute_url(self):
        return reverse('uploadfileapp:home')
  • The function get_absolute_url in the above code simply returns the url to which the the user entry page is forwaded once the submit button is hit. In this case, it will return to the home page after the user entry adding the currently registered user  to the list.
  • To generate the form, model forms simply access the the models.py. The names of the parameters here become the respective labels in the form followed by a input box.

Registering Model

  • Now we need to register the above model into the admin.py file in the users folder. To do so, add the following code to the admin.py file present in  your app folder.
from django.contrib import admin

# Register your models here.
from uploadfileapp.models import User

admin.site.register(User)
  • By now, the model of the database is ready. But we need to  implement this database into the SQLite db. Doing so the SQLite db will create its own model of the same dataset. To do so,  open the Windows PowerShell and the follow the commands  given below.

Making Migrations

  • Make sure that the shell is navigated into the website  folder and run the following command.
python manage.py makemigrations uploadfileapp
  • Next, run the command below to actually implement it into the database.
python manage.py migrate
  • By now, the database is created into the sqlite db.

Configuring the Views

  • This is where modelforms play an important role in form related tasks and data handling.
  • No request handling for forms and no data is to be manually saved into the database as we work with modelforms.

Hence, look for the file views.py in your app folder and then add the following code:-

from django.shortcuts import render

# Create your views here.
from django.views import generic
from django.views.generic import CreateView

from uploadfileapp.models import User


class HomeView(generic.ListView):
    # name of the object to be used in the index.html
    context_object_name = 'user_list'
    template_name = 'uploadfileapp/home_page.html'

    def get_queryset(self):
        return User.objects.all()


# view for the user entry page
class UserEntry(CreateView):
    model = User
    fields = ['user_name', 'user_avatar']

  • In the above file views.py, the class HomeView generates the list of all the registered user in the form of an arraylist named user_list which is later used in the html files  to display the existing users’ data. Also, the html file to be rendered with this view is  mentioned here in the same.
  • Similarly, in the class UserEntry, the fields have been mentioned according to  which the form is to be created.

That was all we had to do the backend. Now, we gotta take care of the front end.i.e the HTML and the CSS.

Building UI for the app

  • To do so, firstly create a directory named templates into the folder uploadfileapp.
  • Now, in the templates folder, create another directory named uploadfileapp and it should be like /uploadfileapp/templates/uploadfileapp/.
  • In the uploadfileapp folder present in templates directory, create a new HTML file called user_form.html and add the following code:-
<html>
<head>

</head>


    <style>
        body{
            background-color: #2b542c;
        }

        h1{
              color: white;
              background-color:#4cae4c;
              width: 100%;
              float:left;
              height: 50px;
        }

        button{
            width: auto;
            height: 40px;
            text-align: center;
            background-color: #1b6d85;
            color: #ffffff;
            font-size: 30px;
            margin-top: 20px;
        }
    </style>


<body >

<h1>Add a new User</h1>

{% if error_message %}
    <p><strong>{{ error_message }}</strong></p>
{% endif %}
<form action="" method="post" enctype="multipart/form-data">
    {% csrf_token %}
    {% include 'uploadfileapp/form-template.html' %}
    <div class="form-group">
        <div class="col-sm-offset-2 col-sm-10">
            <button type="submit" class="btn btn-success">Submit</button>
        </div>
    </div>
</form>

</body>


</html>

  • The above html generates the input panel for the user’s name and  avatar.
  • Now, in the same folder, create another html file named home_page.html and add the following code:-
<html>
<head>
<title class="title" >

</title>

    <style>
        body{
            background-color: #2b542c;
        }

        h1{
              color: white;
              background-color:#4cae4c;
              width: 100%;
              float:left;
              height: 50px;
        }

        button{
            width: auto;
            height: 60px;
            text-align: center;
            background-color: #1b6d85;
            color: #ffffff;
            font-size: 35px;
        }

        img{
            width: 200px;
            height: 150px;

        }
    </style>


</head>

<body >

<h1> UploadFileApp Users</h1>

{% if user_list %}

    {% for user in user_list %}

    <ul>

    <li>
        <h2>{{ user.user_name }}</h2>
        <img src="{{ user.user_avatar.url }}" >

    </li>


    </ul>


{% endfor %}

    {% else %}
    <h1 class="textNoUsersfound" >No users found.</h1>

{% endif %}



     <form action="{% url 'uploadfileapp:user-entry'  %}" method="post" style="display: inline;"
     >
            {% csrf_token %}
            <button   type="submit">Add a new User</button>
        </form>


</body>
</html>

  • The above html code displays the list of registered users.
  • In the same directory, create one last html file named form-template.html and add the code below .This will serve as a base template for each field in the form. You can see this included in the html of the file user_form.html:-
{% for field in form %}
    <div class="form-group">
        <label style="font-size: 20px;color: white; " >{{ field.label_tag }}</label>
        <div class="input" >{{ field }}</div>
    </div>
{% endfor %}

Setting Up Bootstrap

In this example, we also made use of some of the classes of bootstrap. So to use bootstrap in this project, follow the steps given below:-

  • Go to the link given below and download bootstrap.css file.

bootstrap.min

  • In your app folder, create a folder named static. Next in static folder, create another folder by the name of this webapp i.e. uploadfileapp and add the downloaded bootstrapp.css file into the same.

And your bootstrap is all set.

  • We’re almost done. The UI and backend both are ready. We just need to link the broken ends by configuring the urls. To do so, create a file named urls.py in your app folder and add the code below:-
# /uploadfileapp/
from django.conf.urls import url

from uploadfileapp import views

app_name = 'uploadfileapp'

urlpatterns = [

    # uploadfileapp/
    url(r'^$', views.HomeView.as_view(),name='home' ),

    # uploadifileapp/register
    url(r'^register/$', views.UserEntry.as_view(), name='user-entry'),

]

  • Follow the comments to understand the url patterns in the above code.

Finalizing project-

  • In the folder website, there’s a file called settings.py. Hop over to the bottom of this file until you spot the line “
STATIC_URL = '/static/'
  • Now below the line, add another set of lines as shown below:-
STATIC_URL = '/static/'

MEDIA_ROOT = os.path.join(BASE_DIR,'media')#this line is added and it serves as the root address of 
#uploaded file

MEDIA_URL = '/media/'#this line is added and it creates a directory named media in your appfolder
#where the uploaded images will be stored
  • In the same folder website, look for the url file called urls.py and add the following code:-
from django.conf.urls import url, include
from django.contrib import admin
from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [

    url(r'^uploadfileapp/', include('uploadfileapp.urls')),

]

# if the DEBUG is on in settings, then append the urlpatterns as below
if settings.DEBUG:
    urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
  • Finally, mention your app into the INSTALLED APPS category in the file  settings.py in your website folder as shown below:-
INSTALLED_APPS = [
    'uploadfileapp.apps.UploadfileappConfig',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]
  • Thats’ all. We are done coding the app.
  • And your uploadfileapp is all set to undergo a test run.

Running the App

  • Now lets try running the app. Make sure your development server is running. If not you can use the following command in your Windows PowerShell to run your development server.
python manage.py runserver

Django Upload File  Example

  • Now go to the url http://127.0.0.1:8000/uploadfileapp/ to see your list of user entries:-
Django File Upload
Django File Upload
  • Certainly, it was supposed to give the message saying no user found as no entries yet exist.
  • Now, if we click on “Add a new User ” button, its gonna take us to the url given below:-
  • http://127.0.0.1:8000/uploadfileapp/register/
Django File Upload
Django File Upload
  • Once you make an entry, it’ll take you to the homepage showing the list of registered user as shown below:-
Django File Upload
Django File Upload
  • Bingo! The webapp is working perfectly.
  • If you came across certain errors or dificulties in understading, let me know in the comments section.

So thats all for Django File Upload Tutorial friends. Stay tuned and I will post more useful tutorials that will help you in learning Web Development using Django. Meanwhile you can comment if you want a particular topic to be explained in the coming posts. Thank You 🙂

Django ModelForm Example to Save into Database

Hi there, today we will see Django ModelForm Example. If you remember the last post, we saw how to implement ListView and DetailsView using generic views. We created a page to take an input of the title and description of  a product and then displayed it using ListView and DetailsView.

The point which I am concerned with is that we had to configure the saving of the data into the database ourselves in the last post. Now what if I told you that we don’t need to manage the database operations by our own in this post. Django will do it all for us. Not only that, it will also create forms (without  writing actual html form ), allow us to update(using UpdateView class) and delete the data(using DeleteView class) on the database without actually having to  write any subsequent code for database related tasks.

Yeah, Model forms along the with class based views are meant for the purposes mentioned above. It pretty much simplifies the things for a developer doing database related tasks. I know this just increased your energy level to learn Model forms. So, without any delay, let’s get started.

To learn Model forms, we’ll take  the same  example as in the  previous post which you must go through before moving ahead in this  post. It will help you get a good grasp over class based views.The link is given below.

Django Class Based Views for Implementing List and DetailsView

Django ModelForm Example Overview

We will be doing the following in this Django ModelForm Example

  • Create a Page for entry of a Product information(title, price and description) and save it into the db(which will be done automatically by model forms).
  • Create the index page where we would view the product entries in an unordered list.
  • On the index page, with each product entry, we would also add the delete and update buttons and configure their functions.

Now that you know what we will be dealing with in this post, let’s start coding the app.

Django ModelForm Example

Creating a new Django Project

  • Run your Windows PowerShell in Administrator Mode and run the following command to navigate into the desktop directory :
cd ~/Desktop
  • Run the command below to start a project new django project:
 django-admin startproject website
  • As you do, you will see a  folder on your desktop containing the django files named website
  • Open the folder in any Django IDE or any text editor will work fine.
  • Run the command below to change the directory of PowerShell to the folder “website”:
cd website

Creating a new App inside the Project

  • Run the command below to start a new app into your project.
python manage.py startapp modelforms
  • Here, modelforms is the name of your app. As your run the above command, a folder named modelforms will show up in the website folder.

Coding the App

Creating Model

  • As usual, we need to deal with some data (title, price and desciption). So, we need to create the model of the data and implement that model into the sqlite db of django.
  • To do so, look for the file models.py in your app folder and add the code below:-
from django.db import models

# Create your models here.
from django.urls import reverse


class Product(models.Model):

    product_title = models.CharField(max_length=100)
    product_price = models.CharField(max_length=5)
    product_desc = models.CharField(max_length=100)

    # on submit click on the product entry page, it redirects to the url below. 
    def get_absolute_url(self):
        return reverse('modelforms:index')
  • The function get_absolute_url in the above code simply returns the url to which the the product entry page is forwaded once the submit button is hit. In this case, it will return to the index page after the product entry.
  • To generate the form, model forms simply access the the models.py. The names of the parameters here become the respective labels in the form followed by a input box.

Registering Model

  • Now we need to register the above model into the admin.py file in the users folder. To do so, add the following code to the admin.py file present in  your app folder.
from django.contrib import admin

# Register your models here.
from modelforms.models import Product

admin.site.register(Product)
  • By now, the model of the database is ready. But we need to  implement this database into the SQLite db. Doing so the SQLite db will create its own model of the same dataset. To do so,  open the Windows PowerShell and the follow the commands  given below.

Making Migrations

  • Make sure that the shell is navigated into the website  folder and run the following command.
python manage.py makemigrations modelforms
  • Next, run the command below to actually implement it into the database.
python manage.py migrate
  • By now, the database is created into the sqlite db.

Now comes the section where the real magic happens.

Configuring the Views

  • Yes, the class based views  reduce our efforts to quite an extent.
  • So, look for the file views.py in your app folder and add the following code:-
from django.views import generic
from django.views.generic.edit import CreateView, UpdateView, DeleteView
from django.core.urlresolvers import reverse_lazy

# Create your views here.
from modelforms.models import Product

# view for the index page
class IndexView(generic.ListView):
    # name of the object to be used in the index.html
    context_object_name = 'product_list'
    template_name = 'modelforms/index.html'

    def get_queryset(self):
        return Product.objects.all()

# view for the product entry page
class ProductEntry(CreateView):
    model = Product
    # the fields mentioned below become the entry rows in the generated form
    fields = ['product_title', 'product_price', 'product_desc']

# view for the product update page
class ProductUpdate(UpdateView):
    model = Product
    # the fields mentioned below become the entyr rows in the update form
    fields = ['product_title', 'product_price', 'product_desc']

# view for deleting a product entry
class ProductDelete(DeleteView):
    model = Product
    # the delete button forwards to the url mentioned below.
    success_url = reverse_lazy('modelforms:index')
  • In the above code, we made use of following classes in the views:-
  • generic.ListView- To fetch the data from the db and display it using the html.
  • CreateView- To create the form corresponding to the model of the data as in models.py
  • UpdateView- To create the form for the update of the product info and update the db accordingly.
  • DeleteView- To delete the selected product entry from the db.

By now, the backend of the app is ready.

It’s time to write some htmls i.e working on the templates for this project.

Creating UI for Django model forms example

  • Firstly create a directory named templates into the folder modelforms.
  • Now, in the templates folder, create another directory named modelforms and it should be like /modelforms/templates/modelforms/.
  • In the modelforms folder present in templates directory, create a new HTML file called product_form.html and add the following code:-
 <h3>Add a New Product</h3>

{% if error_message %}
    <p><strong>{{ error_message }}</strong></p>
{% endif %}
<form action="" method="post" enctype="multipart/form-data">
    {% csrf_token %}
    {% include 'music/form-template.html' %}
    <div class="form-group">
        <div class="col-sm-offset-2 col-sm-10">
            <button type="submit" class="btn btn-success">Submit</button>
        </div>
    </div>
</form>
  • In the same directory, create another html file named index.html and add the code below .This will act as a home page and display the list of product_entries.
{% if product_list %}

    {% for product in product_list %}

    <ul>

    <li>
        <h2> Product-Title:{{ product.product_title }}</h2>
        <h2>Price:${{ product.product_price }}</h2>
        <h2>Description:{{ product.product_desc }} </h2>
           <form action="{% url 'modelforms:product-delete' product.id %}" method="post" style="display: inline;">
            {% csrf_token %}
            <button type="submit" class="btn btn-default btn-sm">Delete</button>
        </form>
           <form action="{% url 'modelforms:product-update' product.id  %}" method="post" style="display: inline;">
            {% csrf_token %}
            <button type="submit" class="btn btn-default btn-sm">Update</button>
        </form>


    </li>


    </ul>

{% endfor %}

    {% else %}
    <h1>No product entries found on the database.</h1>


{% endif %}
     <form action="{% url 'modelforms:product-entry'  %}" method="post" style="display: inline;">
            {% csrf_token %}
            <button type="submit" class="btn btn-default btn-sm">Make a Product entry here</button>
        </form>
  • In the same directory, create one last html file named form-template.html and add the code below .This will serve as a base template for each field in the form. You can see this included in the html of the file product_form.html:-
{% for field in form %}
    <div class="form-group">
        <div >
            <span class="text-danger la">{{ field.errors }}</span>
        </div>
        <label  >{{ field.label_tag }}</label>
        <div class="col-sm-10">{{ field }}</div>
    </div>
{% endfor %}
  • We’re almost done. The UI and backend both are ready. We just need to link the broken ends by configuring the urls. To do so, create a file named urls.py in your app folder and add the code below:-
from django.conf.urls import url

from modelforms import views

app_name = 'modelforms'

urlpatterns = [

    # /modelforms/
    url(r'^$', views.IndexView.as_view(), name='index'),

    # modelforms/product/entry
    url(r'^product/entry/$',views.ProductEntry.as_view(),name='product-entry'),

    # modelforms/product/2
    url(r'^product/(?P<pk>[0-9]+)/$', views.ProductUpdate.as_view(), name='product-update'),

    # modelforms/product/(?P<pk>[0-9]+)/delete
    url(r'^album/(?P<pk>[0-9]+)/delete$', views.ProductDelete.as_view(), name='product-delete'),

]
  • Follow the comments to understand the url patterns in the above code.

Finalizing project

  • In the folder website, there’s a file called urls.py. Update that file with code given below:-
from django.conf.urls import url, include
from django.contrib import admin

urlpatterns = [

    url(r'^admin/', admin.site.urls),
    url(r'^modelforms/',include('modelforms.urls'))

]
  • Just one last step. Mention your app into the INSTALLED APPS category in the file  settings.py in your website folder as shown below:-
INSTALLED_APPS = [
    'modelforms.apps.ModelformsConfig',# this line is added
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]
  • That’s it. We are done coding the app.

Running the App

  • Now lets try running the app. Make sure your development server is running. If not you can use the following command in your Windows PowerShell to run your development server.
python manage.py runserver

Django Model Forms Example

Django ModelForm Example
Django ModelForm Example
  • As expected, since the database is empty, it says no product entries found on the database. So, go ahead and hit  the “Make a Product entry here” button and it will to take you to the product_entry page as shown in the image below:-
Django ModelForm Example
Django ModelForm Example
  • Fill the form shown in the image above and hit the submit button. It shall take you to the index page and you will find the  product entry  you just made in the product_list as shown in the image below:-
Django ModelForm Example
Django ModelForm Example
  • In the above image, the delete and update buttons can be seen.So, go ahead and hit the delete button and you will  see the result as shown below. Hitting the delete button simply deletes that particular data from the database.
Django ModelForm Example
Django ModelForm Example
  • If you would have hit the update button, you would have been welcomed by the product entry page. And the data which you entered newly for the product overwrites the previous one.
Django ModelForm Example
Django ModelForm Example
  • Great! It worked out just as expected.
  • You successfully followed this post till the end with full enthusiasm. Congratulations, you are a true django learner. And if you are having some troubles get the source code of this Django ModelForm Example from below.

[sociallocker]Django ModelForm Example Source Code[/sociallocker]

So thats all for this Django ModelForm Example friends. Stay tuned for more Django Tutorials. And please do share the post if you found it helpful. Thank You 🙂

Django Class Based Views for Implementing List and DetailsView

Hi there, this post is about one of the important and general features of Django and you guessed it right. Yeah, it’s about the  Django Class Based Views (Generic Views) and its usage to implement the ListView and DetailsView on a model of data. Now, you might be wondering what acutally do I  mean when I say Generic Views, Django Class Based Views, ListView and Detail View and all stuff. Hold your curiosity. I am gonna walk you through all these concepts.

These days, most of the websites follow a pattern in which one page shows a list of  things and the other page shows the details of the thing selected on the previous page.  For example, consider this very blog, simplifiedpython.net. As you visit it, you are welcomed with a list of posts which is called ListView and as you click on any post, another page shows up giving the details of the post which is called DetailView. Now, you might think that now I know what listview and detailsview are but how do I implement them. This is exactly where generic views comes into play and simplifies things.

Generic Views are basically class based views. These are usually used for the implementation of ListView and DetailView. These have inbuilt functionality and methods to simplify achieving the same. So now that you know the stuff, let’s start coding with generic views:-

As an example to learn generic views, we will be creating a webapp which would do the following:-

  • It shall display a list of watches for sale.@http://127.0.0.1:8000/genericviews/
  • When clicked on any product, it shall show the details of the selected product.
  • It shall accept new watch details i.e. the title and description of the watch.@http://127.0.0.1:8000/genericviews/makeentry and save them into the db to be later shown in the listview.

Django Class Based Views Example

Creating a new Django Project

  • Run your Windows PowerShell in Administrator Mode and run the following command to navigate into the desktop directory :
cd ~/Desktop
  • Run the command below to start a project new django project:
 django-admin startproject website
  • As you do, you will see a  folder on your desktop containing the django files named website
  • Open the folder in any Django IDE or any text editor will work fine.
  • Run the command below to change the directory of PowerShell to the folder “website”:
cd website

Creating a new App inside the Project

  • Run the command below to start a new app into your project.
python manage.py startapp genericviews
  • Here, genericviews is the name of your app. As your run the above command, a folder named users will show up in the website folder.

Coding the App

Creating Model

  • In the app folder genericviews, there’s a file called models.py. To configure the database, we need a model of the data we will be dealing with. To do so, add the following code to the models.py python file.
from django.db import models


# Create your models here.

class Product(models.Model):
     # title of the watch
     title = models.CharField(max_length=100)
     # description of the watch
    desc = models.CharField(max_length=300)

    def __str__(self):
        return self.title

Registering Model

  • Now we need to register the above model into the admin.py file in the users folder. To do so, add the following code to the admin.py file present in  users folder.
from django.contrib import admin

# Register your models here.
from genericviews.models import Product

admin.site.register(Product)
  • By now, the model of the database is ready. But we need to  implement this database into the SQLite db. To do so,  open the Windows PowerShell and the follow the commands  given below.

Making Migrations

  • Make sure that the shell is navigated into the website  folder and run the following command.
python manage.py makemigrations genericviews
  • Next, run the command below to actually implement it into the database.
python manage.py migrate
  • By now, the database is created into the sqlite db.

Building the Form

  • In the app folder genericviews, create a new python  file called forms.py. To configure the form through which the input is to be taken, code this file forms.py with the code below.
from django import forms


class ProductForm(forms.Form):

    # variable for the title of the product
    title = forms.CharField(label="Title", max_length=100)
    # variable for the description of the product
    desc = forms.CharField(label="Description", max_length=300, help_text="Write a brief of the product.",widget=forms.Textarea)
  • Until now, you went through lot of things in the above instructions and you must be wondering that where the heck is  generic views. Well, your wait is over. Next, we need to  configure the views.py  file in the genericviews app folder where we would actually see generic view being used. So, go ahead and add the code below to the views.py file:-
from django.shortcuts import render

# Create your views here.
from django.views import generic

from genericviews.forms import ProductForm
from genericviews.models import Product


# normal view to handle the entry of the product and store it on the database
def makeentry(request):
    if request.method == 'POST':
        form = ProductForm(request.POST)

        if form.is_valid():
            title = request.POST.get('title', '')
            desc = request.POST.get('desc', '')

        product = Product(title=title, desc=desc)
        product.save()

        form = ProductForm()

        return render(request, 'genericviews/makeentry.html', {'form': form})
    else:
        form = ProductForm()
        return render(request, 'genericviews/makeentry.html', {'form': form})


# generic view to fetch the data then show in a list 
class IndexView(generic.ListView):
    
    # a name to refer to the object_list(to be used in the index.html)
    context_object_name = 'product_list'
    template_name = 'genericviews/index.html'

    def get_queryset(self):
        return Product.objects.all()


# generic view to show the details of a particular object 
class DetailsView(generic.DetailView):
    model = Product
    template_name = 'genericviews/detail.html'

Making URL Pattern for Form

  • Next, in the app folder called  genericviews, create a new python file  named ‘urls.py’ and add the code below:-
from django.conf.urls import url

from genericviews import views

app_name = 'genericviews'

urlpatterns = [

        url(r'^$', views.IndexView.as_view(), name='index'),
        url(r'^(?P<pk>[0-9]+)/$', views.DetailsView.as_view(), name='detail'),
        url(r'^makeentry$', views.makeentry, name='makeentry'),
]
  • By now, we are all done with the backend of this app.

Creating UI for Django generic Views (class based views) example

  • Firstly create a directory named templates into the folder genericviews.
  • Now, in the templates folder, create another directory named genericviews and it should be like /genericviews/template/genericviews.
  • In the genericviews folder present in templates directory, create a new HTML file called makeentry.html and add the following code, it contains the UI used to take input.
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Product Entry</title>
</head>
<body>

    <form action="{% url 'genericviews:makeentry' %}" method="post">
    {% csrf_token %}
   {{ form }}
    <input type="submit" value="Submit">
    </form>


</body>
</html>
  • In the same directory, create another html file named index.html and add the code below .This will act as a home page and display the list of watches.
{% if product_list %}

    <h1>Buy Wrist Watches! </h1>
<ul>
    {% for product in product_list %}

    <li> <a href="{% url 'genericviews:detail' product.id %}">{{ product.title }}</a> </li>
    {% endfor %}
</ul>
{#  In case  no product exists.  #}
{% else %}
<h3> No product found.</h3>
{% endif %}

  • In the same directory, create one last html file named detail.html and add the code below .This will act as a second page and display the detail of the selected watch:-
<h1>{{ product.title }}</h1>
<h3>{{ product.desc}}</h3>

Finalizing project

  • In the folder website, there’s file called urls.py. Update that file with code given below:-
urlpatterns = [

    url(r'^admin/', admin.site.urls),
    url(r'^genericviews/', include('genericviews.urls')),



]
  • Finally in the folder website , there’s another file called settings.py. We need to register the app ‘genericviews‘ into the installed apps category in this file settings.py. To do so, look for the INSTALLED APPS category in settings.py and then register the app as show below :-
INSTALLED_APPS = [
    'genericviews.apps.GenericviewsConfig',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]

That’all. We’re done with coding the app.

Running the App

  • Now lets try running the app make sure your development server is running. If not you can use the following command into your Windows PowerShell to run your development server.
python manage.py runserver

Django Class Based Views (Generic Views) Example

  • Now go to the url http://127.0.0.1:8000/genericviews/makeentry to see your product form to make an entry:-
Django Class Based Views
Django Class Based Views
  • Make 3-4 entries in the form shown above. It shall be stored on the database as you hit submit .
  • Now that we have the data of certain products into our database, we are good to see the listview showing the list of watches.
  • So,  Go to the url:-http://127.0.0.1:8000/genericviews/ and you shall a list of watches as shown in the image below:-
Django Class Based Views
Django Class Based Views
  • Now, if you click on any of the watches, it shall take you the details section as you had entered it.
Django Class Based Views
Django Class Based Views
  • Now if you are still having troubles implement Django Class Based Views then you can get my source code from below.

[sociallocker] Django Class Based Views Source Code [/sociallocker]

So thats all for this Django Class Based Views Tutorial. You can leave your comments below to have a discussion about the queries and confusions. Thank You 🙂

Django Form Validation Example – Simple Form Validation

In last post we learnt simple Django Form Example. In this post we will see again a very simple Django Form Validation Example. Validating inputs is a very essential part of any application whether it is web or mobile. And here is the framework comes with very handy option to add Form Validations. Django has very easy form validation options for certain fields such as email and url. For all other custom validations to be imposed on the inputs, we need to configure them explicitly. In this  Django Form Validation Example we will see how to use them.

In this example, we will be taking input of four parmeters namely email, mobno, password and url and then also set validation upon them. The validation of email, mobile number and url will be achieved implicitly(you’ll understand it in forms.py) however for password, we’ll be defining custom validation explicitly.

To do so, we’ll be working on Windows PowerShell in Administrator Mode and any text editor will work fine.

So, without wasting any time let’s get started.

Django Form Validation Example

Creating a new Django Project

  • Run your Windows PowerShell in Administrator Mode and run the following command to navigate into the desktop directory :
cd ~/Desktop
  • Run the command below to start a project new django project:
 django-admin startproject website
  • As you do, you will see a  folder on your desktop containing the django files named website
  • Open the folder in any Django IDE or any text editor will work fine.
  • Run the command below to change the directory of PowerShell to the folder “website”:
cd website

Creating a new App inside the Project

  • Run the command below to start a new app into your project.
python manage.py startapp contact
  • Here, contact is the name of your app. As your run the above command, a folder named contact will show up in the website folder.

Coding the App

Building the Form

  • In the app folder contact, create a new python  file called forms.py. To configure the form through which the input is to be taken, code this file forms.py with the code below.
import string

from django import forms


class UserForm(forms.Form):
    # to take the input of email #Implicit Validatiom
    email = forms.EmailField(label='Enter your email', max_length=100)

    # to take input of mobile number #Implicit Validation             #to take just numbers as input
    mobno = forms.CharField(label='Enter your mobile number', max_length=15, widget=forms.NumberInput)

    # to take the input of password                         # to make password hidden
    password = forms.CharField(label='Enter your password', widget=forms.PasswordInput)

    # to take the input of URL of website #Implicit Validation
    link = forms.URLField(label='Enter the URL to your website')

    # validator for password(Explicit Validation for Password)
     def clean_password(self):
        password = self.cleaned_data.get('password')
        letters = set(string.ascii_letters)
        digits = set(string.digits)
        pwd = set(password)
        if pwd.isdisjoint(letters) or pwd.isdisjoint(digits):
            raise forms.ValidationError('Password must be alphanumeric.')

        return password
 # similarly def clean_email(self): would be validator for email
 # these clean methods are exexuted when form.is_valid() function is called

Making URL Pattern for Form

  • Next, in the app folder called contact, create a new python file  named ‘urls.py’ and add the code below:-
from django.conf.urls import url
from . import views

app_name = 'contact'

urlpatterns = [

    # /contact/signup:url to take the input from the user
    url(r'^signup$', views.signup, name='signup'),
]
  • Next, in the app folder called contact, there’s a file called views.py. It contains all the functions to be executed associated with different urls. To configure the current app, add the following code to the views.py.
from django.shortcuts import render
from contact.forms import UserForm


# the function executes with the signup url to take the inputs
def signup(request):
    if request.method == 'POST':  # if the form has been filled

        form = UserForm(request.POST)

        if form.is_valid():  # All the data is valid
            return render(request, 'contact/signup.html',
                          {'all_okay': True})  # Redirect after POST
        else:
            return render(request, 'contact/signup.html', {'form': form, 'all_okay': False})
    else:
        form = UserForm()  # an unboundform

        return render(request, 'contact/signup.html', {'form': form})
  • By now, the backend of the app ‘contact‘  is ready

Creating UI for Django Form Validation Example

  • Firstly create a directory named template into the folder contact.
  • Now, in the template folder, create another directory named contact and it should be like /contact/template/contact.
  • In the contact folder present in template directory, create a new HTML file called signup.html and add the following code, it contains the UI used to take input
<!-- The alert box to be shown when the submit button is clicked-->
{% if all_okay %}
    <script>alert("All data inputs are valid.")</script>
{% else %}
    <form action="{% url 'contact:signup' %}" method="post">
    {% csrf_token %}
   {{ form }}
    <input type="submit" value="Submit">
    </form>
    {% if errors %}
   {% for key, error_list in errors.iteritems %}
       {{key}} : {{error_list}}
   {% endfor %}
{% endif %}

{% endif %}

Finalizing the Things

  • In the folder website, there’s file called urls.py. Update that file with code given below:-
from django.conf.urls import url, include
from django.contrib import admin

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^contact/', include('contact.urls')),
]
  • Finally in the folder website , there’s another file called settings.py. We need to register the app ‘contact’ into the installed apps category in this file settings.py. To do so, look for the INSTALLED APPS category in settings.py and then register the app as show below :-
INSTALLED_APPS = [
    'contact.apps.ContactConfig',#this line is added
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]

That’all. We’re done with coding the app.

Running the App

  • Now lets try running the app. Make sure your development server is running. If not you can use the following command into your Windows PowerShell to run your development server.
python manage.py runserver

Django Form Validation Example

  • Now go to the url http://127.0.0.1:8000/contact/signup/ to see your form
Django Form Validation Example
Django Form Validation Example
  • When the email entered is invalid, an error pops up as shown in the image below.
Django Form Validation Example
Django Form Validation Example
  • When the mobile number entered is invalid, an error pops up as shown in the image below:-
Django Form Validation Example
Django Form Validation Example

 

  • When the password entered does not fulfill the required criterias(here, it must be alphnumberic), an error pops up as shown in the image below:-
Django Form Validation Example
Django Form Validation Example
  • When the URL entered is invalid, the following error pops up:-
Django Form Validation Example
Django Form Validation Example
  • Now when all the fields are correctly filled, an alert pops up as shown in the image below:-
Django Form Validation Example
Django Form Validation Example

So, as you saw, the form validation is working successfully. Similarly, you can create custom validations for whatever fields are required. So thats all for this Django Form Validation Example. You can also get the source code from the below link.

[sociallocker] Django Form Validation Example Download [/sociallocker]

If you find any trouble regarding this Django Form Validation Example, do let me know in the comments.

Django Save Form Data to Database and Retrieve It

Hello friends, in this Django Save Form Data to Database Tutorial, I am gonna walk you through how to set up an HTML Form, Fetch its Data and store it onto the SQLite database in Django.

Once we are done storing the data into the db, we will also learn how to retrieve the data from the database. As an example, we will take the input of user’s name, email and password and store it on the database. Later, we will also retrieve the list of registered users.

To do so, we’ll be working on Windows PowerShell in Administrator Mode and any text editor will work fine.

So, without wasting any time let’s get started.

Django Save Form Data to Database

Creating a new Django Project

  • Run your Windows PowerShell in Administrator Mode and run the following command to navigate into the desktop directory :
cd ~/Desktop
  • Run the command below to start a project new django project:
 django-admin startproject mywebsite
  • As you do, you will see a  folder on your desktop containing the django files named mywebsite
  • Open the folder in any Django IDE or any text editor will work fine.
  • Run the command below to change the directory of PowerShell to the folder “mywebsite”:
cd mywebsite

Creating a new App inside the Project

  • Run the command below to start a new app into your project.
python manage.py startapp users
  • Here, users is the name of your app. As your run the above command, a folder named users will show up in the mywebsite folder.

Coding the App

Creating Model

  • In the app folder users, there’s a file called models.py. To configure the database, we need a model of the data we will be dealing with. To do so, add the following code to the models.py python file.
from django.db import models


class User(models.Model):
    #to store the name of the user
    username = models.CharField(max_length=100)
    #to store the email of the user
    email = models.CharField(max_length=100)
    #to store the password of the user
    password = models.CharField(max_length=100)

#this returns the name of the user when the object of user is printed
    def __str__(self):
        return self.username

Registering Model

  • Now we need to register the above model into the admin.py file in the users folder. To do so, add the following code to the admin.py file present in  users folder.
from django.contrib import admin
from .models import User

# Register your models here.

admin.site.register(User)
  • By now, the model of the database is ready. But we need to  implement this database into the SQLite db. To do so,  open the Windows PowerShell and the follow the commands  given below.

Making Migrations

  • Make sure that the shell is navigated into the mywebsite  folder and run the following command.
python manage.py makemigrations users
  • Next, run the command below to actually implement it into the database.
python manage.py migrate
  • By now, the database is created into the sqlite db.

Building the Form

  • In the app folder users, create a new python  file called forms.py. To configure the form through which the input is to be taken, code this file forms.py with the code below.
from django import forms

class UserForm(forms.Form):
    #to take the input of username
    username = forms.CharField(max_length=100)
    # to take the input of email
    email = forms.CharField(max_length=100)
    # to take the input of password
    password = forms.CharField(max_length=100)

Making URL Pattern for Form

  • Next, in the app folder called users, create a new python file  named ‘urls.py’ and add the code below:-
from django.conf.urls import url
from . import views

app_name = 'users'

urlpatterns = [

    # /users/signup:url to take the input from the user
    url(r'^signup$', views.signup, name='signup'),
    #/users/showdata:url to display the list of users stored on the database
    url(r'^showdata$', views.showdata, name='showdata'),
]
  • Next, in the app folder called users, there’s a file called views.py. It contains all the functions to be executed associated with different urls. To configure the current app, add the following code to the views.py.
from django.shortcuts import render
from users.forms import UserForm
from users.models import User

#the function executes with the signup url to take the inputs 
def signup(request):
    if request.method == 'POST':  # if the form has been filled

        form = UserForm(request.POST)

        if form.is_valid():  # All the data is valid
            username = request.POST.get('username', '')
            email = request.POST.get('email', '')
        password = request.POST.get('password', '')
        # creating an user object containing all the data
        user_obj = User(username=username, email=email, password=password)
        # saving all the data in the current object into the database
        user_obj.save()

        return render(request, 'users/signup.html', {'user_obj': user_obj,'is_registered':True }) # Redirect after POST

    else:
        form = UserForm()  # an unboundform

        return render(request, 'users/signup.html', {'form': form})

#the function executes with the showdata url to display the list of registered users
def showdata(request):
    all_users = User.objects.all()
    return render(request, 'users/showdata.html', {'all_users': all_users, })



  • By now, the backend of the app ‘users‘  is ready.

Creating UI for Django Save Form Data to Database

  • Firstly create a directory named template into the folder users.
  • Now, in the template folder, create another directory named users and it should be like /users/template/users.
  • In the users folder present in template directory, create a new HTML file called signup.html and add the following code, it contains the UI used to take input
<!-- The alert box to be shown when the submit button is clicked-->
{% if is_registered %}
    <script>alert("You are successfully registered with Username:{{user_obj.username }} and Email: {{ user_obj.email }}")</script>
    {% else %}
    <form action="{% url 'users:signup' %}" method="post">
    {% csrf_token %}
   {{ form }}
    <input type="submit" value="Submit">
    </form>
{% endif %}

Retrieving from Database

  • Next, in the same folder, create another html file named showdata.html and add the following code. It contains the UI to display the list of registered users.
{% if all_users %}

    <h1>Here is the list of users.</h1>
<ul>
    {% for user in all_users %}

    <li> Name:{{ user.username }} Email:{{ user.email  }} Password:{{ user.password }}</li>
    {% endfor %}
</ul>
{#  In case  no user exists.  #}
{% else %}
<h3> No users found.</h3>
{% endif %}

Finalizing the Things

  • In the folder mywebsite, there’s file called urls.py. Update that file with code given below:-
from django.conf.urls import url, include
from django.contrib import admin

urlpatterns = [


    url(r'^admin/', admin.site.urls),
    url(r'^users/', include('users.urls')),
]
  • Finally in the folder mywebsite , there’s another file called settings.py. We need to register the app ‘users’ into the installed apps category in this file settings.py. To do so, look for the INSTALLED APPS category in settings.py and then register the app as show below :-
INSTALLED_APPS = [
    'users.apps.UsersConfig',#this line is added
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]

That’all. We’re done with coding the app.

Running the App

  • Now lets try running the app make sure your development server is running. If not you can use the following command into your Windows PowerShell to run your development server.
python manage.py runserver

Django Save Form Data to Database

  • Now go to the url http://127.0.0.1:8000/signup/ to see your form
Django Save Form Data to Database
Django Save Form Data to Database
  • As you fill data into the boxes and hit the submit button, you will see an alert box as shown below:-
Django Save Form Data to Database
Django Save Form Data to Database

Django Retrieve Data from Database

  • Now go to the url http://127.0.0.1:8000/showdata/ to see the list of registered users as shown in the image below:-
Django Save Form Data to Database
Django Save Form Data to Database
  • Bingo! Its working absolutely fine. If you are still facing troubles you can get my source code from below link.

[sociallocker][download id=”331″] [/sociallocker]

So thats it for Django Save Form Data to Database and Retrieve it tutorial friends. Feel free to leave your comments if you are having any queries or confusions. Also give me a thumbs up and share this post if you found this helpful. Thank You 🙂

Django Forms Example – Generating Forms with Django Form Class

In this Django Forms Example we will see how to use Django Form class to generate Web Forms. A form is very basic need of any web application. And generating forms in Django using the Form class is very easy. And thats it what we will be learning in this Django Forms Example.

If you are an absolute beginner in Python Django you should start reading from the first post. You can go to the first post from the link given below.

Python Django Tutorial for Beginners

This time we will use Sublime Text Editor, as I got request that many of you don’t have PyCharm IDE, as it is a paid tool. And I got a MAC as well so I will be crating the project from Scratch using terminal. You can use the same with power shell as we did in the very first Django Tutorial. So lets start this Django Forms Example.

Starting a New Django Project

  • First create a new directory, I am creating a directory in my desktop.

django forms example

  • Now open terminal and navigate to this folder.
  • Now run the following command to create a virtual environment.
$ virtualenv .
  • It will create a virtual environment in the current directory. Now we need to activate it. So run the following command.
$ source bin/activate
  • Now install Django Framework using the following command.
$ pip install django
  • Now lets create a new Django Project using the following command.
$ django-admin.py startproject DjangoFormExample
  • In the above command DjangoFormExample is our project name you can change it to whatever you want.
  • Now navigate to your project directory.
$ cd DjangoFormExample
  • Now try running your project using the following command.
$ python manage.py runserver
  • If you are getting the following message on terminal then its fine. If not recheck the process 😛

django form example

  • You can go to the given IP to test your project.
  • Now open the Project Folder to your Editor, I am using Sublime as it is really cool.

django forms example sublime

Starting a New Application

  • We have the project running now we will create a new app inside our project. To create a new app write the following command in terminal.
$ python manage.py startapp newsletter
  • After running this command you will get a new folder created inside your project named newsletter.
  • Now inside this newsletter folder create a new folder named templates. We will store our html files inside this folder.

Creating Form

  • Inside newsletter folder create a new file named forms.py. Inside this file we will create our Form.
#importing forms
from django import forms 

#creating our forms
class SignupForm(forms.Form):
	#django gives a number of predefined fields
	#CharField and EmailField are only two of them
	#go through the official docs for more field details
	name = forms.CharField(label='Enter your name', max_length=100)
	email = forms.EmailField(label='Enter your email', max_length=100)
  • Currently we are using CharField and EmailField. Go to this link to know about the available form fields in Django.

Creating View

  • Come inside views.py to create a new view for our form.
from django.shortcuts import render

# Create your views here.

def signupform(request):
	#if form is submitted
	if request.method == 'POST':
		#will handle the request later

	else:
		#creating a new form
		form = SignupForm()

	#returning form 
	return render(request, 'signupform.html', {'form':form});

Defining URL Pattern for Form

  • Now we need a path to show up our form in browser. So come inside urls.py file and modify it as follows.
from django.conf.urls import url
from django.contrib import admin

#importing views from newsletter app 
from newsletter import views as newsletter_views

urlpatterns = [
	#defining url for form
	url(r'^signup/', newsletter_views.signupform),
	
    url(r'^admin/', admin.site.urls),
]

Creating Template

  • Now we need an html file named signupform.html, as it is the file we are rendering from our view. Create this file inside the templates folder we created.
<form action="/signup/" method="post">
    {% csrf_token %}
    {{ form }}
    <input type="submit" value="Submit" />
</form>

What we did?

  • If you remember the last Django Forms Tutorial, in that post we disabled the csrf protection. But we should not do this, so this time I am using the csrf protection system of Django.
  • Then we are rendering the form from the view.

Adding App in Settings

  • Finally we need to add the app in settings.py of the main project folder.
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'newsletter'
]
  • As you can see we added our newsletter app at the bottom.

Running the App

  • Now lets try running the app make sure your development server is running. If not you can use the following command to run your development server.
$ python manage.py runserver
  • Now go to the url http://127.0.0.1:8000/signup/ to see your form
django forms example output
Django Forms Example
  • If you will submit the form it will not work as we have not handled the for submission yet.

Handling Form Submission

  • Again come inside views.py and modify the code as below.
from django.shortcuts import render

from .forms import SignupForm
# Create your views here.

def signupform(request):
	#if form is submitted
	if request.method == 'POST':
		#will handle the request later
		form = SignupForm(request.POST)

		#checking the form is valid or not 
		if form.is_valid():
			#if valid rendering new view with values
			#the form values contains in cleaned_data dictionary
			return render(request, 'result.html', {
					'name': form.cleaned_data['name'],
					'email': form.cleaned_data['email'],
				})

	else:
		#creating a new form
		form = SignupForm()

	#returning form 
	return render(request, 'signupform.html', {'form':form});
  • To complete this we need one more file named result.html inside our templates folder.
<h4>Thanks for Signing Up</h4>
<table>
<tr>
<td>
	Name
</td>
<td>
 	{{ name }}
</td>
</tr>
<tr>
<td>
	Email
</td>
<td>
	{{ email }}
</td>
</tr>
</table>
  • Now try submitting the form.
django forms example
Django Forms Example
  • Bingo! Its working absolutely fine. If you are still facing troubles you can get my source code from below link.

[sociallocker]  [download id=”274″] [/sociallocker]

So thats all for this Django Forms Example. And in the next post we will learn how to insert the form data to database in Django. Thank you 🙂

Python SQLite3 Tutorial to Perform Basic Database Operation

Hello guys, welcome to Python SQLite3 Tutorial. Today in this Python SQLite3 Tutorial we will learn to perform some basic database operations in SQLite3 database with Python. So let’s start our Python SQLite3 Tutorial.

Python SQLite3 Tutorial

#Introduction to SQLite

Before we start covering this Python SQLite3 tutorial I want to give a brief introduction to those who are not familiar with SQLite at all. SQLite is basically a database management system where we can store our data for future use. Every programming software needs data to operate on. This is where we store our relevant data. Further, these data can be retrieved and can be manipulated accordingly.

Here is an example of how the data are stored in a database management system.

Student Id Student Name Student Roll Student Ph. No
101 Mehtab 374 7549161023
102 Vivek 375 8877009587
103 Sumit 376 9798162302

This is a basic view of any database. In SQL we store data in the form of tables. Every record is entered in each row of the table. Table’s columns and their types are well defined and every record entered in the table should fit the table definition. The data types of the each column should be kept in mind too while creating the table.

#Using SQLite3 in Python

Now the next question is how to use SQLite database in python?

For that, first we need to import the SQLite library so that we can use predefined methods/functions or you may say the SQLite modules in python programming. Then we have to create a connection to the database. And to do so we need to create a connection object which is then linked to the database that we will operate on. How to do this has been shown below:-

import sqlite3
conn = sqlite3.connect(‘database.db’ [other optional arguments])

Explanation:

Now at this stage, you guys must be familiar with importing libraries and what this is all about. What needs an explanation is

conn = sqlite3.connect( database_name.db [ other_optional_arguments ] )

Here “conn” is the name of an object that is being associated with the database that we are using. In this example, the name of the database that we are using is ‘database.db’ , .db is the extension of course. The connect() method is a factory function in the SQLite library. Inside this connect() method we provide some arguments such as the name of our database. There are a lot more arguments that can be used which we will discuss later in this Python SQLite3 Tutorial Series. But for instance, we are using only one argument that is the name of the database which we are using that is “database.db”.

Now the name of the connection object that we created is very important because at times we may need to operate on more than one databases in one block of a program so by using the name of the connection object we can identify that for which database we are executing which SQL statement.

#Writing SQL statements in python

Here the problem is, we cannot write SQL statements in python directly. So we need another method which will serve the purpose that is execute() method. Below I have shown how to use this method to execute the SQL statements in python.

Example :

conn.execute(‘sql_statements’)

We are using the connection object “conn” that we created with the execute() method and inside the argument section of the execute() method we write the SQL statements that we want to execute for that specific database which is connected to that connection object ‘conn’.

#Some basic SQLite operations in python

Now in this part of the Python Sqlite3 Tutorial I have demonstrated how to perform some basic operations like creating a table, inserting records into them, updating records, fetching data from a database and to delete/drop the table. These are the most basic operations that come in handy for any  programmer that needs a database to store any kind of data.

Creating a table

In a database we store data in the form of records into the tables and for that first we need to create a table first. So in order to create a table what we need to do is given below :-

import sqlite3
conn = sqlite3.connect('database.db') 
print('Database connection created.') 
conn.execute('''create table Student 
(S_id int primary key, 
S_name text, 
S_roll int, 
S_phone int)''') 
print ('Table created.') 
conn.close()

The output of the above program will look like this:-

We are creating a table named student having 4 attributes ( S_id , S_name , S_roll , S_phone ). Here the S_id will be our primary key as we have specified. Now we have to be very careful with the definition of the table that is the name and datatypes of the attributes used should be declared accordingly and the records should be entered strictly according to the definition of the table. ‘ connection’ is the connection object and ‘ database ‘ is the name of the database that we are using in this example.
In this post I have covered up the connect() method and execute() method before. In this example We have used a new method that is close() method. This is used to end the connection that we had created with the database

Inserting a record into the table

To insert a record into a table the SQLite statement is

insert into Table_Name (Column_Names) values(Values_to_be_Inserted)

 Now what we have to do is just execute it using the execute() method and for that, we need the following code :-

import sqlite3
conn = sqlite3.connect('database.db')
print('Database connection created.')
conn.execute('insert into Student (S_id , S_name , S_roll , S_phone) values ( 101 , "Mehtab Hameed" , 374 , 9586774120 )')
conn.execute('insert into Student (S_id , S_name , S_roll , S_phone) values ( 102 , "Vivek Raj", 375, 8877009587 )')
conn.execute('insert into Student (S_id , S_name , S_roll , S_phone) values ( 103 , "Sumit Mishra" , 376 , 9570123674 )')
conn.execute('insert into Student (S_id , S_name , S_roll , S_phone) values ( 104 , "Belal Haque" , 377 , 7008564196 )')
conn.commit()
print("Values Inserted.")
conn.close()

The output for the above program will look like this :-

SQLite3 Python Tutorial Insert Output

Fetching Data from the Table

Now to operate on the data stored in the database, first of all, we need to fetch that data from our database. And then use them accordingly. Now in SQLite, the code for fetching a record is

select column_name from table_name

And the code is

import sqlite3
conn = sqlite3.connect('database.db')
info = conn.execute('select S_id , S_name , S_roll , S_phone from Student')
for line in info:
    print (line)
conn.close()

What this code does is that we are declaring a variable named info and the value returned by the execute() method, is initialised to it. And to print the values stored in the variable info we are using a for loop to print a row/line at a time until there is no line left.

The output for the above code will produce the following output :-

SQLite3 Python Tutorial Fetch Data Output

Another thing to be jotted down is that if we intend to select all the columns of the table we can use the ” ” (asterisk mark) instead of specifying all the attributes.

import sqlite3
conn = sqlite3.connect('database.db')
info = conn.execute('select * from Student')
for line in info:
    print (line)
conn.close()

This will also have the same output as that of the code above.

Now suppose that we only want to  view  the names of the students and their corresponding contact numbers and leave out other attributes we only specify the attribute that stores the names of the students only. For example :-

import sqlite3
conn = sqlite3.connect('database.db')
info = conn.execute('select S_name , S_phone from Student')
for line in info:
    print (line)
conn.close()

The output for the code will be like this :-

SQLite3 Python Tutorial Fetch Specific Data Output

Updating a specific Record

There may be situations when we need to update or modify a specific data like if a student’s phone number has been changed and it needs to be updated in our database, at times like that, this part plays an important role. Updation of a record is also very simple. It goes like :-

import sqlite3
conn = sqlite3.connect('database.db')
conn.execute('update Student set S_phone = 7002245389 where S_id=101')
info = conn.execute('select S_id , S_name , S_roll , S_phone from Student')
for line in info:
print (line)
conn.close()

the SQLite code to update a record is

select table_name set column_name = new_value where condition

To execute it in python we incorporate this SQLite code with the execute() method. And, this will serve the purpose for us.

The output is as follows :-

Sqlite3 Python Tutorial Update output

Deleting OR Dropping a table

Now there may be situations when we need to delete or drop a table completely. For that we need to execute a simple SQL statement that is (‘drop table if exists table_name’) by using the execute() method. This is as simple as that. And in our case the connection object is ‘conn’ and the table name is student so our code will be as follows

import sqlite3
conn = sqlite3.connect('database.db') 
conn.execute('drop table if exists Student' ) 
conn.close()

For this code the output screen will be this one

SQLite3 Python Tutorial Drop Table Output

So in this tutorial we learnt how to create a connection to the database using connect() method and how to execute the SQL statements using the execute() method. If you are having troubles then you can get the source code from the link given below.

 [sociallocker][download id=”242″][/sociallocker]

That’s all for my Python SQLite3 tutorial. In the next tutorial, we will see some more complex SQL operations in python. Thank You 🙂

Django Database API – Saving Data in SQLite using Models

Hello friends, in last Django tutorial we learnt about Handling HTML Forms in Django. Today we will learn about Django Database API. The best thing is Django Database API is you do not need to write SQL statements, Django will do it for you. Pretty Amazing Right? So lets see what is Django Database API and Database Models.

So lets start our Django Database API Tutorial. We will start from creating a new Django Project. I am using PyCharm.

Django Database API Tutorial

Creating a Django Project

  • Open PyCharm and create a new Django Project. I created DatabaseExample.

django database api

  • We will now create an app inside your project. (If you remember the first Python Django Tutorial for Beginners).
  • But this time we can use the inbuilt terminal of PyCharm to execute commands. To open terminal go to View -> Tool Windows -> Terminal (or simply press alt + F12)

django database api

  • On your terminal execute the command python manage.py startapp <yourappname> to create a new app. In below screenshot you can see I have created an app named Inventory.

django database api

Creating Models

Models in Django is basically blueprint of your database table. And it is the coolest thing as when we are using models, we do not need to create any database table. Each model in our Django maps to the table. And every variable in our Model is a column in the table.

In this tutorial I will create two Models Categories and Products. Both models (tables) will be connected by using Primary and Foreign Key. I hope you already know about Primary and Foreign Keys.

Now follow these steps to make your models.

  • Come inside models.py inside your app directory. (See the screenshot for help).

django database api

  • Write the following code inside models.py file of your app directory.
from django.db import models

#Create your models here.

class Category(models.Model):
    categoryName = models.CharField(max_length=100)

class Product(models.Model):
    productCategory = models.ForeignKey(Category, on_delete=models.CASCADE)
    productName = models.CharField(max_length=100)
    productPrice = models.IntegerField()
    productBrand = models.CharField(max_length=100)

What we did?

In the above code we have created two classes. First class is our model for Category table. The second class is model for Product table. Both tables are connected with primary key and foreign key. Actually whenever we create a model Django creates a column id automatically which is Primary Key. It is a cool thing that we do not need to create tables by running SQL statements, all these things are done by Django.

So finally we have

  • A model Category, it has a variable categoryName, which is a CharField (that means we can store characters in it). Other than this Django will create a variable named id in this model, and the id will be an Auto Increment Integer. And this id will be the Primary Key for our table.
  • A model Product, it has the following variables.
    productCategory -> To store the category id, and it is foreign key.
    productName -> To store name of product.
    productPrice -> To store price of product.
    productBrand -> To store price of product.

Activating our Model

We have created our models, now we need to activate it. As currently it is only in code format and the database is not created yet. To complete the table creation in database we need to activate the models we created. Follow these steps to activate your models.

  • Go inside your project’s settings.py file.

django database api

  •  In this file you will see INSTALLED_APPS, it contains the package of all the apps installed. We need to define our inventory app here. So modify your code as follows.
INSTALLED_APPS = [
    #defining our app here 
    'inventory.apps.InventoryConfig',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]
  • After doing this run your project. And then open terminal (alt + F12) and run the following command
python manage.py makemigrations inventory
python manage.py migrate
  • On executing the above command your models will be migrated to your database.

django database api

Django Database API

Now we will use the Django Database API to store data. We will not create any form or views, in this tutorial we will do everything on terminal. So go inside your terminal and follow these steps.

  • Run the following command to enter Django Database API using python shell.
python manage.py shell
  • The above command will take you to Django Database API.

django database api

  • Now to fetch all the records from the Category Table we can use the following code. It is same as we write in python.

django database api

  • As you can see the QuerySet returned is empty. Because we have not added any data.

Storing Data using Django Database API

Now we will store some data. To store data using models we will create object of our models, and then we will call the save function.

  • See the following screenshot to know how to save data using objects.

django database api

  • Now if we will try fetching the stored data then we will get.

django database api

  • As you can see in the result we are seeing only Category object. If you want to see the actual results then we need to tweak our model code a little.

Filtering Database Results

  • Come inside models.py file of your app and modify the code as follows.
from django.db import models

#Create your models here.

class Category(models.Model):
    categoryName = models.CharField(max_length=100)

    #defining a method to return the category name
    def __str__(self):
        return self.categoryName

class Product(models.Model):
    productCategory = models.ForeignKey(Category, on_delete=models.CASCADE)
    productName = models.CharField(max_length=100)
    productPrice = models.IntegerField()
    productBrand = models.CharField(max_length=100)
  • Now restart your Django Database API shell in terminal and try fetching the categories.

django database api

  • So now you can see the category names that we stored. You can also filter the data using the filter method with primary key.

django database api

  • You also download the source code from the below given link.

[sociallocker] [download id=”186″] [/sociallocker]

So thats all for this Django Database API tutorial friends. In the next tutorial we will insert data using HTML forms. And feel free to leave your comment if having any confusions. Thank You 🙂

Django Forms Tutorial – Working with Forms in Django

Hello friends, welcome to Django Forms Tutorial. We already posted a couple of tutorials for Python Django Framework. Today we will learn how we can handle Forms in this Django Forms Tutorial.

If you are an absolute beginner in Python Django Framework then follow the previous published post first. You can go to the previous post from below links.

  1. Python Django Tutorial for Beginners – Getting Started
  2. Django Views Tutorial – Creating Your First View
  3. Django Templates Tutorial – Creating A Simple Template

Now lets start this Django Forms Tutorial. I am assuming you are already aware of html forms.

[toc]

Django Forms Tutorial

The first thing we will do is, we will create a new Django Project using PyCharm.

Creating a new Project

  • Open PyCharm and Create a New Django Project.
  • I created a project named FormExample

Creating Templates

I want to simplify this tutorial as much as I can. That is why in this post I will use two template. From the first template I will take some values from the user and in the second template we will display the taken values. This way you will get the basic idea of how HTML form works in Django. And that is the main motive of this Django Forms Tutorial. So lets create our templates first.

  • Inside templates folder create an HTML file and name it anything. I just created index.html. And write the following HTML code.
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Django Forms Tutorial</title>
</head>
<body>
<h2>Django Forms Tutorial</h2>
<form method="post" action="/getdata/">
    <table>
        <tr>
            <td>Enter your name:</td>
            <td><input type="text" name="name"/></td>
        </tr>
        <tr>
            <td>Enter your email:</td>
            <td><input type="email" name="email"/></td>
        </tr>
        <tr>
            <td>Enter your phone:</td>
            <td><input type="text" name="phone"/></td>
        </tr>
        <tr>
            <td>

            </td>
            <td>
                <button>Submit Form</button>
            </td>
        </tr>
    </table>
</form>
</body>
</html>

What we did?

Above we have created a very simple HTML document. The document has an HTML form. We are using POST method in Form. And inside the action attribute we have given a URL /getdata/ we will define this URL in our urls.py file.

In form we have 3 fields name, email and phone that the user will enter.

  • Now create one more HTML file inside templates folder. I just created showdata.html and write the following html code inside this file.
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Django Forms Tutorial</title>
</head>
<body>
<h2>Django Forms Tutorial</h2>
<form method="post" action="/getdata/">
    <table>
        <tr>
            <td>Your Name</td>
            <td><strong>{{ name }}</strong></td>
        </tr>
        <tr>
            <td>Your Email</td>
            <td><strong>{{ email }}</strong></td>
        </tr>
        <tr>
            <td>Your Phone</td>
            <td><strong>{{ phone }}</strong></td>
        </tr>
    </table>
</form>
</body>
</html>

What we did?

Again we have created a simple HTML page. The page has a table that will display the data entered in the form we created. As I explained in the previous tutorial that for variables inside HTML form we write it inside {{ }}.

Creating View

Now we will create a view to handle our request.

  • Inside your project create a new file views.py and write the following code.
#importing required packages
from django.http import HttpResponse
from django.template import loader
from django.views.decorators.csrf import csrf_exempt

#disabling csrf (cross site request forgery)
@csrf_exempt
def index(request):
    #if post request came 
    if request.method == 'POST':
        #getting values from post
        name = request.POST.get('name')
        email = request.POST.get('email')
        phone = request.POST.get('phone')

        #adding the values in a context variable 
        context = {
            'name': name,
            'email': email,
            'phone': phone
        }
        
        #getting our showdata template
        template = loader.get_template('showdata.html')
        
        #returing the template 
        return HttpResponse(template.render(context, request))
    else:
        #if post request is not true 
        #returing the form template 
        template = loader.get_template('index.html')
        return HttpResponse(template.render())

If you are working with GET, replace POST with GET in the above code. And inside your HTML form change POST to GET.

What we did?

In the above code we are first disabling csrf. In django there is already a feature to prevent Cross Site Request Forgery (CSRF). But I wanted to make this tutorial as simple as possible so I just disabled csrf for now. using @csrf_exempt. (Read this Django Forms Example to know working without disabling csrf).

Then we defined our view index, inside the view we are first checking whether a POST request has came or not. If POST is true then we are getting values from POST. Then we are adding the values in another variable and passing it to our template. The same we did in the last Django Templates Tutorial.

And in the else part we are loading the same form template.

Defining URL Patterns

  • Come inside urls.py file and modify it as follow.
from django.conf.urls import url
from django.contrib import admin

#importing views
#we need to create views.py
from . import views

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    #define the url getdata that we have written inside form
    url(r'^getdata/', views.index),

    #defining the view for root URL
    url(r'^$', views.index),
]
  • Now try executing your project.
django forms tutorial
Before Form Submission
django forms tutorial
After Form Submission

Bingo! our form is working absolutely fine. You can also download the source code from the below link.

[sociallocker]  [download id=”142″][/sociallocker]

Next Post: Django Forms Example with Form Class

So thats all for this Django Forms Tutorial friends. This was very basic form handling using Django. In upcoming tutorials we will learn some cool features of Django with Forms. And feel free to submit any query by comments regarding this Django Forms Tutorial. Thank You 🙂

Django Templates Tutorial – Creating A Simple Template

Welcome to Django Templates Tutorial. In this tutorial we will create a very simple Django Template. I already posted a couple of tutorials for getting started with Python Django Framework. In this Django Templates Tutorial we will see how to create a simple template.

If you haven’t read the previous post then It would be good if you go through the previous post first. You can visit the previous tutorials from the given links.

And after reading the above mentioned post, come back to this Django Template Tutorial to know how template works in Django.

[toc]

What is a Template?

I am pretty sure that you know it already, but still for those who don’t know. A template is just an HTML file, that contains the HTML design of our website.

Templates in Django

If I tell you what are Templates in Django then the answer is “A Django Template is a sequence of Text that helps in separation of the presentation layer of a document from its data”.

Why Templates?

You may think that why use templates? If you remember the last tutorial where we learnt about creating a view. The code we used there in our view is

from django.http import HttpResponse

def index(request):
    return HttpResponse("<h1>Welcome to Mailing System Python Django App</h1>")

As you can see we have hardcoded the html inside HttpResponse. And it is not a convenient way to design the page. It will take more effort. And also when we need to change the design of the page, we need to change python code. That is why we separate the presentation layer from the python code. And we will learn HOW TO do this, in this Django Templates Tutorial.

Django Templates Tutorial

Now lets begin our Django Templates Tutorial, as we know  now why we need it. I am using PyCharm. Today I will tell you an easy way of creating projects 😉 . And now you do not need to open powershell to type commands. 😛 So Follow these steps to create your project.

Creating a new Django Project

  • Open PyCharm and click on Create New Project.

django templates tutorial

  • Now select Django from the left and give your project a name. And click on Create.

django templates tutorial

Creating views.py

To define our views inside the project we will create a new file named views.py.

  • So inside your project create a new python file and name it views.

django templates tutorial

Defining a URL

Now to see our template we will define a URL pattern.

  • Come inside the urls.py file of your project and modify it as follows.
from django.conf.urls import url
from django.contrib import admin

#importing the views we created 
from . import views

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    
    #defining a new URL pattern
    #when we will go here our template will render
    url(r'^firsttemplate/', views.index),
]

What we did?

The above code is very simple and we already did it in the last tutorial about creating a simple view in django.

Creating a Template

Take a look in your project structure, you will see a folder named template. It is the folder where we will create our templates.

django templates tutorial

So as I already said template is nothing but an HTML file containing the presentation of our page. So lets create a template.

  • Right click on templates folder and go to new->html file, put a file name and click on create. I have created index.html. 
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Django Templates Tutorial</title>
</head>
<body>
    <h1>Our First Template</h1>
</body>
</html>
  •  Above you can see a very simple html file. And it is actually our template.

Rendering Template

Template will be rendered via view. But this time we do not need to hardcode the html inside our python code. As we already separated the html and now it is an individual file.

To render the template we created follow these steps.

  • Come inside views.py file that we created. And write the following code.
from django.http import HttpResponse

#importing loading from django template 
from django.template import loader

#our view which is a function named index
def index(request):
    
    #getting our template 
    template = loader.get_template('index.html')
    
    #rendering the template in HttpResponse
    return HttpResponse(template.render())

What we did?

In the above code first we imported loader. We need to it load the template.

Then we have our function named index, and it is actually our view that is taking the request.

Inside the function we created our template from loader.

And finally we are rendering the template in HttpResponse.

Running Your Project

  • Now lets try running our project. This time we don’t need powershell and some typical powershell commands. In the top right corner of the screen you will see a play button.

django templates tutorial

  • Just click on this button and your development server will start running. You can see it below in your IDEs console.

django templates tutorial

  • As you can see the development server is running on http://127.0.0.1:8000/ it is already hyperlinked so just click on it. And your browser will open. You can also go to this link on your browser manually. But you have to append our URL pattern that we created for our view at the end. So the URL is
    http://127.0.0.1:8000/firsttemplate/
  • Go to the above URL and you will see the template we created.

django forms tutorial

  • BINGO! our template is rendered successfully.
  • Passing Values to Template
  • We can also pass values to our template. This is needed when we are making a dynamic web app. So lets see how we can do this. Its pretty easy. Just follow these steps.
  • Go to your template file index.html and change it as follow
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Django Templates Tutorial</title>
</head>
<body>
<div style="width:50%;margin:0 auto; font-size:250%">
    <h1>User Profile</h1>
    <table>
        <tr>
            <th>Name</th>
            <td>{{ name }}</td>
        </tr>
        <tr>
            <th>Father's Name</th>
            <td>{{ fname }}</td>
        </tr>
        <tr>
            <th>Course</th>
            <td>{{ course }}</td>
        </tr>
        <tr>
            <th>Address</th>
            <td>{{ address }}</td>
        </tr>
    </table>
</div>
</body>
</html>

What we did?

In the above html file we just created a simple table. And where we want to pass the variable value we have written a variable instead of writing a static html. Just remember wherever we need to put a variable in html page we need to write it between {{ }} .

  •  Now while rendering the template we will pass the values needed. So come inside views.py file and modify it as follows.
from django.http import HttpResponse

#importing loading from django template
from django.template import loader

#our view which is a function named index
def index(request):

    #getting our template
    template = loader.get_template('index.html')

    #creating the values to pass
    context = {
        'name':'Belal Khan',
        'fname':'Azad Khan',
        'course':'Python Django Framework',
        'address':'Kanke, Ranchi, India',
    }

    #rendering the template in HttpResponse
    #but this time passing the context and request
    return HttpResponse(template.render(context, request))

What we did?

We have created a variable named context containing the values to pass. It is very much similar to JSON object. And then we are passing the context with request, while rendering our template.

Now refresh your page and you will see the following.

django templates tutorial
Django Templates Tutorial

As you can see the values passed are showing up on the page. Bingo! Its working fine.

Next Post: Django Forms Tutorial – Working with Forms in Django

So thats all for this Django Templates Tutorial. Feel free to leave your comments if having any ideas or feedback regarding this Django Templates Tutorial. We will do some more cool stuffs in upcoming tutorials. Thank You 🙂