form组件之modelForm

modelForm的使用及参数设置

  从modelForm这个名字就能看出来,这个form是和模型类model有知己诶关联的,还是以数和出版社的模型来说明:

models.py(模型)

复制代码
from django.db import models


# Create your models here.
class Book(models.Model):
    title = models.CharField(max_length=32)
    pub_date = models.DateField()
    price = models.DecimalField(max_digits=5, decimal_places=2)
    state=models.IntegerField(choices=((1,'已出版'),(2,'未出版')),default=1)  #在数据库存储是以数字存储的,怎么取值?book是类的对象--book.get_state_display
    publish = models.ForeignKey(to="Publish", to_field="id", on_delete=models.CASCADE, null=True)
    authors = models.ManyToManyField("Author", db_table="book2authors")  # 创建关系表

    def __str__(self):
        return self.title


class Publish(models.Model):
    name = models.CharField(max_length=32)
    city = models.CharField(max_length=32)
    email = models.CharField(max_length=32)

    def __str__(self):
        return self.name


class Author(models.Model):
    name = models.CharField(max_length=32)
    age = models.IntegerField()
    gender=models.IntegerField(choices=((1,'男'),(2,'女'),),default=1)#在数据库存储是以数字存储的,怎么取值?book是类的对象--book.get_gender_display

 urls.py(路径分发)

复制代码
urlpatterns = [
    path('admin/', admin.site.urls),
    path('books/', views.books, name='books'),
    path('addbooks/', views.addbooks, name='addbooks'),
    re_path('delbooks/(\d+)', views.delbooks),
    re_path('editbooks/(\d+)', views.editbooks)
]
复制代码

 

  view.py(视图函数)

复制代码
#创建Modelforms类并指向模型Book,为了渲染数据和校验使用
class BookModelForm(forms.ModelForm):    #看清楚继承的类不再是forms.Form而是forms.Modelform
class Meta:
model = models.Book #指定为哪个模型创建的
# fields=['title','price'] #指定模型的字段
# exclude=['title'] #排除互某个字段
fields = '__all__' #指定所有的字段

      widgets={                                           #参数设置,指定字段设置
            "title":wid.TextInput(attrs={"class":"form-control"}),
            "price":wid.TextInput(attrs={"class":"form-control"})
            }
      error_messages={                                   #错误信息设置,要看清楚对齐的方式
            "title":{"required":"该字段不能为空"}  
            }
      labels={                                          #对field的label进行设置
        "title":"书籍名称"
          }


#查看书籍
def books(request): booklist = models.Book.objects.all() return render(request, 'books.html', {'booklist': booklist})


#添加书籍
def addbooks(request):
# 通过form/ModelForm以及校验标签渲染字段以及输入框
if request.method == 'POST':
form = BookModelForm(request.POST)
if form.is_valid():
form.save()
return redirect('/books/')
else:
return render(request, 'addbooks.html', {'form': form})
else:
# form=BookForm() #form组件形式,根据字段选择不同的字段类型
form = BookModelForm()
return render(request, 'addbooks.html', {'form': form})


#编辑书籍
def editbooks(request, editbook_id):
editbook=models.Book.objects.filter(pk=editbook_id).first()
if request.method == 'POST':
form=BookModelForm(request.POST,instance=editbook) #对象要带,要不然直接保存,就跟添加是一模一样的,不变成了添加,而不是是修改修改源对象
if form.is_valid():
form.save()
return redirect('/books/')
else:
return render(request,'editbooks.html',{'form':form})
else:
form=BookModelForm(instance=editbook)
return render(request,'editbooks.html',{'form':form})
复制代码

   关于html:

#form.html  添加和编辑共用功能区共用这一部分,所以提取出来

<div class="container">
    <div class="row">
        <div class="col-md-4 col-md-offset-4">
            <form action="" method="post" novalidate>
                {% csrf_token %}
                {% for field in form %}
                    <div class="form-group">
                        <label for="title">{{ field.label }}</label>
                        {{ field }} <span>{{ field.errors.0 }}</span>
                    </div>
                {% endfor %}
                <input type="submit" value="提交" class="btn btn-default pull-right">
            </form>
        </div>
    </div>
</div>


#add_books.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>添加书籍</title>
<link rel="stylesheet" href="/static/bootstrap/css/bootstrap.css">
</head>
<body>

<h3>添加书籍</h3>
{% include 'form.html' %}

</body>
</html>

#edit_book
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>编辑书籍</title>
<link rel="stylesheet" href="/static/bootstrap/css/bootstrap.css">
</head>
<body>

<h3>编辑书籍</h3>

{% include 'form.html' %}

</body>
</html>


 

posted @ 2019-01-16 23:08  阿布_alone  阅读(323)  评论(0编辑  收藏  举报
TOP