article

Thursday, April 9, 2020

Python Django Forms


Python Django Forms - Django provides a Form class which is used to create HTML forms. It describes a form and how it works and appears.

Forms.py
 
from django import forms
 
COUNTRY_CHOICES =( 
    ("1", "Philippines"), 
    ("2", "Japan"), 
    ("3", "Korea"), 
    ("4", "Singapore"), 
    ("5", "USA"), 
)
CHOICES=[('male','Male'),
         ('female','Female')]

class StudentForm(forms.Form):  
    firstname = forms.CharField(label="Enter first name",max_length=50)  
    lastname  = forms.CharField(label="Enter last name", max_length = 100)  
    country  = forms.ChoiceField(choices = COUNTRY_CHOICES)
    date  = forms.DateField()
    age = forms.DecimalField()
    email = forms.EmailField()
    photo = forms.FileField()
    gender = forms.ChoiceField(choices=CHOICES, widget=forms.RadioSelect) 
    accept  = forms.BooleanField(label="Accept privacy and terms")
 
    def __str__(self):
        return self.firstname
Views.py
 
from django.shortcuts import render, redirect

# Create your views here.
from django import forms
from myapp.forms import StudentForm  
  
def index(request):  
    student = StudentForm()  
    return render(request,"form.html",{'form':student})   
Forms.html
<!DOCTYPE html>  
<html lang="en">  
<head>  
    <meta charset="UTF-8">  
    <title>Django Forms</title>  
</head>  
<body>  
<p><h2>Django Forms</h2></p>
<form method="POST" class="post-form">  
        {% csrf_token %}  
        {{ form.as_p }}
        <button type="submit" class="save btn btn-default">Save</button>  
</form> 
</body>  
</html>

urls.py

from django.contrib import admin
from django.urls import path
from myapp import views 

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

Related Post