Django에서 자주 사용하는 Form 양식

12260 단어
Django의 가장 강력한 부분 중 하나는 자동 관리 인터페이스입니다.이것은 모델에서 메타데이터를 읽어서 신속하고 모델 중심의 인터페이스를 제공하여 신뢰를 받는 사용자가 그 중에서 귀하의 사이트의 내용을 관리할 수 있도록 합니다.관리자의 권장 사용법은 조직의 내부 관리 도구에만 한정됩니다.그것은 결코 당신의 전체 전단을 구축하기 위한 것이 아닙니다.
Django Form
일반 Form 양식 제출




    
    Title


    

:{{ error.username }}

:{{ error.password }}

# 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


    

: {{ form.username }} {{ form.username.errors.0 }}

: {{ form.password }} {{ form.errors.password }}

: {{ form.RepeatPass }} {{ form.errors.RepeatPass }}

# 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


    

{{ form.username.label }} {{ form.username }}

{{ form.password.label }} {{ form.password }}

{{ form.mobile.label }} {{ form.mobile }}

{{ form.email.label }} {{ form.email }}

{{ form.text }}

# 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


    
{% for field in form %}

{{ field.label_tag }} {{ field }} {{ field.errors.0 }}

{% endfor %}
# 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})

좋은 웹페이지 즐겨찾기