Django-Form 양식 및 ModelForm

9699 단어 Django
1.form.py
from django import forms
from operation.models import UserAsk

class UserAskForm(forms.Form):
    name = forms.CharField(required=True,min_length=2,max_length=20)
    mobile = forms.CharField(required=True,min_length=11,max_length=11)
    course_name = forms.CharField(required=True,min_length=5,max_length=50)


#  DRf    serializers  
#           
class AnotherUserForm(forms.ModelForm):
    new_fields = forms.CharField(required=True)   #          
    class Meta:
        model = UserAsk
        # fields = "__all__"  #      
        fields = ('name', 'mobile', 'course_name', )  #     

    #save
2.View.py에서save 방법을 직접 호출할 수 있습니다.여기서 AnotherUserForm은 UserAskForm으로 이름이 변경되었습니다.
class AddUserAskView(View):
    def post(self,request):
        userask_form = UserAskForm(request.POST)
        if userask_form.is_valid():
            user_ask = userask_form.save(commit=True)

3. 사용자 정의 ModelForm의 필드 검증, 예를 들어 정규 표현식으로 핸드폰 번호가 합법적인지 검증한다.
class UserAskForm(forms.ModelForm):
    # new_fields = forms.CharField(required=True)   #          
    class Meta:
        model = UserAsk
        # fields = "__all__"  #      
        fields = ('name', 'mobile', 'course_name', )  #     

    #save
    #   mobile    
    def clean_mobile(self):
        '''
                  
        '''
        mobile = self.cleaned_data['mobile']
        #        
        REGEX_MOBILE = "^1[358]\d{9}$|^147\d{8}$|^176\d{8}$"
        p = re.compile(REGEX_MOBILE)
        if p.match(mobile):
            return mobile
        #           
        else:
            raise forms.ValidationError(u'      ',code='mobile_invalid')

좋은 웹페이지 즐겨찾기