多应用+插件架构,代码干净,二开方便,首家独创一键云编译技术,文档视频完善,免费商用码云13.8K 广告
>[success] # 基础案例 ~~~ 1.创建表时会默认创建自增列id字段 2.创建两个表的字段关系用ForeignKey 3.ForeignKey的变量名实际是关联表的对象,实际字段是变量名_id ~~~ >[danger] ##### model.py ~~~ from django.db import models # Create your models here. class Business(models.Model): caption = models.CharField(max_length=32) class Host(models.Model): nid = models.AutoField(primary_key=True) hostname = models.CharField(max_length=32) bussiness = models.ForeignKey(Business) ~~~ >[danger] ##### views.py ~~~ from django.shortcuts import render,redirect # Create your views here. from . import models def index(request): if request.method == "GET": hostobj = models.Host.objects.all() busobj = models.Business.objects.all() return render(request,'index.html',{'hostobj':hostobj,"busobj":busobj}) if request.method == "POST": h = request.POST.get('hostname',None) b = request.POST.get('b_name',None) models.Host.objects.create(hostname=h,bussiness_id=b) return redirect('/index/') ~~~ >[danger] ##### templates ~~~ <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> .hid{ display: none; } .back{ position: fixed; left: 0; right: 0; bottom: 0; top: 0; background:black; opacity:0.3; z-index: 100; } .add_modal{ position: fixed; height: 400px; width: 500px; top: 200px; left: 500px; background:white; z-index: 101; } </style> </head> <body> <input type="button" id="addmodel" value="添加"> <div class="hid back"> <div class="add_modal"> <form method="post"> {% csrf_token %} <input type="text" name="hostname"> <br> <select name="b_name"> {% for i in busobj %} <option value="{{i.id }}">{{ i.caption }}</option> {% endfor %} </select> <input type="submit"> </form> </div> </div> <ul> {% for i in hostobj %} <li>{{ forloop.counter }}{{ i.hostname }}-{{ i.bussiness.caption }}</li> {% endfor %} </ul> </body> <script src="/static/jquery-1.12.4.js"></script> <script> $(function () { Bindclik(); }); function Bindclik() { $('#addmodel').click( function () { $('.back').removeClass("hid") } ) } </script> </html> ~~~