How to use URL Validator in Django?
Last Updated : 28 Apr, 2025
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:
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