Django

Accept a String Parameter in URL and Display a Personalized Greeting

πŸ“Œ Introduction

In Django, URL parameters are not limited to numbers. We can also pass strings through the URL.

In this program, we will:

  • Accept a name from the URL
  • Send it to the view
  • Display a personalized greeting in the template

🎯 Program Statement

πŸ‘‰ Accept a string parameter in URL and display a personalized greeting.


βš™οΈ Step 1: Create Project and App

django-admin startproject myproject
cd myproject
python manage.py startapp myapp

βš™οΈ Step 2: Register App

1. File: settings.py

Path:

myproject/myproject/settings.py

Code:

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

βš™οΈ Step 3: Configure Templates Folder

2. File: settings.py

Path:

myproject/myproject/settings.py

Code:

import os

TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]

βš™οΈ Step 4: Create View

3. File: views.py

Path:

myproject/myapp/views.py

Code:

from django.shortcuts import render

def greet_user(request, name):
return render(request, 'greet_user.html', {'name': name})

🧠 Explanation

  • name is received from the URL
  • It is passed to the template using a dictionary
  • The template displays the greeting message

βš™οΈ Step 5: Create URL Mapping

4. File: urls.py

Path:

myproject/myproject/urls.py

Code:

from django.contrib import admin
from django.urls import path
from myapp import views

urlpatterns = [
path('admin/', admin.site.urls),
path('greet/<str:name>/', views.greet_user),
]

🧠 Explanation

<str:name>
  • str means a string value will be accepted
  • name is the variable name passed to the view

Example:

/greet/Juhi/

Here:

  • Juhi is the string
  • It is stored in name

βš™οΈ Step 6: Create Template

5. File: greet_user.html

Path:

myproject/templates/greet_user.html

Code:

<!DOCTYPE html>
<html>
<head>
<title>Greeting Page</title>
</head>
<body>
<h1>Personalized Greeting</h1>
<h2>Hello, {{ name }}! Welcome to Django.</h2>
</body>
</html>

βš™οΈ Step 7: Run Server

python manage.py runserver

🌐 Step 8: Output

Open:

http://127.0.0.1:8000/greet/Nyra/

βœ… Output:

Personalized Greeting
Hello, Nyra! Welcome to Django.

Another example:

http://127.0.0.1:8000/greet/Aman/

βœ… Output:

Hello, Aman! Welcome to Django.

🧠 How It Works

  1. User enters a URL like /greet/Kavita/
  2. Django matches it with:
path('greet/<str:name>/', views.greet_user)
  1. Django sends "Kavita" to the view as name
  2. View passes it to the template
  3. Template displays the personalized greeting

⚠️ Common Errors

❌ URL not working

Check that you wrote:

path('greet/<str:name>/', views.greet_user)

and not <int:name>.


❌ Greeting not displayed

Check that the template variable matches the dictionary key:

{'name': name}

and in HTML:

{{ name }}

❌ TemplateDoesNotExist

Make sure the file exists here:

myproject/templates/greet_user.html

❌ App not registered

Add 'myapp' inside INSTALLED_APPS.


πŸ§ͺ Practice Questions

  1. Display message: Welcome, <name>, to MCA Department
  2. Accept city name in URL and display it
  3. Create URL like /student/Riya/ and display Hello Riya
  4. Accept two string parameters such as name and course

🎀 Viva Questions and Answers

1. What is a string URL parameter in Django?

A string URL parameter is a text value passed through the URL. Django captures it using <str:variable_name> and sends it to the view.

2. What is the use of <str:name> in urls.py?

It tells Django to accept a string from the URL and store it in the variable name. This variable is then passed to the view function.

3. How is the URL parameter received in the view?

The URL parameter is received as a function argument after request. For example, in def greet_user(request, name), the value is stored in name.

4. Can we display the URL parameter directly in HTML?

Not directly. First it must be passed from the view to the template using render() and a context dictionary.

5. What is the difference between <int:num> and <str:name>?

<int:num> accepts only integer values, while <str:name> accepts text. Django uses these converters to validate the type of input.

6. What happens if the type in the URL does not match?

Django will not match the URL pattern and usually shows a 404 error. This helps prevent invalid input.

7. Why do we use templates instead of HttpResponse here?

Templates provide better presentation and clearer separation between logic and display. They are more suitable for real web pages.

8. What is personalized greeting?

A personalized greeting is a message that changes according to the user’s name or input. It makes the output dynamic.

9. Can we pass more than one string parameter in URL?

Yes, Django allows multiple URL parameters. For example, we can use a path like student/<str:name>/<str:course>/.

10. Why are URL parameters useful in Django?

They make applications dynamic and flexible by allowing values to be passed directly through the URL. This is useful for profiles, details pages, and custom messages.


πŸ‘‰ Next Post: Create and Render a Basic HTML Template Using Django render()
πŸ‘‰ Back to List: Django Programs (60 Questions with Solutions)


Further Reading

Introduction to Django Framework and its Features

Django Practice Exercise

Examples of Array Functions in PHP

Basic Programs in PHP

Registration Form Using PDO in PHP

Inserting Information from Multiple CheckBox Selection in a Database Table in PHP

programmingempire

princites.com

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *