Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Django
  • Views
  • Model
  • Template
  • Forms
  • Jinja
  • Python SQLite
  • Flask
  • Json
  • Postman
  • Interview Ques
  • MongoDB
  • Python MongoDB
  • Python Database
  • ReactJS
  • Vue.js
Open In App
Next Article:
How to use URL Validator in Django?
Next article icon

How to use URL Validator in Django?

Last Updated : 28 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

In Django, a popular Python web framework, URL validation can be easily implemented using built-in tools and libraries. In this article, we will explore how to use the URL validator in Django to ensure that the URLs in your web application are valid and secure.

Django's URL Validator

Django provides a URL validator as part of its built-in validation tools. This validator checks whether a given string is valid according to the URL specification. To use this validator, follow these steps:

Step 1: Create a project folder, and Navigate to the Project Directory

django-admin startproject bookstore
cd bookstore

Activate Virtual Environment (Optional)

Step 2: Create a Django App

Inside your project, create a Django app named "mini":

python manage.py startapp mini

Step 3: Define the Model

In this example, we'll create a simple model to store the validated URLs. Open the models.py file in your url_validator_app folder and define the model as follows:

Python3
# mini/models.py from django.db import models  class ValidatedURL(models.Model):     url = models.URLField(unique=True)      def __str__(self):         return self.url 

Step 4: Create form.py

By defining this form class, we've created a structure for capturing and validating URL input from users. It encapsulates the logic needed for URL validation, making it easy to use in our views and templates.

Python3
# mini/forms.py from django import forms from django.core.validators import URLValidator  class URLForm(forms.Form):     url = forms.URLField(         label='Enter a URL',         validators=[URLValidator()],         widget=forms.TextInput(attrs={'placeholder': 'https://example.com'})     ) 

Step 5: Genrate view of the App

The index view handles URL validation and form submissions, while the success view displays the list of validated URLs.

Python3
# mini/views.py from django.shortcuts import render, redirect from .forms import URLForm from .models import ValidatedURL  def index(request):     if request.method == 'POST':         form = URLForm(request.POST)         if form.is_valid():             url = form.cleaned_data['url']             ValidatedURL.objects.create(url=url)             return redirect('success')     else:         form = URLForm()     return render(request, 'url_validator_app/index.html', {'form': form})  def success(request):     validated_urls = ValidatedURL.objects.all()     return render(request, 'url_validator_app/success.html', {'validated_urls': validated_urls}) 

Step 6: Create the Templates

Create two HTML templates: one for the form and another for displaying the validated URLs. Create a templates folder within your app directory and add the following templates:

template/index.html: URL Validator

HTML
<!DOCTYPE html> <html> <head>     <title>URL Validator</title> </head> <body>     <h1>URL Validator</h1>     <form method="post">         {% csrf_token %}         {{ form.as_p }}         <button type="submit">Submit</button>     </form> </body> </html> 

template/index2.html: Validated URLs

HTML
<!DOCTYPE html> <html> <head>     <title>Validated URLs</title> </head> <body>     <h1>Validated URLs</h1>     <ul>         {% for url in validated_urls %}             <li>{{ url }}</li>         {% empty %}             <li>No validated URLs yet.</li>         {% endfor %}     </ul>     <a href="{% url 'index' %}">Back to validation</a> </body> </html> 

Step 7: Configure URLs in the mini/urls.py

Configure your app's URLs by creating a urls.py file within the app folder:

Python3
# mini/urls.py from django.urls import path from . import views  urlpatterns = [     path('', views.index, name='index'),     path('success/', views.success, name='success'), ] 

Step 8: Incude app URLs in the Project URLs

urls.py: In your project's urls.py, include the URLs from your app:

Python3
# url_validator_project/urls.py from django.contrib import admin from django.urls import path, include  urlpatterns = [     path('admin/', admin.site.urls),     path('', include('mini.urls')), ] 

Output:



Next Article
How to use URL Validator in Django?

P

puja2370
Improve
Article Tags :
  • Project
  • Python
  • Geeks Premier League
  • Python Django
  • Geeks Premier League 2023
Practice Tags :
  • python

Similar Reads

    How to use 'validate_email' in Django?
    One crucial aspect of web development is managing user data, and email validation is a common task in this regard. The validate_email function in Django is a handy tool that helps developers ensure the validity of email addresses submitted by users. In this article, we will explore how to use valida
    2 min read
    how to use validate_ipv4_address in django
    A validator is a callable that takes a value and raises a ValidationError if it doesn’t meet the criteria. Validators can be useful for re-using validation logic between different types of fields. In this article, we will learn how to use the 'validate_ipv4_address' validator in Django. Required Mod
    3 min read
    How to Use MaxLengthValidator in Django
    Django, an excessive degree Python web framework, affords a plethora of gear and capabilities to make net development simpler and extra green. One such feature is the MaxLengthValidator, a validation tool that lets you enforce man or woman limits on entering fields for your Django fashions. In this
    3 min read
    Python | Form validation using django
    Prerequisites: Django Installation | Introduction to DjangoDjango works on an MVT pattern. So there is a need to create data models (or tables). For every table, a model class is created. Suppose there is a form that takes Username, gender, and text as input from the user, the task is to validate th
    5 min read
    null=True - Django Built-in Field Validation
    Built-in Field Validations in Django models are the default validations that come predefined to all Django fields. Every field comes in with built-in validations from Django validators. One can also add more built-in field validations for applying or removing certain constraints on a particular fiel
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences