ModelForm

 

 

Model,操作数据
	
Form,用户请求验证+生成HTML标签


应用场景:
	大型应用:
		Model,操作数据
		Form,用户请求验证+生成HTML标签
	小型应用:
		ModelForm,操作数据+用户请求验证+生成HTML标签

a. 事例

from django.conf.urls import url,include
from django.contrib import admin
from app01 import views
urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^test/', views.test),
    url(r'^edit-(\d+)/', views.edit),
]
urls.py
from django.db import models

class UserGroup(models.Model):

    title = models.CharField(max_length=32)

    def __str__(self):
        return self.title
class Role(models.Model):
    name = models.CharField(max_length=32)

    def __str__(self):
        return self.name
class UserInfo(models.Model):
    user = models.CharField(max_length=32)
    email = models.EmailField()
    ug = models.ForeignKey(UserGroup,null=True,blank=True)

    m2m = models.ManyToManyField('Role')

    def __str__(self):
        return self.user
models.py
from django.shortcuts import render,HttpResponse,redirect
from app01 import models
from django.template.response import TemplateResponse
from django.forms import Form,ModelForm
from django.forms import fields as ffields
from django.forms import widgets as fwidgets

"""
class TestForm(Form):
    user = fields.CharField()
    email = fields.EmailField()
    ug_id = fields.ChoiceField(
        widget=widgets.Select,
        choices=[]
    )

    def __init__(self,*args,**kwargs):
        super(TestForm,self).__init__(*args,**kwargs)

        self.fields['ug_id'].choices = models.UserGroup.objects.values_list('id','title')


def test(request):
    if request.method == "GET":
        form = TestForm()
        context = {
            'form': form
        }
        return render(request,'test.html',context)
    else:
        form = TestForm(request.POST)
        if form.is_valid():
            # {ug:1}
            models.UserInfo.objects.create(**form.cleaned_data)
            return redirect('http://www.oldboyedu.com')
        context = {
            'form': form
        }
        return render(request, 'test.html', context)
"""

class TestModelForm(ModelForm):
    user = ffields.EmailField(label='用户名')

    class Meta:
        model = models.UserInfo
        fields = "__all__"
        error_messages = {
            'user':{'required':'用户名不能为空'},
            'email':{'required':'邮箱不能为空','invalid':'邮箱格式错误'},
        }
        labels = {
            'user': '用户名',
            'email': "邮箱"
        }
        help_texts = {
            'user': "帮你一下"
        }
        # widgets = {
        #     'user': fwidgets.Textarea(attrs={'class':'c1'})
        # }
        # field_classes = {
        #     'user': ffields.EmailField
        # }

    # def clean_user(self):
    #     pass
    #
    # def clean_email(self):
    #     pass
def test(request):
    if request.method == "GET":
        form = TestModelForm()
        context = {
            'form': form
        }
        return render(request,'test.html',context)
    else:
        form = TestModelForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect('http://www.oldboyedu.com')
        context = {
            'form': form
        }
        return render(request, 'test.html', context)


def edit(request,nid):
    obj = models.UserInfo.objects.filter(id=nid).first()
    if request.method == "GET":
        form = TestModelForm(instance=obj)
        context = {
            'form': form
        }
        return render(request, 'edit.html', context)
    else:
        form = TestModelForm(instance=obj,data=request.POST,files=request.FILES)
        if form.is_valid():
            form.save()
            return redirect('http://www.oldboyedu.com')
        context = {
            'form': form
        }
        return render(request, 'test.html', context)
views.py
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <form method="POST" novalidate>
        {% csrf_token %}
        {{ form.as_p }}
{#        <p>{{ form.user }}{{ form.user.errors.0 }}</p>#}
{#        <p>{{ form.email }}{{ form.email.errors.0 }}</p>#}
{#        <p>{{ form.ug }}{{ form.ug.errors.0 }}</p>#}
{#        <p>{{ form.m2m }}{{ form.m2m.errors.0 }}</p>#}
        <input type="submit"  value="提交" />
    </form>
</body>
</html>
test.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <form method="POST" novalidate>
        {% csrf_token %}
        <p>{{ form.user }}{{ form.user.errors.0 }}</p>
        <p>{{ form.email }}{{ form.email.errors.0 }}</p>
        <p>{{ form.ug }}{{ form.ug.errors.0 }}</p>
        <p>{{ form.m2m }}{{ form.m2m.errors.0 }}</p>
        <input type="submit"  value="提交" />
    </form>
</body>
</html>
edit.html

 

沛齐

 

  

posted @ 2017-09-08 17:03  golangav  阅读(219)  评论(0编辑  收藏  举报