Create View – Function based Views Django

Last Updated : 13 Jan, 2020
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Create View refers to a view (logic) to create an instance of a table in the database. It is just like taking an input from a user and storing it in a specified table. Django provides extra-ordinary support for Create Views but let’s check how it is done manually through a function-based view. This article revolves around Create View which involves concepts such as Django Forms, Django Models.
For Create View, we need a project with some models and forms which will be used to create instances of that model.

Django Create View – Function Based Views

Illustration of How to create and use create view using an Example. Consider a project named geeksforgeeks having an app named geeks.

Refer to the following articles to check how to create a project and an app in Django.

After you have a project and an app, let’s create a model of which we will be creating instances through our view. In geeks/models.py,




# import the standard Django Model
# from built-in library
from django.db import models
   
# declare a new model with a name "GeeksModel"
class GeeksModel(models.Model):
  
    # fields of the model
    title = models.CharField(max_length = 200)
    description = models.TextField()
  
    # renames the instances of the model
    # with their title name
    def __str__(self):
        return self.title


After creating this model, we need to run two commands in order to create Database for the same.

Python manage.py makemigrations
Python manage.py migrate

Now we will create a Django ModelForm for this model. Refer this article for more on modelform – Django ModelForm – Create form from Models. create a file forms.py in geeks folder,




from django import forms
from .models import GeeksModel
  
  
# creating a form
class GeeksForm(forms.ModelForm):
  
    # create meta class
    class Meta:
        # specify model to be used
        model = GeeksModel
  
        # specify fields to be used
        fields = [
            "title",
            "description",
        ]


Now we have everything ready for back end. Let’s create a view and template for the same. In geeks/views.py,




from django.shortcuts import render
  
# relative import of forms
from .models import GeeksModel
from .forms import GeeksForm
  
  
def create_view(request):
    # dictionary for initial data with 
    # field names as keys
    context ={}
  
    # add the dictionary during initialization
    form = GeeksForm(request.POST or None)
    if form.is_valid():
        form.save()
          
    context['form']= form
    return render(request, "create_view.html", context)


Create a template in templates/create_view.html,




<form method="POST" enctype="multipart/form-data">
  
    <!-- Security token -->
    {% csrf_token %}
  
    <!-- Using the formset -->
    {{ form.as_p }}
      
    <input type="submit" value="Submit">
</form>


Let’s check what is there on http://localhost:8000/
django-create-view-function-based

Now let’s try to enter data in this form,
create-view-function-enter-data

Bingo.! Create view is working and we can verify it using the instance created through the admin panel.
django-mopdel-created-create-view
This way one can create create view for a model in Django.



Previous Article
Next Article

Similar Reads

