Pages

Subscribe:

Ads 468x60px

Friday, December 23, 2022

form validation using python

 web form validation is quit easy in python

create an html file.

  1. <!DOCTYPE html>  
  2. <html lang="en">  
  3. <head>  
  4.     <meta charset="UTF-8">  
  5.     <title>Index page</title>  
  6. </head>  
  7. <body>  
  8. <form method="POST" class="post-form" enctype="multipart/form-data">  
  9.         {% csrf_token %}  
  10.         {{ form.as_p }}  
  11.         <button type="submit" class="save btn btn-default">Submit</button>  
  12. </form>  
  13. </body>  
  14. </html>  

create a page modules.py
  1. from django.db import models  
  2. class Employee(models.Model):  
  3.     eid = models.CharField(max_length=20)  
  4.     ename = models.CharField(max_length=100)  
  5.     econtact = models.CharField(max_length=15)  
  6.     class Meta:  
  7.         db_table = "employee" 

now create a file forms.py

  1. from django import forms  
  2. from myapp.models import Employee  
  3.   
  4. class EmployeeForm(forms.ModelForm):  
  5.     class Meta:  
  6.         model = Employee  
  7.         fields = "__all__"  

create another file named views.py and paste the below code

  1. def emp(request):  
  2.     if request.method == "POST":  
  3.         form = EmployeeForm(request.POST)  
  4.         if form.is_valid():  
  5.             try:  
  6.                 return redirect('/')  
  7.             except:  
  8.                 pass  
  9.     else:  
  10.         form = EmployeeForm()  
  11.     return render(request,'index.html',{'form':form})  

No comments:

Post a Comment