Python Django concatenate string

In this Python Django Tutorial, we will learn the implementation of Python Django concatenate strings. And, these are the following topics that we are going to discuss in this tutorial.

  • Python Django concatenate multiline string
  • Django concatenate string basic commands
  • Django concatenate string template
  • Django concatenate string in views
  • Django concatenate string and int basic commands
  • Django concatenate string and int template
  • Django concatenate string and int
  • Django concatenate string model
  • Django template filter concatenate string and int

Python Django concatenate multiline string

String concatenation is the process of joining two strings together.

  • There are multiple ways to concatenate strings.
    • By using the + operator
    • By using join() function
    • By using the % operator
    • By using format() function
  • Multiple ways to concatenate string and int.
    • By using the str() function
    • By using the % operator
    • By using the format() function
    • By using the f strings

Django concatenate string basic commands

In this section, we’ll learn basic commands to concatenate strings.

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

django-admin startproject PythonGuides
  • Here, we create a Django project named PythonGuides.

CREATE APP: Then, we’ll learn to create a Django App. Type the following command in the terminal.

python manage.py startapp home
  • Here, we create a Django App named home.

INSTALL APP: In the settings.py file, we must include the above-created app.

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

CREATE TEMPLATES: The Templates folder is then created in the project root directory. And, we’ll create HTML files within the folder.

django concatenate string
TEMPLATES

ADD TEMPLATES: We also need to add the “Templates Directory” in the settings.py file.

django concatenate string basic command
DIRS

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

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

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

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

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

CREATE FORM: Now, we create a form. And the below code snippets to the forms.py file of the home app.

from django import forms

class StringConcat(forms.Form):
    String_1 = forms.CharField(label='String 1')
    String_2 = forms.CharField(label='String 2')
  • Here, we create a StringConcat class with two Charfield.

Read: Python filter not in Django

Django concatenate string template

In this section, we’ll learn how to create HTML files that will be rendered in views.

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

<!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> 
  • We create the form using the form tag.
  • Here, we use the csrf_token tag is used in form to avoid malicious attacks.
  • Then, we use form.as_p tag to render Django forms as a paragraph.

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>Concatenated String : </b> {{FString}}
    </p>
</body>
</html>

Also, check: Outputting Python to html Django

Django concatenate string in views

In this section, we’ll learn to create views to concatenate strings.

Example #1 By using the + operators.

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

from django.shortcuts import redirect, render
from home.forms import StringConcat

def ConcatForm(request):  
    if request.method == "POST":  
        form = StringConcat(request.POST)  
        if form.is_valid():  
            String1 = form.cleaned_data['String_1']
            String2 = form.cleaned_data['String_2']
            FString = String1 + " " + String2
            return render(request, 'index.html', {'FString':FString})
    else:  
        form = StringConcat()  
    return render(request,'form.html',{'form':form})
  • Here, the variables String1 and String2 are combined using the + operator and stored in another variable FString.

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

djnago concatenate string in view
Add String
django concatenate string template
Concatenated String using + operator

Example #2 By using the join() function.

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

from django.shortcuts import redirect, render
from home.forms import StringConcat

def ConcatForm(request):  
    if request.method == "POST":  
        form = StringConcat(request.POST)  
        if form.is_valid():  
            String1 = form.cleaned_data['String_1']
            String2 = form.cleaned_data['String_2']
            FString = " ".join([String1, String2])
            return render(request, 'index.html', {'FString':FString})
    else:  
        form = StringConcat()  
    return render(request,'form.html',{'form':form})
  • Here, the variables String1 and String2 are combined using the join() method and stored the combined string in another variable FString which is separated by space.
  • The join() method accepts only the list as its argument.

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

python django concatenate string
Enter String
python django concatenate string template
Concatenated String using join() method

Example #3 By using the % operator

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

from django.shortcuts import redirect, render
from home.forms import StringConcat

def ConcatForm(request):  
    if request.method == "POST":  
        form = StringConcat(request.POST)  
        if form.is_valid():  
            String1 = form.cleaned_data['String_1']
            String2 = form.cleaned_data['String_2']
            FString = ("%s %s" %(String1, String2))
            return render(request, 'index.html', {'FString':FString})
    else:  
        form = StringConcat()  
    return render(request,'form.html',{'form':form})
  • Here, the variables String1 and String2 are combined using the % operator and stored the combined string in another variable FString.
  • The % operator can be used for string formatting as well as string concatenation.
concatenate string in django
concatenate string in Django
string concatenation using python django
Concatenated String using % operator

Example #4 By using the format() function

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

from django.shortcuts import redirect, render
from home.forms import StringConcat

