首页 > 代码库 > Python 【第十三章】 Django 之 FORM
Python 【第十三章】 Django 之 FORM
不涉及数据库存储数据例一 :FORM 实现页面下拉选择框:
url.py
from django.conf.urls import url from django.contrib import admin from app01 import views urlpatterns = [ # url(r‘^admin/‘, admin.site.urls), url(r‘^index/‘,views.index), ]
views.py
from django.shortcuts import render from django.shortcuts import HttpResponse from app01 import models from django import forms class Indexform(forms.Form): c = { (1,‘CEO‘), (2,‘COO‘) } user_type_id = forms.IntegerField(widget=forms.Select(choices=c)) def index(request): form = Indexform() return render(request,‘index.html‘,{‘form‘:form})
index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title></title> </head> <body> <h1>index</h1> {{ form.user_type_id }} </body> </html>
涉及数据库存储数据例二:通过models.py 一对一外表关联方式来实现
models.py
from django.db import models # Create your models here. class UserType(models.Model): caption = models.CharField(max_length=16) class UserInfo(models.Model): user = models.CharField(max_length=32) pwd = models.CharField(max_length=32) user_type = models.ForeignKey(‘UserType‘)
创建数据库表执行以下两个语句:
python manage.py makemigrations python manage.py migrate
views.py 通过循环来生成数据
from django.shortcuts import render # from django.shortcuts import HttpResponse from app01 import models from django import forms class Indexform(forms.Form): # c = { # (1,‘CEO‘), # (2,‘COO‘) # } c = models.UserType.objects.all().values_list(‘id‘,‘caption‘) user_type_id = forms.IntegerField(widget=forms.Select(choices=c)) def index(request): for i in range(10): models.UserType.objects.create(caption=‘CE‘+str(i)) c = models.UserType.objects.all().count() print(c) form = Indexform() return render(request,‘index.html‘,{‘form‘:form})
生成 数据后,修改viiews.py
from django.shortcuts import render # from django.shortcuts import HttpResponse from app01 import models from django import forms class Indexform(forms.Form): # c = { # (1,‘CEO‘), # (2,‘COO‘) # } c = models.UserType.objects.all().values_list(‘id‘,‘caption‘) user_type_id = forms.IntegerField(widget=forms.Select(choices=c)) def index(request): # for i in range(10): # models.UserType.objects.create(caption=‘CE‘+str(i)) # c = models.UserType.objects.all().count() # print(c) form = Indexform() return render(request,‘index.html‘,{‘form‘:form})
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<h1>index</h1>
{{ form.user_type_id }}
</body>
</html>
遇到问题,如果在数据库中继续添加新数据,会出现页面没有显示 新数据,如果显示 ,需要重启django
以下方法是解决上述问题
Python 【第十三章】 Django 之 FORM
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。