博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
ModelForm理解简单运用(增删改查)
阅读量:6265 次
发布时间:2019-06-22

本文共 1898 字,大约阅读时间需要 6 分钟。

from django.shortcuts import render, redirect,HttpResponse # Create your views here. from django.forms import widgets as wid from django.forms import ModelForm from .models import * class BookForm(ModelForm):     class Meta:         model = Book         fields = "__all__"         labels = {"title": "书籍名称", "price": "价格"}         widgets = {
"title": wid.TextInput(attrs={"class": "form-control"}), "price": wid.TextInput(attrs={"class": "form-control"}), "date": wid.TextInput(attrs={"class": "form-control", "type": "date"}), "publish": wid.Select(attrs={"class": "form-control"}), "authors": wid.SelectMultiple(attrs={"class": "form-control"}), } error_messages = {
"title": {"required": "不能为空"} } def booklist(request): book_list = Book.objects.all() return render(request,"booklist.html",locals()) def add(request): if request.method == "POST": form = BookForm(request.POST) if form.is_valid(): form.save() return redirect("/booklist/") else: return render(request,"add.html",locals()) form = BookForm() return render(request,"add.html",locals()) def edit(request,edit_book_id): edit_book = Book.objects.filter(pk=edit_book_id).first() if request.method == "POST": form = BookForm(request.POST, instance=edit_book) if form.is_valid(): form.save() # edit_book.update(request.POST) return redirect("/booklist/") form = BookForm(instance=edit_book) return render(request,"edit.html",locals()) def delete(request,delete_book_id): if delete_book_id: Book.objects.filter(pk=delete_book_id).first().delete() return redirect("/booklist/") else: return HttpResponse("数据不存在,出错了")

 

转载于:https://www.cnblogs.com/FWF1944/p/10877983.html

你可能感兴趣的文章
网站目录
查看>>
APUE-文件和目录(七)符号链接
查看>>
CSS 简介
查看>>
System Verilog基础(二)
查看>>
2018/11/26 Samba服务器配置
查看>>
2018/12/08 PAT刷题 L1-034 点赞
查看>>
如何改变TextBox.PassWordChar的值 转
查看>>
css的工作原理
查看>>
【pip】的安装
查看>>
内存泄漏及其检测工具
查看>>
QT Model based vs Item based
查看>>
[Leetcode]669 Trim a Binary Search Tree
查看>>
Linux C Programing - Arguments(2)
查看>>
禁止选择文本和禁用右键 v1.0
查看>>
swift 动画
查看>>
can 驱动
查看>>
Linux使用ASF云挂卡(挂游戏时长)
查看>>
UML入门 之 交互图 -- 时序图 协作图详解
查看>>
【Android 多媒体开发】 MediaPlayer 网络视频播放器
查看>>
Linux 绝对路径与相对路径
查看>>