def ConcatForm(request):  
    if request.method == "POST":  
        form = StringConcat(request.POST)  
        if form.is_valid():  
            String1 = form.cleaned_data['String_1']
            String2 = form.cleaned_data['String_2']
            FString = "{} {}".format(String1, String2)
            return render(request, 'index.html', {'FString':FString})
    else:  
        form = StringConcat()  
    return render(request,'form.html',{'form':form})
  • Here, the variables String1 and String2 are combined using the format() function and stored the combined string in another variable FString.
  • The format() function uses positional formatting to concatenate elements within a string.
  • The position of strings is set using the curly braces {}.
python django concatenate string in views
Python Django concatenate string in views
concatenate string in views using python django
Concatenated String using format() function

Read: Python Django vs ReactJS

Django concatenate string and int basic commands

In this section, we’ll learn basic commands to create a project and an app to perform concatenation on string and int.

CREATE PROJECT: First, we create a Django Project named ‘MyProject’.

djnago-admin startproject MyProject

CREATE APP: Then, we create a Django App named ‘MyApp’.

python manage.py startapp MyApp

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',
    'MyApp',
]

CREATE TEMPLATES: Create a Templates Folder in the project root directory to add the HTML files.

ADD TEMPLATES: Add the above-created folder in the settings.py file.

'DIRS':['Templates']

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

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

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

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

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

CREATE FORM: Now, create a form to take input from the user.

from django import forms

class StringConcatForm(forms.Form):
    Char_String = forms.CharField(label='Character String')
    Int_String = forms.IntegerField(label='Integer String')
  • Here, we create a StringConcatForm class with one Charfield and one IntegerField.

Read Python Django round to two decimal places

Django concatenate string and int template

In this section, we’ll learn to create HTML files that are rendered in views to concatenate string and int.

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

<!DOCTYPE html>  
<html lang="en">  
<head>  
    <meta charset="UTF-8">  
    <title>App</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> 
  • The form tag is used to generate the form.
  • To avoid malicious attacks, we use the csrf_token tag in the form.
  • And, the form.as_p tag is then used to render Django forms as a paragraph.

home.html: Add the following code to the home.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>String</title>
</head>
<body>
    <p>
       <b>Concatenated String : </b> {{FullString}}
    </p>
</body>
</html>
  • This HTML file is used to render the concatenated String.

Read: Python Django set timezone

Django concatenate string and int

In this section, we’ll learn to create views to concatenate string and int.

Example #1 By using the str() function.

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

from django.shortcuts import redirect, render
from MyApp.forms import StringConcatForm

def ConcatString(request):  
    if request.method == "POST":  
        form = StringConcatForm(request.POST)  
        if form.is_valid():  
            CharString = form.cleaned_data['Char_String']
            IntString = form.cleaned_data['Int_String']
            FullString = CharString + str(IntString)
            return render(request, 'home.html', {'FullString':FullString})
    else:  
        form = StringConcatForm()  
    return render(request,'app.html',{'form':form})
  • Here, the one string and int type variable are concatenated using the str() function.
django concatenate string and int basic commands
Django concatenate string and int
python django cancatenate string and int basic commands
Concatenate string and int using str() function

Example #2 By using the % operator.

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

from django.shortcuts import redirect, render
from MyApp.forms import StringConcatForm

def ConcatString(request):  
    if request.method == "POST":  
        form = StringConcatForm(request.POST)  
        if form.is_valid():  
            CharString = form.cleaned_data['Char_String']
            IntString = form.cleaned_data['Int_String']
            FullString = ("%s %s" %(CharString, IntString))
            return render(request, 'home.html', {'FullString':FullString})
    else:  
        form = StringConcatForm()  
    return render(request,'app.html',{'form':form})
  • Here, the one string and int type variable are concatenated using the % operator.
django concatenate string and int template
Django concatenate string and int
python django concatenate string and int template
Django concatenate string and int using the % operator

Example #3 By using the format() function.

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

from django.shortcuts import redirect, render
from MyApp.forms import StringConcatForm

def ConcatString(request):  
    if request.method == "POST":  
        form = StringConcatForm(request.POST)  
        if form.is_valid():  
            CharString = form.cleaned_data['Char_String']
            IntString = form.cleaned_data['Int_String']
            FullString = "{} {}".format(CharString, IntString)
            return render(request, 'home.html', {'FullString':FullString})
    else:  
        form = StringConcatForm()  
    return render(request,'app.html',{'form':form})
  • Here, the one string and int type variable are concatenated using the format() function.
  • Another advantage of format() is that it eliminates the need to convert integers to strings before concatenating the input.
django concatenate string and int
Django concatenate string and int
python django concatenate string and int
Django concatenate string and int using the format() function

Example #4 By using the f strings.

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

from django.shortcuts import redirect, render
from MyApp.forms import StringConcatForm

