Python list append Django

In this Python Django Tutorial, we’ll learn how to append a list in Django. And we’ll also see examples related to this. These are the following topics we are going to discuss in this tutorial.

  • Python list append Django
  • Python list append Django basic commands
  • Python list append Django view-string append
  • Python list append Django view-number append
  • Python list append Django view-list append
  • Python Django append queryset to list
  • Python Django session list append

Python list append Django

In this section, we’ll learn basic knowledge to append the list in python.

In Python, the append() function adds a single item to an existing list. It does not return a new list of items, but it does add the item to the end of the existing list.

The size of the list expands by one after calling the append() method on it.

Syntax:

list_name.append(elements)
  • Elements: The append() method accepts a single element as an input parameter and appends it to the list’s end.

Note: Numbers, strings, another list, and dictionaries can all be appended within a list.

Read: Python Django concatenate string

Python list append Django basic commands

In this section, we’ll learn basic commands to append the list in Django.

CREATE PROJECT:  First, we need to create a Django Project ‘BookShop’. For this, type the following command in the terminal.

django-admin startproject BookShop

CREATE APP: Then, we’ll create a Django App ‘Books’. For this, type the following command in the terminal.

python manage.py startapp Books

INSTALL APP: Now, include the above-created app in the settings.py file.

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'Books',
]

CREATE TEMPLATES: Then create the folder with the name Templates. And, add HTML files within the folder.

ADD TEMPLATES: Now, add this folder Templates folder in the settings.py file.

DIRS : ['Templates']

PROJECT URLs: Add the following code in the urls.py file of the BookShop.

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('Books.urls'))
]

APP URLs: Add the following code in the urls.py file of the Books.

from django.urls import path
from . import views
urlpatterns = [
path('', views.Books, name='Books'),
]

CREATE FORM: Now, add the following code to the forms.py file of the Books app to create the form.

from django import forms

class BooksForm(forms.Form):
    Author = forms.CharField()
    Book = forms.CharField()
    Price = forms.IntegerField()

form.html: Add the following code to the form.html file to create a form.

<!DOCTYPE html>  
<html lang="en">  
<head>  
    <meta charset="UTF-8">  
    <title>Index</title>  
</head>  
<body>  
<form method="POST" class="post-form" enctype="multipart/form-data">  
        {% csrf_token %}  
        {{ form.as_p }}  
        <button type="submit" class="save btn btn-default">Submit</button>  
</form>  
</body>  
</html> 

index.html: Add the following code to the index.html file.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <p>
       <b>Book List : </b> {{List}}
    </p>
</body>
</html>

Read: Python Django MySQL CRUD

Python list append Django view-string append

In this section, we’ll learn to append strings to the list in Django.

CREATE VIEW: Add the following code in the views.py file.

from django.shortcuts import render
from Books.forms import BooksForm

def Books(request):  
    if request.method == "POST":  
        form = BooksForm(request.POST)  
        if form.is_valid():  
            Author = form.cleaned_data['Author']
            Book = form.cleaned_data['Book']
            Price = form.cleaned_data['Price']
            print(Book)
            BookList = ['Moby Dick', 'War and Peace']
            print(BookList)
            BookList.append(Book)
            print(BookList)
            return render(request, 'index.html', {'List':BookList})
    else:  
        form = BooksForm()  
    return render(request,'form.html',{'form':form})
  • The append() function is a built-in python function.
  • Here, it is used to append string elements to the end of the list.

Run the server: Start the server and access the form by defining the URL as http://127.0.0.1:8000.

python list append django
Python list append Django
python list append django view string append
Python list append Django view string append

Read: Python Django form validation

Python list append Django view-number append

In this section, we’ll learn to append numbers to the list in Django.

CREATE VIEW: Add the following code in the views.py file.

from django.shortcuts import render
from Books.forms import BooksForm

def Books(request):  
    if request.method == "POST":  
        form = BooksForm(request.POST)  
        if form.is_valid():  
            Author = form.cleaned_data['Author']
            Book = form.cleaned_data['Book']
            Price = form.cleaned_data['Price']
            PriceList = [256, 598]
            PriceList.append(Price)
            print(PriceList)
            return render(request, 'index.html', {'List':PriceList})
    else:  
        form = BooksForm()  
    return render(request,'form.html',{'form':form})
  • The append() function is a built-in python function.
  • Here, it is used to append number elements to the end of the list.

Run the server: Start the server and access the form by defining the URL as http://127.0.0.1:8000.

python list append using django
Python list append using Django
python list append django view number append
Python list append Django view number append

Read: Union operation on models Django

Python list append Django view-list append

In this section, we’ll learn to append a list to the list in Django.

CREATE VIEW: Add the following code in the views.py file.

from django.shortcuts import render
from Books.forms import BooksForm

def Books(request):  
    if request.method == "POST":  
        form = BooksForm(request.POST)  
        if form.is_valid():  
            Author = form.cleaned_data['Author']
            Book = form.cleaned_data['Book']
            Price = form.cleaned_data['Price']
            AuthorList = ['Homer','Nabokov']
            AuthorList.append(Author)
            BookList = ['The Odyssey','Lolita']
            BookList.append(Book)
            BookList.append(AuthorList)
            print(BookList)
            return render(request, 'index.html', {'List':BookList})
    else:  
        form = BooksForm()  
    return render(request,'form.html',{'form':form})
  • The append() function is a built-in python function.
  • Here, it is used to append the list to the end of the list.