Update View - Function based Views Django
Update View refers to a view (logic) to update a particular instance of a table from the database with some extra details. It is used to update entries in the database for example, updating an article at geeksforgeeks. So Update view must display the old data in the form and let user update the data from there only. Django provides extra-ordinary s
4 min read
Detail View - Function based Views Django
Detail View refers to a view (logic) to display a particular instance of a table from the database with all the necessary details. It is used to display multiple types of data on a single page or view, for example, profile of a user. Django provides extra-ordinary support for Detail Views but let's check how it is done manually through a function-b
3 min read
Delete View - Function based Views Django
Delete View refers to a view (logic) to delete a particular instance of a table from the database. It is used to delete entries in the database for example, deleting an article at geeksforgeeks. So Delete view must show a confirmation message to the user and should delete the instance automatically. Django provides extra-ordinary support for Delete
3 min read
List View - Function based Views Django
List View refers to a view (logic) to list all or particular instances of a table from the database in a particular order. It is used to display multiple types of data on a single page or view, for example, products on an eCommerce page. Django provides extra-ordinary support for List Views but let's check how it is done manually through a function
3 min read
Class Based vs Function Based Views - Which One is Better to Use in Django?
Django...We all know the popularity of this python framework all over the world. This framework has made life easier for developers. It has become easier for developers to build a full-fledged web application in Django. If you're an experienced Django developer then surely you might have been aware of the flow of the project. How things run in the
7 min read
Function based Views - Django Rest Framework
Django REST Framework allows us to work with regular Django views. It facilitates processing the HTTP requests and providing appropriate HTTP responses. In this section, you will understand how to implement Django views for the Restful Web service. We also make use of the @api_view decorator. Before working on Django REST Framework serializers, you
13 min read
Django Function Based Views
Django is a Python-based web framework which allows you to quickly create web application without all of the installation or dependency problems that you normally will find with other frameworks. Django is based on MVT (Model View Template) architecture and revolves around CRUD (Create, Retrieve, Update, Delete) operations. CRUD can be best explain
7 min read
Createview - Class Based Views Django
Create View refers to a view (logic) to create an instance of a table in the database. We have already discussed basics of Create View in Create View – Function based Views Django. Class-based views provide an alternative way to implement views as Python objects instead of functions. They do not replace function-based views, but have certain differ
3 min read
ListView - Class Based Views Django
List View refers to a view (logic) to display multiple instances of a table in the database. We have already discussed the basics of List View in List View – Function based Views Django. Class-based views provide an alternative way to implement views as Python objects instead of functions. They do not replace function-based views, but have certain
4 min read
UpdateView - Class Based Views Django
UpdateView refers to a view (logic) to update a particular instance of a table from the database with some extra details. It is used to update entries in the database, for example, updating an article at geeksforgeeks. We have already discussed basics of Update View in Update View – Function based Views Django. Class-based views provide an alternat
3 min read
DetailView - Class Based Views Django
Detail View refers to a view (logic) to display one instances of a table in the database. We have already discussed basics of Detail View in Detail View – Function based Views Django. Class-based views provide an alternative way to implement views as Python objects instead of functions. They do not replace function-based views, but have certain dif
3 min read
DeleteView - Class Based Views Django
Delete View refers to a view (logic) to delete a particular instance of a table from the database. It is used to delete entries in the database for example, deleting an article at geeksforgeeks. We have already discussed basics of Delete View in Delete View – Function based Views Django. Class-based views provide an alternative way to implement vie
3 min read
FormView - Class Based Views Django
FormView refers to a view (logic) to display and verify a Django Form. For example, a form to register users at Geeksforgeeks. Class-based views provide an alternative way to implement views as Python objects instead of functions. They do not replace function-based views, but have certain differences and advantages when compared to function-based v
3 min read
Class based views - Django Rest Framework
Class-based views help in composing reusable bits of behavior. Django REST Framework provides several pre-built views that allow us to reuse common functionality and keep our code DRY. In this section, we will dig deep into the different class-based views in Django REST Framework. This article assumes you are already familiar with Django and Django
12 min read
Django Class Based Views
Django is a Python-based web framework that allows you to quickly create web applications. It has a built-in admin interface which makes it easy to work with it. It is often called a Class-Based included framework because it provides built-in facilities for every functionality. Class Based Generic Views are an advanced set of Built-in views that ar
10 min read
How to Use permission_required Decorators with Django Class-Based Views
In Django, permissions are used to control access to views and resources. When working with function-based views (FBVs), decorators like @permission_required are commonly used to restrict access based on user permissions. But what happens when we use class-based views (CBVs)? Django offers flexibility to apply the same permission checks to CBVs as
4 min read
TemplateView - Class Based Generic View Django
Django provides several class based generic views to accomplish common tasks. The simplest among them is TemplateView. It Renders a given template, with the context containing parameters captured in the URL. TemplateView should be used when you want to present some information on an HTML page. TemplateView shouldn’t be used when your page has forms
2 min read
How to Pass Additional Context into a Class Based View (Django)?
Passing context into your templates from class-based views is easy once you know what to look out for. There are two ways to do it - one involves get_context_data, the other is by modifying the extra_context variable. Let see how to use both the methods one by one. Explanation: Illustration of How to use get_context_data method and extra_context va
2 min read
Built-in Error Views in Django
Whenever one tries to visit a link that doesn't exist on a website, it gives a 404 Error, that this page is not found. Similarly, there are more error codes such as 500, 403, etc. Django has some default functions to for handle HTTP errors. Let's explore them one-by-one. Built-in Error Views in Django - 404 view (page not found) - Normally this vie
3 min read
Render a HTML Template as Response - Django Views
A view function, or view for short, is simply a Python function that takes a Web request and returns a Web response. This article revolves around how to render an HTML page from Django using views. Django has always been known for its app structure and ability to manage applications easily. Let's dive in to see how to render a template file through
3 min read
Raw SQL queries in Django views
Let's create a simple Django project that demonstrates the use of raw SQL queries in a view. In this example, we'll create a project to manage a list of books stored in a database. We'll create a view that retrieves books from the database using a raw SQL query and displays them on a webpage. Setting up the projectWe assume that Django is already i
4 min read
Views In Django | Python
Django Views are one of the vital participants of the MVT Structure of Django. As per Django Documentation, A view function is a Python function that takes a Web request and returns a Web response. This response can be the HTML contents of a Web page, a redirect, a 404 error, an XML document, an image, or anything that a web browser can display.  D
6 min read
PyQtGraph – Getting View of Image View
In this article, we will see how we can get the view objects of the image view object in PyQTGraph. PyQtGraph is a graphics and user interface library for Python that provides functionality commonly required in designing and science applications. Its primary goals are to provide fast, interactive graphics for displaying data (plots, video, etc.). W
3 min read
Rendering Data-Frame to html template in table view using Django Framework
In Django, It is easy to render the HTML templates by setting URLs of respective HTML pages. Here we will let to know about how we can work with DataFrame to modify them for table view in the HTML template or web-pages, and for that, we have to use 'render' and 'HttpResponse' functions to manipulate the data inside the DataFrame. Sample DataFrame:
3 min read
How to View Raw SQL Queries Executed by Django
The most important thing while working on Django is to understanding the executed SQL queries running in the background. It is really important from the perspective that, with the help of these SQL queries, one can tune the performance of the database, find the bottlenecks, and troubleshoot the problems appropriately. The three major approaches to
4 min read
Django Get the Static Files URL in View
In Django, static files such as CSS, JavaScript, and images are essential for building interactive and visually appealing web applications. While Django provides robust mechanisms to manage static files, we might need to access the URLs of these static files directly within our views, especially when we need to manipulate or dynamically generate co
3 min read
Creating views on Pandas DataFrame
Many times while doing data analysis we are dealing with a large data set, having a lot of attributes. All the attributes are not necessarily equally important. As a result, we want to work with only a set of columns in the dataframe. For that purpose, let's see how we can create views on the Dataframe and select only those columns that we need and
2 min read
Creating views on Pandas DataFrame | Set - 2
Prerequisite: Creating views on Pandas DataFrame | Set - 1 Many times while doing data analysis we are dealing with a large data set has a lot of attributes. All the attributes are not necessarily equally important. As a result, we want to work with only a set of columns in the dataframe. For that purpose, let's see how we can create views on the D
2 min read
Python - Obtain title, views and likes of YouTube video using BeautifulSoup
In this article, we will learn how can we obtain data (like title, views, likes, dislikes etc) from any YouTube video using a Python script. For this task, we are going to use very famous library for web scraping BeautifulSoup and Requests. Modules required and Installation : Requests : Requests allows you to send HTTP/1.1 requests extremely easily
2 min read
Pafy - Getting Views Count of the Video
In this article we will see how we can get the view counts of the given youtube video in pafy. Pafy is a python library to download YouTube content and retrieve metadata. Pafy object is the object which contains all the information about the given video. View counts is basically the number of views the video has, view count represents how large the
2 min read
Practice Tags :