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 validate_ipv4_address in django
Next article icon

how to use validate_ipv4_address in django

Last Updated : 02 Oct, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

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 Modules

  • Install Django
  • Create Virtual Env

Use of validate_ipv4_address in Django

To start the project use this command

django-admin startproject queryexpressionsproject cd app

To start the app use this command

python manage.py startapp app

Now add this app to the 'settings.py'

Screenshot-from-2023-09-27-13-07-55

Starting the Project

model.py: This code snippet demonstrates how to define a Django model with custom validators for specific fields. It enforces data integrity by ensuring that the ip_address field, the ip_address field contains a valid IPv4 address.'ip_address' as a character field with a maximum length of 15 characters. It uses the built-in 'validate_ipv4_address' validator to validate that the input data is a valid IPv4 address.

Python3
from django.db import models from django.core.exceptions import ValidationError from django.core.validators import validate_ipv4_address   class Product(models.Model):     name = models.CharField(max_length=100)     price = models.DecimalField(max_digits=10, decimal_places=2)     quantity = models.PositiveIntegerField()     ip_address = models.CharField(max_length=15,                            validators=[validate_ipv4_address])      def __str__(self):         return self.name 

form.py: This custom validation method if any part of the input is not a valid integer, it raises a validation error. Otherwise, it returns the cleaned data as a string with valid integers.

Python3
from django import forms from .models import Product  class ProductForm(forms.ModelForm):     class Meta:         model = Product         fields = ['name', 'price', 'quantity', 'ip_address'] 

view.py: Overall, this code represents a Django application with views that display expensive products and allow users to create new products through a form. The 'Product' model is used to interact with the database, and the views handle the logic for rendering templates and processing form submissions.

Python3
# app/views.py from django.http import HttpResponse from django.db import models from .models import Product from django.shortcuts import render, redirect from .forms import ProductForm   def home(request):     return HttpResponse('Hello, World!')   def expensive_products(request):     # Calculate the total value and filter for expensive products     expensive_products = Product.objects.annotate(         total_value=models.ExpressionWrapper(models.F('price') * models.F('quantity'),                                            output_field=models.DecimalField())     ).filter(total_value__gt=1000)      return render(request, 'myapp/index.html',                                      {'expensive_products': expensive_products})    def create_product(request):     if request.method == 'POST':         form = ProductForm(request.POST)         if form.is_valid():             form.save()             # Redirect to the expensive products              # page or another appropriate page             return redirect('expensive_products')       else:         form = ProductForm()          return render(request, 'myapp/index2.html', {'form': form}) 

Setting up GUI

index.html: The index.html template to display the categories for each product.

HTML
<!DOCTYPE html> <html> <head>     <title>Expensive Products</title> </head> <body>     <h1>Expensive Products</h1>     <ul>         {% for product in expensive_products %}             <li>                 <strong>{{ product.name }}</strong><br>                 Price: ${{ product.price }}<br>                 Quantity: {{ product.quantity }}<br>                 Total Value: ${{ product.total_value }}<br>                 Valid IP4: ${{ product.ip_address }}              </li>         {% endfor %}     </ul> </body> </html> 

index2.html: This template renders the product creation form.

HTML
<!DOCTYPE html> <html> <head>     <title>Create Product</title> </head> <body>     <h1>Create Product</h1>     <form method="post">         {% csrf_token %}         {{ form.as_p }}         <button type="submit">Create</button>     </form>      {% if form.errors %}         <div class="alert alert-danger">             <strong>Error:</strong>             <ul>                 {% for error in form.errors %}                     <li>{{ error }}</li>                 {% endfor %}             </ul>         </div>     {% endif %} </body> </html> 

urls.py: It include a new URL pattern for the product creation view.

Python3
# pdfapp/urls.py from django.urls import path from . import views  urlpatterns = [     path('hello/', views.home, name='home'),     path('expensive-products/', views.expensive_products, name='expensive_products'),     path('create-product/', views.create_product, name='create_product'), ] 

urls.py: Include the 'products' app's URLs in the project's main urls.py file.

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

Deployement of the Project

Run these commands to apply the migrations:

python3 manage.py makemigrations python3 manage.py migrate  

Run the server with the help of following command:

python3 manage.py runserver  

Output

Screenshot-from-2023-09-26-00-02-09

Screenshot-from-2023-09-26-00-02-52





Screenshot-from-2023-09-23-19-07-24




Next Article
how to use validate_ipv4_address in django

C

chitransh39zj
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 URL Validator in Django?
    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 ValidatorDjango provides
    3 min read
    How Do I Get User IP Address in Django?
    In web development, knowing a user's IP address can be crucial for a variety of reasons, such as logging, analytics, security, and customization. Django, a powerful web framework for Python, provides several ways to access user IP addresses. In this article, we'll walk through creating a small Djang
    2 min read
    Convert IP address to integer and vice versa
    We will use the ipaddress module for this purpose. ipaddress is a module that helps in the creation, manipulation and operation on IPv4 and IPv6 addresses and networks. The motivation of converting IP Addresses to integers and vice versa is that other modules that use IP addresses (such as socket) u
    2 min read
    How to Disable Django's CSRF Validation?
    Cross-Site Request Forgery (CSRF) protection is a critical security feature in Django that helps protect your web applications from certain types of attacks. However, there are scenarios where you might need to disable CSRF validation, such as during API development, in development environments, or
    3 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