Django에서 자주 사용하는 Form 양식
Django Form
일반 Form 양식 제출
Title
# name: views.py
from django.shortcuts import render,HttpResponse
def index(request):
if request.method == "GET":
return render(request,"index.html")
else:
username = request.POST.get("username")
password = request.POST.get("password")
error = {"username":"","password":""}
if len(username) > 10:
error["username"]=" 10"
if len(password) < 5:
error["password"] = " 5"
return render(request,"index.html",{"error":error})
Form 구현 로그인 양식
Title
# name:views.py
from django.shortcuts import render,HttpResponse
from django.forms import Form,fields,widgets
from django.core.exceptions import ValidationError
class LoginForm(Form):
username = fields.CharField(
required = True,
max_length = 10,
error_messages={"required":" "},
widget=widgets.TextInput(attrs={"placeholder":" ","class":"form-control"})
)
password = fields.CharField(
required = True,
max_length=10,
error_messages={"required":" ","min_length":" 5"},
widget=widgets.PasswordInput(attrs={"placeholder":" ","class":"form-control"})
)
RepeatPass = fields.CharField(
required=True,
max_length=10,
error_messages={"required":" ","min_length":" 5"},
widget=widgets.PasswordInput(attrs={"placeholder":" ","class":"form-control"})
)
# ( )
def clean_password(self):
if self.cleaned_data.get("password").isdigit() or self.cleaned_data.get("password").isalpha():
raise ValidationError(" ")
else:
return self.cleaned_data["password"]
# ( , ),
def clean_RepeatPass(self):
if self.cleaned_data.get("password") != self.cleaned_data.get("RepeatPass"):
raise ValidationError(" ")
else:
return self.cleaned_data
def index(request):
if request.method =="GET":
form = LoginForm()
return render(request, "index.html", {"form": form})
else:
form = LoginForm(request.POST)
if form.is_valid():
# username = form.data['username']
data = form.cleaned_data
username = data.get("username")
password = data.get("password")
print(username,password)
return render(request, "index.html", {"form": form})
return render(request, "index.html", {"form": form})
Form 사용자 등록
Title
# name: models.py
from django.db import models
class User(models.Model):
id = models.AutoField(primary_key=True)
username = models.CharField(max_length=64)
password = models.CharField(max_length=32)
mobile = models.CharField(max_length=32)
email = models.EmailField(max_length=64)
text = models.CharField(max_length=128)
# name: views.py
from django.shortcuts import render,HttpResponse
from MyWeb import models
from django.forms import Form,fields,widgets
from django.core.validators import RegexValidator
from django.core.exceptions import ValidationError
class UserForm(Form):
username = fields.CharField(
label = " : ", #
required = True, #
min_length=4, #
max_length = 10, #
validators=[ RegexValidator(r'^[0-9a-zA-Z]+$'," ,0-9a-z") ],
error_messages={"required":" ","invalid":" ",
"min_length":" 5","max_length":" 10"},
widget=widgets.TextInput(attrs={"placeholder":" ","class":"form-control"})
)
password = fields.CharField(
label = " : ",
required = True,
min_length=5,
max_length=10,
error_messages={"required":" ","min_length":" 5"},
widget=widgets.PasswordInput(attrs={"placeholder":" ","class":"form-control"})
)
mobile = fields.CharField(
label = " : ",
required=True,
validators=[RegexValidator('[0-9]', " ")],
error_messages={"required":" "},
widget=widgets.TextInput(attrs={"placeholder": " ","class": "form-control"})
)
email = fields.EmailField(
label=" : ",
required=True,
error_messages={"required":" !!","invalid":" "},
widget=widgets.EmailInput(attrs={"placeholder": " ", "class": "form-control"})
)
text = fields.CharField(
required=True,
widget=widgets.Textarea(attrs={"placeholder": " , ...", "class": "form-control",
"style":"margin: 0px; width: 203px; height: 98px;"})
)
def index(request):
if request.method =="GET":
form = UserForm()
return render(request, "index.html", {"form": form})
else:
form = UserForm(request.POST)
if form.is_valid():
# username = form.data['username']
data = form.cleaned_data
username = data.get("username")
is_exits = models.User.objects.filter(username="admin").count()
if is_exits != 0:
return HttpResponse(" ")
else:
models.User.objects.create(**data)
return HttpResponse(" ")
else:
return render(request, "index.html", {"form": form.errors})
return render(request, "index.html", {"form": form})
기타 일반적인 Form 양식
Title
# name: views.py
from django.shortcuts import render,HttpResponse
from django.forms import Form,fields,widgets
class MyForm(Form):
hobby = fields.ChoiceField(
label=" :",
required=True,
initial=1, # 1
choices=( (1," "),(2," "),(3," "),(4," ")),
widget=widgets.RadioSelect()
)
select = fields.ChoiceField(
label=" ( ):",
required=True,
initial=1,
choices=( (1," "),(2," "),(3," "),(4," ")),
widget=widgets.Select()
)
multiple = fields.MultipleChoiceField(
label=" ",
choices=((1, " "), (2, " "), (3, " "), (4, " ")),
initial=[2, 4],
widget=widgets.SelectMultiple()
)
checkbox = fields.ChoiceField(
label=" ",
initial="checked", #
widget=widgets.CheckboxInput()
)
multselect = fields.MultipleChoiceField(
label=" ",
choices=((1, " "), (2, " "), (3, " "), (4, " ")),
initial=[1, 3],
widget=widgets.CheckboxSelectMultiple()
)
data = fields.DateField(
label=" ",
widget = widgets.DateInput(attrs={"type":"date"})
)
files = fields.FilePathField(path="./MyProject",
allow_folders=True,recursive=True)
ip = fields.GenericIPAddressField(protocol="both",unpack_ipv4=False)
def index(request):
if request.method=="GET":
form = MyForm()
return render(request,"index.html",{"form":form})
else:
form = MyForm(request.POST)
if form.is_valid():
data = form.cleaned_data
print(data.get("hobby"))
return HttpResponse("hello lyshark")
부모 클래스를 다시 쓰는 방법form 폼을 통해 init 방법을 다시 쓰는 방법으로 데이터베이스 동적 추가, 전단 동적 디스플레이를 실현하고 두 개의 선택 상자를 예로 들면
# name: models.py
from django.db import models
class DBHost(models.Model):
id = models.AutoField(primary_key=True)
host = models.CharField(max_length=32)
title = models.CharField(max_length=32)
# name:index.html
{{ form.title }}
{{ form.host }}
# name:views.py
from django.shortcuts import render
from django.forms import Form,fields,widgets
from MyWeb import models
class DBHost(Form):
title = fields.IntegerField(widget=widgets.Select(choices=[]))
host = fields.IntegerField(widget=widgets.SelectMultiple(choices=[]))
# __init__
def __init__(self,*args,**kwargs):
super(DBHost, self).__init__(*args,**kwargs)
self.fields['title'].widget.choices = models.DBHost.objects.all().values_list("id","title")
self.fields['host'].widget.choices = models.DBHost.objects.all().values_list("id", "host")
def index(request):
form = DBHost()
return render(request,"index.html",{"form":form})
Form 양식에 데이터를 반환Form 양식은 기본 데이터를 반환합니다. 번호를 사용하여 지정된 데이터의 기본 매개 변수를 조회하고 편집 상자로 반환할 수 있습니다.
# name:views.py
from django.shortcuts import render
from django.forms import Form,fields,widgets
from MyWeb import models
class MyForm(Form):
host = fields.CharField(required=True,widget=widgets.TextInput())
title = fields.CharField(required=True, widget=widgets.TextInput())
def index(request):
nid = request.GET.get("id") # ID
qset = models.DBHost.objects.filter(id=nid).values("host","title")
dic = qset[0] #
form = MyForm(dic) #
return render(request,"index.html",{"form":form})
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
다양한 언어의 JSONJSON은 Javascript 표기법을 사용하여 데이터 구조를 레이아웃하는 데이터 형식입니다. 그러나 Javascript가 코드에서 이러한 구조를 나타낼 수 있는 유일한 언어는 아닙니다. 저는 일반적으로 '객체'{}...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.