Python菜鳥之路:Django ModelForm的使用

1、簡單使用案例html

#views.py
#views.py
from django.shortcuts import render,HttpResponse
from app01 import models

from django import forms
from django.forms import fields as Ffields
from django.forms import widgets as Fwidgets
class UserInfoModelForm(forms.ModelForm):

    is_rmb = Ffields.CharField(widget=Fwidgets.CheckboxInput())

    class Meta:
        model = models.UserInfo
        fields = '__all__'
        # fields =  ['username','email']
        # exclude = ['username']
        labels = {
            'username': '用戶名',
            'email': '郵箱',
        }
        help_texts = {
            'username': '...'
        }
        widgets = {
            'username': Fwidgets.Textarea(attrs={'class': 'c1'})
        }
        error_messages = {
            '__all__':{

            },
            'email': {
                'required': '郵箱不能爲空',
                'invalid': '郵箱格式錯誤..',
            }
        }
        field_classes = {
            # 'email': Ffields.URLField
        }

        # localized_fields=('ctime',)

    def clean_username(self):
        old = self.cleaned_data['username']
        return old

def index(request):
    if request.method == "GET":
        obj = UserInfoModelForm()
        return render(request,'index.html',{'obj': obj})
    elif request.method == "POST":
        obj = UserInfoModelForm(request.POST)
        if obj.is_valid():
            # obj.save() 等效於下面的3條
            instance = obj.save(False)
            instance.save()  # 這樣的話只會保存當前的類到數據庫,並不會保存關聯的多對多關係到U2G表中
            obj.save_m2m()  # 保存many to many的關係到數據庫


        # print(obj.is_valid())
        # print(obj.cleaned_data)
        # print(obj.errors.as_json())
        return render(request,'index.html',{'obj': obj})

  

  

#models.py
from django.db import models

# Create your models here.


class UserType(models.Model):
    caption = models.CharField(max_length=32)


class UserGroup(models.Model):
    name = 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')
    u2g = models.ManyToManyField(UserGroup)

  

    總結: 從上邊能夠看到ModelForm用起來也是很是方便的,好比增長修改之類的操做。可是也帶來額外很差的地方,model和model之間耦合了。若是不耦合的話,mf.save()方法也沒法直接提交保存。 可是耦合的話使用場景一般侷限用於小程序,寫大程序就最好不用了python

相關文章
相關標籤/搜索