article

Friday, April 10, 2020

Python Django Forms and Validation


Python Django Forms and Validation

Django Form Validation - Django provides built-in methods to validate form data automatically. Django forms submit only if it contains CSRF tokens. It uses uses a clean and easy approach to validate data.

The is_valid() method is used to perform validation for each field of the form, it is defined in Django Form class. It returns True if data is valid and place all data into a cleaned_data attribute.

Sql table
CREATE TABLE employee (
id INTEGER PRIMARY KEY,
name STRING (100),
contact STRING (100)
);
#models.py
from django.db import models

# Create your models here.
class Employee(models.Model):  
    name = models.CharField(max_length=100)  
    contact = models.CharField(max_length=100)  
    class Meta:  
        db_table = "employee"  
#forms.py
from django import forms  
from myapp.models import Employee  
  
class EmployeeForm(forms.ModelForm):  
    class Meta:  
        model = Employee  
        fields = "__all__"  
#view.py
from django.shortcuts import render, redirect

# Create your views here.
from myapp.forms import EmployeeForm  

def index(request): 
    if request.method == "POST":
        form = EmployeeForm(request.POST)
        if form.is_valid():
            model_instance = form.save(commit=False)
            model_instance.save()
            return redirect('/')
    else:
        form = EmployeeForm()
        return render(request, "index.html", {'form': form})
//templates/index.html
<!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">Save</button>  
</form>  
</body>  
</html> 

urls.py
from myapp import views 

urlpatterns = [
    path('admin/', admin.site.urls),   
    path('', views.index),   
]

Related Post