stark元件之pop頁面,按鈕,url,頁面
阿新 • • 發佈:2018-11-12
- 1、Window open() 方法
- 2、admin的pop新增按鈕
- 3、stark之pop功能
- 3、知識點總結
- 4、coding程式碼
1、Window open() 方法
效果圖
2、admin的pop新增按鈕
3、stark之pop功能
POP功能:
1.如何只有多對多和一對多欄位後面才渲染 "+"
2."+"的對應的跳轉路徑
3.儲存新增記錄的同時,應該將原頁面對應的下拉選單新增該記錄。
1、
2、多對多欄位如何渲染
3、isinstance判斷型別
4、 一對多或多對多欄位的關聯模型
5、bootstrap頁面自適應col-xs-8
6、model表顯示的是__str__
7、構造url
8、傳遞資料,window.open使用
3、知識點總結
1、pop功能:
1.在一對多和多對多欄位後渲染 +
2.+對應的跳轉路徑
3.儲存新增記錄同時,將原頁面的對應的下拉選單中新增該記錄
2、在一對多和多對多欄位後渲染+
後臺需要先判斷 是否是 一對多 多對多欄位
modelform, 遍歷
for bfield in form:
print(bfield.field) # 是每個form欄位物件
所以:判斷是否是一對多,多對多欄位
if isinstance(bfield.field, ModelChoiceField):
bfield.is_pop = True # 為特殊欄位加上特有屬性,方便前端判斷。
注意:ModelMultipleChoiceField(多對多) 繼承 ModelChoiceField(一對多)
ModelChoiceField 繼承 ChoiceField
3、+對應的跳轉路徑
form表單得一對多,多對多得欄位物件
bfield.field.queryset.model # 相關聯得模型!!<class 'app01.models.Publish'>
#(模型表得物件去找 filter_field_obj.rel.to.objects.all(),到to是模型。)
根據queryset找model queryset.model
根據model找queryset model.objects.all()
related_model_name = bfield.field.queryset.model._meta.model_name # publish
related_app_label = bfield.field.queryset.model._meta.app_label # app01
反向解析url
_url = reverse("%s_%s_add" % (related_app_label, related_model_name))
# 為bfield新增自己特有的url,
# ?後面是為了,區分是top,還是正常頁面開啟/add/,方便之後關閉,以及賦值。
bfield.url = _url + "?pop_res_id=id_%s" % bfield.name
4、關閉彈出得top頁面
top彈出,關閉頁面,回到到原頁面;
正常新增,跳轉到list頁面;
返回 res = {"pk":obj.pk, 'text':str(obj), "pop_res_id": pop_res_id}
到pop.html,方便關閉pop頁面
pop.html:
關閉以及將接收得資料傳到原頁面上!
window.opener.pop_response("{{ res.pk}}","{{ res.text }}","{{ res.pop_res_id }}");
window.close()
5、原頁面接收資料,並顯示剛新增得資料(window.opener)
拿到 id, text, pop_res_id
動態建立 option append到對應得下拉框中,並選中;
var $option = $("<option>");
$option.html(text);
$option.val(pk);
$option.attr('selected','selected');
$('#'+pop_res_id).append($option)
6、前端展示:定位,(父相子絕)
<div style="position: relative"> {% if field.is_pop %} <a onclick="pop('{{ field.url }}')"><span style="font-size: 23px;position: absolute; right: -23px; top: 25px;">+</span></a> {% endif %} </div>
7、補充:
ChoiceFiled
ModelChoiceFiled(ChoiceFiled) ---- select(單選) --- ForeignKey
MultiModelChoiceFiled (ModelChoiceFiled)----select(多選) --- ManyToManyField
Book模型,form表單,modelform;
modelform幫我們轉成了form表單;
bootstrap頁面自適應: col-xs-8
程式碼註釋總結:
首先準備工作做完: window.opener.pop_response('{{ res.pk }}','{{ res.text }}','{{ res.pop_res_id }}'); window.close() 在pop頁面關閉前把指定的值傳參給主頁面執行,然後執行一個close,關閉掉自己。
2.增加檢視函式
# 增加資料檢視函式 def add_view(self,request): ModelFormDemo=self.get_modelform_class() form = ModelFormDemo() #迴圈每個form欄位,看看他們的型別是不是一對多和對多型別,是的話需要前端新增+號 for bfield in form: 迴圈ModelForm的每一個欄位,把多對多和一對多欄位篩選出來。 print(bfield.field) #欄位物件 print(bfield.name) #欄位名(字串) from django.forms.models import ModelChoiceField if isinstance(bfield.field,ModelChoiceField): bfield.is_pop=True 如果需要加+的話,那麼賦一個True的值。方便前端判定 【 {% if field.is_pop %} <a onclick="pop('{{ field.url }}')" href="" style="position: absolute;right: -30px;top: 26px"><spanstyle="font-size: 26px">+</span></a> {% endif %} 】 #print(bfield.field.queryset.model)
#這裡需要注意,pop出來頁面需要新增的表名和app名,和主頁面的新增是不一樣的。
注意:
related_model_name=bfield.field.queryset.model._meta.model_name related_app_label=bfield.field.queryset.model._meta.app_label
#通過一個方向解析拿到一個url.
_url=reverse("%s_%s_add"%(related_app_label,related_model_name))
#要知道的是,點的哪個加號,在URL後加一個這個欄位的名字,做一個記號。
bfield.url=_url+"?pop_res_id=id_%s"%bfield.name
檢視函式中繼續:
if request.method=="POST": form = ModelFormDemo(request.POST) if form.is_valid(): obj=form.save() pop_res_id=request.GET.get("pop_res_id") #每一個modelform渲染到前端的id是id_+"欄位名" #<input type="text" name="title" maxlength="32" required="" id="id_title"> if pop_res_id: #如果能取到id的話,表示是pop頁面而不是主頁面的新增。 res={"pop_res_id":pop_res_id,"pk":obj.pk,"text":str(obj)} #pop頁面新增成功以後,obj也就有了值,就是當前新增這條資料的各種值, #取到id,新增的欄位,新增的內容給了前端模板。 return render(request,"pop.html",locals()) else: return redirect(self.get_list_url()) return render(request,"add_view.html",locals())
前端模板拿到後端傳過來的url以後,渲染到+上。
http://127.0.0.1:8000/stark/app01/publish/add/?pop_res_id=id_publish http://127.0.0.1:8000/stark/app01/author/add/?pop_res_id=id_authors 點選不同的+,url也不同。pop_res_id也都不同。 同時給+繫結一個彈框事件: function pop(url) { window.open(url,"","width=600,height=400,top=100,left=100") } 開啟框以後,新增完畢點選提交後,
window.opener.pop_response('{{ res.pk }}','{{ res.text }}','{{ res.pop_res_id }}');
window.close()
#把值取到並且把視窗關閉。
最後就是
function pop_response(pk,text,pop_res_id){ var $option = $("<option>"); //建立一個標籤 $option.html(text); //將新增的資料的文字值給了這個標籤內容 $option.val(pk); //賦一個value值,值是這條記錄的PK $option.attr("selected","selected"); //預設為選中 $("#"+pop_res_id).append($option) //哪個標籤後新增的,就把這個option放到哪個標籤下。 } #主新增頁面拿到關閉前通過引數傳過來的值以後,渲染出一個option標籤,把內容,和id,等全部寫好,最後加到指定的select標籤下面。
4、coding程式碼
1、starkadmin
from django.shortcuts import HttpResponse from stark.service import stark from .models import * from django.forms import ModelForm class AuthorConfig(stark.ModelStark): list_display = ['nid', 'name', 'age'] list_display_links = ['name','age'] class BookModelForm(ModelForm): class Meta: model = Book fields = "__all__" labels = { "authors":"作者", "publishDate":"出版日期", } class BookConfig(stark.ModelStark): # list_display = ['title', 'price','publish','authors'] list_display = ['__str__',] list_display_links = ['title'] modelform_class = BookModelForm search_fields = ['title','price'] list_filter = ['title','publish','authors'] # 一對多,多對多欄位 # 批量修改資料 def patch_init(self,request,queryset): queryset.update(price=111) # return HttpResponse("批量初始化OK") patch_init.short_description = "批量初始化" actions = [patch_init] stark.site.register(Book,BookConfig) stark.site.register(Publish) stark.site.register(Author,AuthorConfig) stark.site.register(AuthorDetail) # print(stark.site._registry)View Code
2、stark/service/stark.py
# -*- coding: utf-8 -*- # @Time : 2018/08/17 0017 14:46 # @Author : Venicid from django.conf.urls import url from django.shortcuts import HttpResponse,render,redirect from django.utils.safestring import mark_safe from django.urls import reverse from django.db.models import Q # 與或非 from django.db.models.fields.related import ForeignKey from django.db.models.fields.related import ManyToManyField import copy from stark.utils.page import Pagination class ShowList(object): def __init__(self,config, data_list,request): self.config = config # MOdelStark例項物件 self.data_list = data_list # 資料 self.request =request # 分頁 data_count = self.data_list.count() current_page = int(self.request.GET.get('page',1)) base_path = self.request.path self.pagination = Pagination(current_page,data_count,base_path,self.request.GET,per_page_num=10, pager_count=11,) # 分頁後的資料 self.page_data = self.data_list[self.pagination.start:self.pagination.end] # actions 批量初始化,欄位 # self.actions = self.config.actions # [patch_init] self.actions = self.config.new_actions() # [pathch_delete,patch_init,] # 構建資料[{'name':'path_init',"desc":'xxxxx'}] # filter的tag如何生成的 def get_filter_linktags(self): link_dic = {} for filter_field in self.config.list_filter: # ['title','publish','authors'] # 1.獲取url中的相關欄位,後面比較 current_id = self.request.GET.get(filter_field,0) pararms = copy.deepcopy(self.request.GET) # 2 頁面生成 各種欄位 filter_field_obj = self.config.model._meta.get_field(filter_field) print(filter_field_obj,type(filter_field_obj)) # app01.Book.publish < class 'django.db.models.fields.related.ForeignKey'> # app01.Book.authors < class 'django.db.models.fields.related.ManyToManyField'> # print('rel...',filter_field_obj.re) # <ManyToOneRel: app01.book> # print('rel...',filter_field_obj.re.to.objects.all()) # <QuerySet [<Publish: 南京出版社>, <Publish: 北京出版社>]> # 解決步驟 # print('rel...',filter_field_obj.__dict__) # print('rel...',filter_field_obj.remote_field) # print('rel...',filter_field_obj.remote_field.__dict__) # print("rel...", filter_field_obj.remote_field.model.objects.all()) # <QuerySet [<Publish: 南京出版社>, <Publish: 北京出版社>]> # <QuerySet [<Author: jack>, <Author: tom>]> # 一對一欄位or一對多欄位 if isinstance(filter_field_obj,ForeignKey) or isinstance(filter_field_obj,ManyToManyField): data_list = filter_field_obj.remote_field.model.objects.all() else: # 普通欄位 data_list = self.config.model.objects.all().values('pk',filter_field) # 3、 生成標籤的href temp = [] if pararms.get(filter_field): del pararms[filter_field] temp.append("<a href='?%s'>全部</a>"%pararms.urlencode()) else: temp.append("<a href='#' class='active'>全部</a>") # 處理filter欄位的href for obj in data_list: # print(data_list) # 一對一,一對多欄位 if isinstance(filter_field_obj, ForeignKey) or isinstance(filter_field_obj, ManyToManyField): pk = obj.pk text = str(obj) pararms[filter_field] = pk else: # 普通欄位 pk = obj.get('pk') text = obj.get(filter_field) pararms[filter_field] = text _url = pararms.urlencode() # print(type(current_id),type(pk),type(text)) if str(current_id) == str(pk) or str(current_id) ==str(text): link_tag = "<a href='?%s' class='active'>%s</a>"%(_url,text) else: link_tag = "<a href='?%s'>%s</a>"%(_url,text) temp.append(link_tag) link_dic[filter_field] = temp return link_dic def get_action_list(self): """action批量初始化,構架資料""" temp = [] for action in self.actions: temp.append( {'name':action.__name__, # class的類名 "desc":action.short_description # class的屬性 } ) return temp def get_header(self): # 構建表頭 header_list = [] # # header_list = ['選擇','pk',...'操作','操作'] for field in self.config.new_list_play(): if callable(field): # header_list.append(field.__name__) val = field(self.config, header=True) header_list.append(val) else: if field == "__str__": header_list.append(self.config.model._meta.model_name.upper()) else: val = self.config.model._meta.get_field(field).verbose_name # 中文名稱 header_list.append(val) return header_list def get_body(self): # 構建表單 new_data_list = [] for obj in self.page_data: #分頁後的資料 # Book表模型,Author表模型 temp = [] for field in self.config.new_list_play(): # ["__str__"] ['name','age'] if callable(field): # edit() 可呼叫的 val = field(self.config,obj) # 直接呼叫edit()函式 else: try: field_obj = self.config.model._meta.get_field(field) if isinstance(field_obj,ManyToManyField): ret = getattr(obj,field).all() # 反射 obj是例項物件,name是方法 t = [] for obj in ret: t.append(str(obj)) val = ','.join(t) else: val = getattr(obj, field) # list_display_links 按鈕 if field in self.config.list_display_links: _url = self.config.get_change_url(self,obj) val = mark_safe("<a href='%s'>%s</a>"%(_url,val)) # __str__ 的步驟 except Exception as e: val = getattr(obj,field) # <bound method Book.__str__ of <Book: php> _url = self.config.get_change_url(obj) # /app01/book/3/change/ val = mark_safe("<a href='%s'> %s </a>" % (_url, val())) temp.append(val) new_data_list.append(temp) # print('new_data_list',new_data_list) # 構造資料 [['jack', 44], ['mark', 33]] return new_data_list class ModelStark(object): list_display = ['__str__',] # 子類中沒有,直接用父類自己的 list_display_links = [] modelform_class = [] search_fields = [] # 模糊查詢欄位 actions = [] list_filter = [] # 過濾欄位 # 批量刪除 def patch_delete(self,request,queryset): queryset.delete() patch_delete.short_description = "Delete selected " def __init__(self,model, site): self.model = model self.site = site # 增刪改查url def get_add_url(self): model_name = self.model._meta.model_name app_label = self.model._meta.app_label _url = reverse("%s_%s_add" %(app_label,model_name)) return _url def get_list_url(self): model_name = self.model._meta.model_name app_label = self.model._meta.app_label _url = reverse("%s_%s_list" %(app_label,model_name)) return _url def get_change_url(self,obj): model_name = self.model._meta.model_name app_label = self.model._meta.app_label _url = reverse("%s_%s_change" %(app_label,model_name),args=(obj.pk,)) return _url # 複選框,編輯,刪除 def checkbox(self,obj=None, header=False): if header: return mark_safe("<input id='choice' type='checkbox'>") return mark_safe("<input class='choice_item' type='checkbox' name='selected_pk' value='%s'>"%obj.pk) def edit(self,obj=None, header=False): if header: return "操作" # 方案1:固定url # return mark_safe("<a href=/stark/app01/userinfo/%s/change>編輯</a>") # 方案2:拼接url # return mark_safe("<a href='%s/change'>編輯</a>") # 方案3:反向解析 model_name = self.model._meta.model_name app_label = self.model._meta.app_label _url = reverse("%s_%s_change"%(app_label,model_name),args=(obj.pk,)) # print("_url",_url) return mark_safe("<a href='%s'>編輯</a>"%_url) def deletes(self,obj=None, header=False): if header: return "操作" model_name = self.model._meta.model_name app_label = self.model._meta.app_label _url = reverse("%s_%s_delete"%(app_label,model_name),args=(obj.pk,)) return mark_safe("<a href='%s'>刪除</a>"%_url) # ModelForm元件渲染 list、增、刪、改頁面 def get_modelform_class(self): """ModelForm元件""" if not self.modelform_class: from django.forms import ModelForm class ModelFormDemo(ModelForm): class Meta: model = self.model fields = "__all__" return ModelFormDemo else: return self.modelform_class def new_list_play(self): """構建 ['checkbox','pk', 'name', 'age', edit,'delete']""" temp = [] temp.append(ModelStark.checkbox) temp.extend(self.list_display) if not self.list_display_links: temp.append(ModelStark.edit) temp.append(ModelStark.deletes) return temp # action = ['delete',...] def new_actions(self): temp = [] temp.append(ModelStark.patch_delete) # delete新增 temp.extend(self.actions) # 如果定義新的,就擴充套件到temp中 return temp ''' def list_view(self,request): ret1 = self.model.objects.filter(title__startswith='py') ret2 = self.model.objects.filter(price__in=[11,22,33,44,55]) ret3 = self.model.objects.filter(price__range=[10,20]) ret4 = self.model.objects.filter(title__contains='O') ret5 = self.model.objects.filter(title__icontains='O') return HttpResponse("過濾成功") ''' def get_search_condition(self,request): """search模糊查詢""" key_word = request.GET.get("q",'') self.key_word = key_word search_connection = Q() if key_word: search_connection.connector = "or" for search_field in self.search_fields: search_connection.children.append((search_field+"__contains", key_word)) return search_connection def get_filter_condition(self,request): """filter過濾處理""" filter_condition = Q() # 並且 for filter_field,val in request.GET.items(): if filter_field in self.list_filter: # list_filter = ['publish','authors'] filter_condition.children.append((filter_field,val)) return filter_condition def list_view(self, request): if request.method == 'POST': # print('post',request.POST) action = request.POST.get("action") # action': ['patch_init'], if action: selected_pk = request.POST.getlist('selected_pk') # 'selected_pk': ['5']}> action_func = getattr(self,action) # 反射查詢 action # 取出例項方法 queryset = self.model.objects.filter(pk__in=selected_pk) # 查詢 ret = action_func(request,queryset) # 執行action() # 執行例項方法() # return ret # 獲取search的Q物件 search_connection = self.get_search_condition(request) # 獲取filter構建Q物件 filter_condition = self.get_filter_condition(request) # 篩選獲取當前表所有資料 # data_list = self.model.objects.all().filter(search_connection) data_list = self.model.objects.all().filter(search_connection).filter(filter_condition) #按照showlist展示頁面, 構建表頭,表單 show_list = ShowList(self,data_list,request) # self=ModelSTark例項物件 # 構建一個檢視addurl add_url = self.get_add_url() return render(request,'list_view.html', locals()) def add_view(self, request): ModelFormDemo=self.get_modelform_class() form = ModelFormDemo() # 列印form的每個欄位 from django.forms.boundfield import BoundField from django.forms.models import ModelChoiceField from django.forms.models import ModelMultipleChoiceField for bfield in form: # print(type(bfield)) # <class 'django.forms.boundfield.BoundField'> # print('field',bfield.field) # <django.forms.models.ModelChoiceField object at 0x000000F2C0DEDC50> # print('name',bfield.name) # publish if isinstance(bfield.field,ModelChoiceField): bfield.is_pop = True # print(bfield.field.queryset.model) # 一對多或多對多欄位的關聯模型 # <class 'app01.models.Publish'> <class 'app01.models.Author'> # print(bfield.field.queryset.model._meta) # app01.author related_app_name = bfield.field.queryset.model._meta.app_label # app01 related_model_name = bfield.field.queryset.model._meta.model_name # author _url = reverse("%s_%s_add"%(related_app_name,related_model_name)) bfield.url = _url+"?pop_res_id=id_%s"%bfield.name if request.method == "POST": form = ModelFormDemo(request.POST) if form.is_valid(): obj = form.save() # window.open新增頁面 要返回的資料 pop_res_id = request.GET.get('pop_res_id') if pop_res_id: res = {"pk":obj.pk,'text':str(obj),'pop_res_id':pop_res_id} return render(request,'pop_view.html',locals()) else: return redirect(self.get_list_url()) return render(request, "add_view.html",locals()) def delete_view(self, request, id): url = self.get_list_url() if request.method == "POST": self.model.objects.filter(pk=id).delete() return redirect(url) return render(request, "delete_view.html", locals()) def change_view(self, request, id): edit_obj = self.model.objects.filter(pk=id).first() ModelFormDemo=self.get_modelform_class() form = ModelFormDemo(instance=edit_obj) if request.method == "POST": form = ModelFormDemo(request.POST,instance=edit_obj) if form.is_valid(): form.save() return redirect(self.get_list_url()) return render(request, "change_view.html",locals()) #構造 add/delete/change def get_urls2(self): model_name = self.model._meta.model_name app_label = self.model._meta.app_label temp = [] temp.append(url(r'^$', self.list_view, name='%s_%s_list'%(app_label,model_name))) temp.append(url(r'^add/', self.add_view, name='%s_%s_add'%(app_label,model_name))) temp.append(url(r'^(\d+)/delete/', self.delete_view, name='%s_%s_delete'%(app_label,model_name))) temp.append(url(r'^(\d+)/change/', self.change_view, name='%s_%s_change'%(app_label,model_name))) return temp @property def urls2(self): return self.get_urls2(), None, None class StarkSite(object): """site單例類""" def __init__(self): self._registry = {} def register(self,model, stark_class=None): """註冊""" if not stark_class: stark_class = ModelStark self._registry[model] = stark_class(model,self) def get_urls(self): """構造一層urls app01/book""" temp = [] for model, stark_class_obj in self._registry.items(): # print(model, 'stark_clas_obj', stark_class_obj) # 不同的model模型表 """ <class 'app01.models.UserInfo'> ----> <app01.starkadmin.UserConfig object at 0x00000072DDB65198> <class 'app01.models.Book'> ----> <stark.service.stark.ModelStark object at 0x00000072DDB65240> """ app_label = model._meta.app_label # app01 model_name = model._meta.model_name # book # temp.append(url(r'^%s/%s'%(app_label, model_name),([],None,None))) temp.append(url(r'^%s/%s/'%(app_label, model_name),stark_class_obj.urls2)) """ path('app01/userinfo/',UserConfig(Userinfo,site).urls2), path('app01/book/',ModelStark(Book,site).urls2), """ return temp @property def urls(self): # return [],None,None return self.get_urls(),None,None site = StarkSite() # 單例物件View Code
3、list_View.html
{% extends 'base.html' %} {% block title %} <title>list頁面</title> {% endblock %} {% block css %} <style type="text/css"> .active { color: red !important; } .filter a { text-decoration: none; color: grey; } </style> {% endblock %} {% block content %} <div class="col-md-9"> <a class="btn btn-primary" href="{{ add_url }}">新增資料</a> {% if show_list.config.search_fields %} <form action="" method="get"> <input type="text" class="form-control" style="width: 30%;display: inline-block;margin-top: 8px" name="q" value="{{ show_list.config.key_word }}"> <button class="btn btn-success">submit</button> </form> {% endif %} <form action="" method="post"> {% csrf_token %} <select name="action" class="form-control" style="display: inline-block;width: 200px;margin: 8px 8px 8px 0;height: 35px;vertical-align: -2px"> <option value="">-------</option> {% for item in show_list.get_action_list %} <option value="{{ item.name }}">{{ item.desc }}</option> {% endfor %} </select> <button type="submit" class="btn btn-primary">Go</button> <table class="table table-bordered table-striped"> <tr> {% for header in show_list.get_header %} <th>{{ header }}</th> {% endfor %} </tr> {% for data in show_list.get_body %} <tr> {% for item in data %} <td>{{ item }}</td> {% endfor %} </tr> {% endfor %} </table> </form> <nav> <ul class="pagination"> {{ show_list.pagination.page_html|safe }} </ul> </nav> </div> <div class="col-md-3"> <div class="filter"> {% for filter_field, linktags in show_list.get_filter_linktags.items %} <div class="well"> <p>{{ filter_field.upper }}</p> {% for link in linktags %} <p>{{ link|safe }}</p> {% endfor %} </div> {% endfor %} </div> </div> {% endblock %} {% block javascript %} <script type="text/javascript"> $('#choice').click(function () { if ($(this).prop('checked')) { //物件自身屬性中是否具有指定的屬性 $('.choice_item').prop("checked", true) } else { $('.choice_item').prop("checked", false) } }) </script> {% endblock %}View Code
4、add_view.html
{% extends 'base.html' %} {% block title %} <title>add頁面</title> {% endblock %} {% block css %} <style type="text/css"> input, select { display: block; width: 100%; height: 34px; padding: 6px 12px; font-size: 14px; line-height: 1.42857143; color: #555; background-color: #fff; background-image: none; border: 1px solid #ccc; border-radius: 4px; -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075); box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075); -webkit-transition: border-color ease-in-out .15s, -webkit-box-shadow ease-in-out .15s; -o-transition: border-color ease-in-out .15s, box-shadow ease-in-out .15s; transition: border-color ease-in-out .15s, box-shadow ease-in-out .15s; } .error { color: red; } </style> {% endblock %} {% block header %} <h3>add頁面</h3> {% endblock %} {% block content %} <div class="col-md-6 col-xs-8 col-md-offset-4"> {% include 'form.html' %} </div> {% endblock %} {% block javascript %} <script type="text/javascript"> //開啟open頁面 function pop(url) { window.open(url, '', 'width=600,height=400,left=100,right=100') } //open頁面操作完成,返回資料 function pop_response(pk,text,id) { //選擇哪一個select標籤 // option的文字值與value值 var $option =$('<option>'); //<option></option> $option.html(text); //<option>南京出版社</option> $option.val(pk); //<option val=111>南京出版社</option> $option.attr("selected","selected"); //<option val=111 selected>南京出版社</option> $('#'+id).append($option) } </script> {% endblock %}View Code
5、form.html
<form action="" method="post" novalidate> {% for field in form %} {% csrf_token %} <div class="form-group" style="position:relative;"> <label for="">{{ field.label }}</label> {{ field }} <span class="error pull-right">{{ field.errors.0 }}</span> {% if field.is_pop %} <a onclick="pop('{{ field.url }}')" href="" style="font-size: 25px;position: absolute;top: 25px;right: -25px"><span>+</span></a> {% endif %} </div> {% endfor %} <br> <button class="btn btn-success pull-right">提交</button> </form>View Code
6、pop_view.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</