django form表单select下拉菜单数据源实时更新(每次访问获取一次数据库内容)

重点是: Form类对象实例化的时候,在类里边__init()__函数中加入重新更新select数据源

from django.shortcuts import render,redirect
from app3 import models
from app3 import form
from django import forms
from django.forms import widgets

#静态字段,value_list获取列表[()]加元组返回值


class Fromdb(forms.Form):
    purpose = forms.CharField()
    user = forms.IntegerField(
        widget=widgets.Select()
        )
    #保证每次访问重新获取最新数据
    def __init__(self,*args,**kwargs):
        super(Fromdb,self).__init__(*args,**kwargs)
        self.fields["user"].widget.choices=models.Stu.objects.values_list("id", "name")

def formdb(request):
    stus = Fromdb()
    return render(request,"formdb.html",{"stus":stus})

 

你可能感兴趣的:(django)