zoukankan      html  css  js  c++  java
  • Django ModelForm组件

    代码

    from django import forms
    from django.forms import widgets as wig  # 因为重名,所以起个别名
    from django.shortcuts import render
    
    from app01.models import Book
    
    
    class BookModel(forms.ModelForm):
        class Meta:
            model = Book  # 对应的model对象
            # 包括哪些字段
            fields = "__all__"
            # fields = ['title','price']
            # 不包括
            # exclude = ['title']
            labels = {
                'title': '书籍名称',
                'price': '价格'
            }
            error_messages = {
                'title': {'required': '标题错误'},
                'price': {'required': '价格输入有误'}
            }
            widgets = {
                "title": wig.TextInput(attrs={'class': 'c1'})
            }
    #钩子函数和form一样
    def clean_price(self): pass def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) for fields in self.fields.values(): fields.widget.attrs.update({'class': 'form-control'}) # Create your views here. def index(request): if request.method == "GET": # 模型直接渲染页面 book = BookModel() # 带值,渲染 book = BookModel(instance=Book.objects.filter(pk=1).first()) return render(request, '1.html', locals()) else: book = BookModel(request.POST) if book.is_valid(): # 数据直接存储到数据库 book.save() # book = BookModel(request.POST,instance=book_01) 指定了对应到图书内容 # book.save() #这里就update操作 return render(request, '1.html', locals())
  • 相关阅读:
    Python2 cmp() 函数
    Python round() 函数
    Python floor() 函数
    Python ceil() 函数
    Python abs() 函数
    Python oct() 函数
    Python ord() 函数
    Python hex() 函数
    Python2 unichr() 函数
    Android--------工具类StatusBarUtil实现完美状态栏
  • 原文地址:https://www.cnblogs.com/ls1997/p/11140488.html
Copyright © 2011-2022 走看看