10.12Django Form Form

Source: Internet
Author: User

2018-10-12 15:24:23

From form reference connection: https://www.cnblogs.com/yuanchenqi/articles/7614921.html

New use of modelform, more convenient and more concise than the form!

The more you try, the luckier you get! There are more than 30 days to complete the luffycity project and then there are other flask. Reptiles or something, and then you're done!

Tomorrow weekend, the blog to tidy up again!!!!!

Re-optimize your blog project!!! 233333333!

The more effort, the luckier! Never overestimate yourself!

views.py

 fromDjango.shortcutsImportRender,redirect from. ModelsImport* fromDjangoImportForms fromDjango.formsImportWidgets as Wid fromDjango.formsImportModelform#to convert the model into a form meta is a configuration classclassbookform (modelform):classMeta:model= book Fields="__all__"Labels= {            "title":"Book name",            " Price":"Price"        }        #add tags to specific boxesWidgets = {                "title": Wid. TextInput (attrs={"class":"Form-control"})                " Price": Wid. TextInput (attrs={"class":"Form-control"})                "authors": Wid. TextInput (attrs={"class":"Form-control"})            }        #Configuration Error message        #error_messages{        #     "": ""        # }#these are equivalent to the following native Bookform (forms. Form) class"""Bookform of the native"""#class Bookform (forms. Form):#title = forms. Charfield (max_length=32,label= "book name")#Price = forms. Decimalfield (max_digits=8, decimal_places=2,label= "price") # 999999.99#when rendering a specific tag, add something specific#date = forms. Datefield (label= "Date",#widget=widgets. TextInput (attrs={"type": "Date"})#     )## It's okay with the database .##gender =forms. Choicefield (choices= (1, "Male"), (2, "female"), (3, "other" )))## It has to do with the database and the following two##publish =forms. Choicefield (Choices=publish.objects.all (). Values_list ("PK", "title"))## Single-Selection drop-down box#publish=forms. Modelchoicefield (Queryset=publish.objects.all ())#authors=forms. Modelmultiplechoicefield (Queryset=author.objects.all ())defBooks (Request): Book_list=Book.objects.all ()returnRender (Request,"books.html", Locals ())"""using the native form form"""#def addbook (request):#if request.method== "POST":#form = bookform (Request. POST)#if Form.is_valid ():#print ("Cleaned_data", Form.cleaned_data)#Title=form.cleaned_data.get ("title")#price=form.cleaned_data.get ("Price")#date=form.cleaned_data.get ("date")#Publish=form.cleaned_data.get ("Publish")#Authors=form.cleaned_data.get ("authors") # [+]#book_obj=book.objects.create (title=title,price=price,date=date,publish=publish)#Book_obj.authors.add (*authors)#return Redirect ("/books/")#Form=bookform ()#Publish_list=publish.objects.all ()#Author_list=author.objects.all ()#return render (Request, "add.html", Locals ())"""add with Modelform."""defAddbook (Request):ifrequest.method=="POST": Form=Bookform (Request. POST)ifform.is_valid (): Form.save ()returnredirect"/books/")"""Native Form"""#def editbook (request,edit_book_id):#if request.method== "POST":#Title=request. Post.get ("title")#Price=request. Post.get ("Price")#Date=request. Post.get ("date")#Publish_id=request. Post.get ("publish_id")#Author_pk_list=request. Post.getlist ("Author_pk_list") # [+]##Book.objects.filter (pk=edit_book_id). Update (TITLE=TITLE,PRICE=PRICE,DATE=DATE,PUBLISH_ID=PUBLISH_ID) #Book_obj=book.objects.filter (pk=edit_book_id). First ()#Book_obj.authors.set (author_pk_list)#return Redirect ("/books/")#Edit_book=book.objects.filter (pk=edit_book_id). First ()#Form=bookform ()#return render (Request, "edit.html", Locals ())"""Edit_books made with Modelform."""defEditbook (request,edit_book_id): Edit_book= Book.objects.filter (pk=edit_book_id). First ()ifRequest.method = ="POST":        #Pass in a Isinstance object and let him know who to update .form = Bookform (Request. POST, isinstance=Edit_book)ifform.is_valid (): Form.save ()returnredirect"/books/") Form= Bookform (isinstance=Edit_book)returnRender (Request,"edit.html", locals ())

Like Add.html and edit_book.html.

<! DOCTYPE html>"ZH-CN">"UTF-8"> <title>Title</title> <meta name="Viewport"Content="Width=device-width, initial-scale=1">""Method="Post"Novalidate>     {% Csrf_token%}     {% forFieldinchForm%}        <div>{{Field.label}} {{field}}}</div>     {% ENDFOR%}    <input type="Submit"></form></body>

Notes

Native Formforms component Choicefield (Field) Modelchoicefield (Choicefield) Modelmultiplechoicefield (Modelchoicefield )       1designing form components for form forms ModelformclassBook (models. Model): Title=models. Charfield (max_length=32) Price=models. Decimalfield (max_digits=8,decimal_places=2)#999999.99Date=models. Datefield () Publish=models. ForeignKey ("Publish") Authors=models. Manytomanyfield ("Author")    classbookform (forms. Form): Title= Forms. Charfield (max_length=32,label="Book name") Price= Forms. Decimalfield (max_digits=8, decimal_places=2,label="Price")#999999.99Date = forms. Datefield (label="Date", Widgets=widgets. TextInput (attrs={"type":"Date"})        )        #gender=forms. Choicefield (choices= (1, "Male"), (2, "female"), (3, "other" )))        #publish=forms. Choicefield (Choices=publish.objects.all (). Values_list ("PK", "title"))Publish=forms. Modelchoicefield (queryset=Publish.objects.all ()) Authors=forms. Modelmultiplechoicefield (Queryset=author.objects.all ())

10.12Django Form Form

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.