def ConcatString(request):  
    if request.method == "POST":  
        form = StringConcatForm(request.POST)  
        if form.is_valid():  
            CharString = form.cleaned_data['Char_String']
            IntString = form.cleaned_data['Int_String']
            FullString = f"{CharString} {IntString}"
            return render(request, 'home.html', {'FullString':FullString})
    else:  
        form = StringConcatForm()  
    return render(request,'app.html',{'form':form})
  • Here, the one string and int type variable are concatenated using the f strings.
concatenate string and int using django
Concatenate string and int using Django
concatenate string in django using python django
Concatenate string and int using f string

Read: If statement in Django template

Django concatenate string model

In this section, we’ll learn to concatenate strings using the Django model.

CREATE PROJECT: First, we create a Django Project named ‘Employee’.

djnago-admin startproject Employee

CREATE APP: Then, we create a Django App named ‘Records’.

python manage.py startapp Records

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',
    'Records',
]

CREATE TEMPLATES: Create a Templates Folder in the project root directory to add the HTML files.

django concatenate string model
Django concatenate string model

ADD TEMPLATES: Add the above-created folder in the settings.py file.

'DIRS':['Templates']

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

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

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

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

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

CREATE MODEL: Add the following code in the models.py file.

from django.db import models

class EmpRecords(models.Model):
    first_name=models.CharField(max_length=200)
    last_name=models.CharField(max_length=200)
    email=models.EmailField()
    class Meta:
        db_table = "EmpRecords"
  • Here we create different attributes such as first_namelast_name, and, email with specific datatypes which represent columns in the database.
  • To change the default name of the table, we pass the new table in db_table in the class Meta.

CREATE FORM: Add the following code in the forms.py file.

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

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

from django.shortcuts import render
from Records.forms import EmpRecordsForm
from .models import EmpRecords

def EmpRecord(request):  
    if request.method == "POST":  
        form = EmpRecordsForm(request.POST)  
        if form.is_valid():  
            First_Name = form.cleaned_data['first_name']
            Last_Name = form.cleaned_data['last_name']
            Email = form.cleaned_data['email']
            data = EmpRecords(first_name=First_Name, last_name=Last_Name, email=Email )
            data.save()
            FullName = First_Name + " " + Last_Name
            return render(request, 'index.html', {'FullName':FullName})
    else:  
        form = EmpRecordsForm()  
    return render(request,'records.html',{'form':form})

  • Here, the variables First_Name and Last_Name are combined using the + operator and stored in another variable FullName.
  • And we also save the records in the admin database.

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

concatenate string model using django
Concatenate string model using Django
concatenate string model using python django
Concatenate string using model
python django concatenate string model
Admin Panel Record

Read: Django get all data from POST request

Django template filter concatenate string and int

In this section, we’ll learn the concatenation of string and int using a built-in template filter.

The “add” filter is used to add the argument to the value. If this fails, it adds the values together.

Syntax:

{{ first|add:second }}

Let’s see an example to concatenate string and int using add template filter.

Execute the steps outlined in the following preceding sections.

  • Django concatenate string and int basic commands

After this, carry forward with the following steps.

CREATE FORM: Add the following code to the forms.py file.

from django import forms

class StringConcatForm(forms.Form):
    Char_String = forms.CharField(label='Character String')
    Int_String = forms.CharField(label='Integer String')

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

from django.shortcuts import render
from MyApp.forms import StringConcatForm

def ConcatString(request):  
    if request.method == "POST":  
        form = StringConcatForm(request.POST)  
        if form.is_valid():  
            CharString = form.cleaned_data['Char_String']
            IntString = form.cleaned_data['Int_String']
            context = {
                'CharString':CharString,
                'IntString' :IntString
            }
            return render(request, 'index.html',context)
    else:  
        form = StringConcatForm()  
    return render(request,'app.html',{'form':form})

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

<!DOCTYPE html>  
<html lang="en">  
<head>  
    <meta charset="UTF-8">  
    <title>App</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>String</title>
</head>
<body>
    <p>
       <b>Concatenated String : </b> {{CharString|add:" "|add:IntString}}
    </p>
</body>
</html>
  • Here, we concatenate CharString and IntString variables using add filter.

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

django template filter concatenate string and int
Django template filter concatenate string and int
python django concatenate add filter string and int
Python Django concatenate add filter string and int

You may also like to read the following Django tutorials.

In this Python Django Tutorial, we have discussed the Python Django concatenate multiline string and we have also discussed the following topics in this tutorial.

  • Python Django concatenate multiline string
  • Django concatenate string basic commands
  • Django concatenate string template
  • Django concatenate string in views
  • Django concatenate string and int basic commands
  • Django concatenate string and int template
  • Django concatenate string and int
  • Django concatenate string model
  • Django template filter concatenate string and int