django의 Form 3.

2575 단어
일반 선택 플러그인
#  radio,      
# user = fields.CharField( 
#     initial=2, 
#     widget=widgets.RadioSelect(choices=((1,'  '),(2,'  '),)) 
# ) 
 
#  radio,      
# user = fields.ChoiceField( 
#     choices=((1, '  '), (2, '  '),), 
#     initial=2, 
#     widget=widgets.RadioSelect 
# ) 
 
#  select,      
# user = fields.CharField( 
#     initial=2, 
#     widget=widgets.Select(choices=((1,'  '),(2,'  '),)) 
# ) 
 
#  select,      
# user = fields.ChoiceField( 
#     choices=((1, '  '), (2, '  '),), 
#     initial=2, 
#     widget=widgets.Select 
# ) 
 
#   select,     
# user = fields.MultipleChoiceField( 
#     choices=((1,'  '),(2,'  '),), 
#     initial=[1,], 
#     widget=widgets.SelectMultiple 
# ) 
 
 
#  checkbox 
# user = fields.CharField( 
#     widget=widgets.CheckboxInput() 
# ) 
 
 
#   checkbox,     
# user = fields.MultipleChoiceField( 
#     initial=[2, ], 
#     choices=((1, '  '), (2, '  '),), 
#     widget=widgets.CheckboxSelectMultiple 
# ) 

선택 탭을 사용할 때choices의 옵션은 데이터베이스에서 얻을 수 있지만 정적 필드에서 얻은 값이 실시간으로 업데이트되지 않기 때문에 사용자 정의 구조 방법을 사용하여 이 목적을 달성해야 합니다.
models.py
class UserType(models.Model):
    caption = models.CharField(max_length=32)

class UserInfo(models.Model):
    username = models.CharField(max_length=32)
    email = models.EmailField()
    user_type = models.ForeignKey(to='UserType',to_field='id')

방법 1:
from django.forms import Form 
from django.forms import widgets 
from django.forms import fields 
  
class UserInfoForm(forms.Form):
    username = Ffields.CharField(max_length=32)
    email = Ffields.EmailField()
    user_type = Ffields.ChoiceField(
        choices=models.UserType.objects.values_list('id','caption')
    )

    def __init__(self, *args, **kwargs):
        super(UserInfoForm,self).__init__(*args, **kwargs)
        self.fields['user_type'].choices = models.UserType.objects.values_list('id','caption')


방식2:django가 제공하는 ModelChoiceField와 ModelMultipleChoiceField 필드를 사용하여 실현
from django import forms 
from django.forms import fields 
from django.forms import widgets 
from django.forms import models as form_model  #  models  ,  
 
class FInfo(forms.Form): 
    authors = form_model.ModelMultipleChoiceField(queryset=models.NNewType.objects.all()) 
    # authors = form_model.ModelChoiceField(queryset=models.NNewType.objects.all()) 

좋은 웹페이지 즐겨찾기