ModelForm 사용 방법

2896 단어
우선 모델에 정의된 클래스를 보십시오.
class UserInfo(models.Model):
    """
     
    """
    username = models.CharField(max_length=32)
    password = models.CharField(max_length=64)
    nickname = models.CharField(max_length=32)
    email = models.EmailField()

    roles = models.ManyToManyField('Role')

    def __str__(self):
        return self.nickname

그리고view에 이렇게 쓰면 ModelForm 클래스를 만듭니다.
from django.forms import ModelForm
from django.forms import widgets as wid
from django.forms import fields as fld
class UserModelForm(ModelForm):

    # use = fld.CharField()

    class Meta:
        model = models.UserInfo
        fields = "__all__"    
        # fields = ['username','nickname',]
        # exclude = ['username',]
        # error_messages = {
        #     "username": {'required':' '}
        # }
        # widgets = {
        #     "username":wid.Textarea(attrs={'class':'c1'})
        # }
        # labels = {
        #     'username':' '
        # }
        # help_texts = {
        #     'username': ' , '
        # }
        #
        # field_classes = {
        #     'username': fld.EmailField
        # }

    # def clean_email(self):
    #     pass
    #
    # def clean_nickname(self):
    #     pass
    #
    # def clean(self):
    #     pass

view에 함수를 추가하고 실례화된 모델_form 프론트에 전달
def user_add(request):
    #  #  Form :
    if request.method == 'GET':
        model_form = UserModelForm()
        return render(request,'rbac/user_add.html',{'model_form':model_form})
    else:
        model_form = UserModelForm(request.POST)
        if model_form.is_valid():
            model_form.save()   #  , save 
            return redirect('/rbac/users.html')

        return render(request, 'rbac/user_add.html', {'model_form': model_form})

그리고 전방에서form을 빠르게 생성할 수 있습니다.
    
{% csrf_token %} {{ model_form.as_p }}

수정하다
def user_edit(request,pk):
    obj = models.UserInfo.objects.filter(pk=pk).first()

    if not obj:
        return redirect('/rbac/users.html')
    if request.method == 'GET':
        model_form = UserModelForm(instance=obj)
        return render(request,'rbac/user_edit.html',{'model_form':model_form})
    else:
        model_form = UserModelForm(request.POST,instance=obj)
        if model_form.is_valid():
            model_form.save()
            return redirect('/rbac/users.html')
        return render(request, 'rbac/user_edit.html', {'model_form': model_form})

좋은 웹페이지 즐겨찾기