Run the server: Start the server and access the form by defining the URL as http://127.0.0.1:8000.

python django list append
Python Django list append
python list append django view list append
Python list append Django view list append

Read: Python filter not in Django

Python Django append queryset to list

In this section, we’ll learn to append queryset to list in the Django.

CREATE PROJECT:  First, we need to create a Django Project ‘ArticleClub’. For this, type the following command in the terminal.

django-admin startproject ArticleClub

CREATE APP: Then, we’ll create a Django App ‘Articles’. For this, type the following command in the terminal.

python manage.py startapp Articles

INSTALL APP: Now, include the above-created app in the settings.py file.

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'Articles',
]

CREATE AND ADD TEMPLATES: Then create the folder with the name Templates and add this folder in the settings.py file. And, add HTML files within the folder.

PROJECT URLs: Add the following code in the urls.py file of the Articles.

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('',include('Articles.urls'))
]

APP URLs: Add the following code in the urls.py file of the Articles.

from django.urls import path
from . import views
urlpatterns = [
path('', views.Article, name='Article'),
]

CREATE MODEL: Now, add the following code to the models.py file of the Articles app to create the model.

from django.db import models

class ArticleDetails(models.Model):
    Article = models.CharField(max_length=200)
    Writter = models.CharField(max_length=50)
    
    def __str__(self):  
        return "%s %s" % (self.Article, self.Writter) 

CREATE FORM: Now, add the following code to the forms.py file of the Articles app to create the form.

from django import forms  
from .models import ArticleDetails
  
class ArticleDetailsForm(forms.ModelForm):  
    class Meta:  
        model = ArticleDetails 
        fields = "__all__"  

form.html: Add the following code to the form.html file to create a form.

<!DOCTYPE html>  
<html lang="en">  
<head>  
    <meta charset="UTF-8">  
    <title>Index</title>  
</head>  
<body>  
<form method="POST" class="post-form" enctype="multipart/form-data">  
        {% csrf_token %}  
        {{ form.as_p }}  
        <button type="submit" class="save btn btn-default">Submit</button>  
</form>  
</body>  
</html> 

index.html: Add the following code to the index.html file.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <p>
       <b>List : </b> {{list}}
    </p>
</body>
</html>

CREATE VIEW: Add the following code in the views.py file.

from django.shortcuts import render
from .forms import ArticleDetailsForm
from .models import ArticleDetails

def Article(request):
    article = ArticleDetails.objects.all()
    articles_list = list(article)
    new_list = ['Article','Writter']
    new_list.append(articles_list)
    if request.method == 'POST':
        form = ArticleDetailsForm(request.POST)
        if form.is_valid():
            form.save()
            return render(request, 'index.html', {'list':new_list})
    else:
        form = ArticleDetailsForm
    return render(request,'form.html',{'form':form})

Run the server: Start the server and access the form by defining the URL as http://127.0.0.1:8000.

list append using python django
list append using Python Django
django append queryset to list
Django append queryset to list

Read: Login system in Python Django

Python Django session list append

In this section, we’ll learn to append sessions in the list using Django.

CREATE PROJECT:  First, we need to create a Django Project ‘SessionProject’. For this, type the following command in the terminal.

django-admin startproject SessionProject

CREATE APP: Then, we’ll create a Django App ‘SessionApp’. For this, type the following command in the terminal.

python manage.py startapp SessionApp

CREATE AND ADD TEMPLATES: Then create the folder with the name Templates and add this folder in the settings.py file. And, add HTML files within the folder.

PROJECT URLs: Add the following code in the urls.py file of the SessionApp.

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('SessionApp.urls'))
]

APP URLs: Add the following code in the urls.py file of the SessionApp.

from django.urls import path
from . import views
urlpatterns = [
path('set/', views.setsession, name='SetSession'),
path('get/', views.getsession, name='GetSession'),
]

getsession.html: Add the following code to the getsession.html file to create a form.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Get Session</title>
</head>
<body>
    <h4>Get Session</h4>
    {{list}}
</body>
</html>

CREATE VIEW: Add the following code in the views.py file.

from django.shortcuts import render
from django.http import HttpResponse

# Create Session
def setsession(request):
    request.session['session_name'] = 'Welcome'
    return HttpResponse('<h1>Created</h1>') 

# Get Session
def getsession(request):
    name = request.session.get('session_name', default='Guest')
    list = ['Old Sessions']
    list.append(name)
    return render(request, 'getsession.html', {'list':list})
  • First, we create a session named Welcome.
  • After that, we get a created session and append it to the list.
  • And, in last we render the appended list to the HTML Template.

Run the server: Start the server and access the form by defining the URL as http://127.0.0.1:8000/set.

python django session list append
Python Django session list append
session list append using python django
session list append using Python Django

Also, take a look at some more Python Django tutorials.

In this Python Django Tutorial, we have discussed the Python list append Django and we have also discussed the following topics in this tutorial.

  • Python list append Django
  • Python list append Django basic commands
  • Python list append Django view-string append
  • Python list append Django view-number append
  • Python list append Django view-list append
  • Python Django append queryset to list
  • Python Django session list append