时间:2020-12-25 12:43:29 | 栏目:Python代码 | 点击:次
我就废话不多说了,还是直接看代码吧!
#模板 class IndexForm(forms.Form): # 模板,用户提交的name和这里的变量名一定要是一致的.否则不能获取数据 user = forms.CharField(min_length=6, error_messages={'required': '用户名不能为空', 'min_length': '用户名长度不能小于6'}) email = forms.EmailField(error_messages={'required': '邮箱不能为空', 'invalid': '邮箱格式错误'}) """ 单选 favor = forms.ChoiceField( choices=[(1, '小虎'), (2, '小小虎'), (3, '小B虎')] ) """ # 多选 favor = forms.MultipleChoiceField( choices=[(1, '小虎'), (2, '小小虎'), (3, '小B虎')] ) pass #函数 def index(request): obj = IndexForm() return render(request, "index.html", {'obj': obj}) def edit_index(request): obj = IndexForm({'user': 'root', 'email': '123@qq.com', 'favor': [2,3]}) return render(request, "index.html", {'obj': obj}) #前端 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <p>{{ obj.user }}</p> <p>{{ obj.email }}</p> <p>{{ obj.favor }}</p> </body> </html>
补充知识:django使用模板实现下拉菜单,菜单内容读取后台动态填充,并动态设置默认值
看代码吧!
<select id="heard1" class="form-control" required="" data-parsley-id="6485" name="name"> {% for name in data_list %} <option id="name" value="{{ name }}" {% if name == role_name %} selected {% endif %}>{{ name }}</option> {% endfor %} </select>
这里面的重点是:
{% if name == role_name %} selected {% endif %}
这句话中得判断条件,name就是自己从data_list中遍历出来得那个name, role_name也是自己传过来得数据,这个数据是我自己定义的另一个库中的数据,因为两个库是关联的;
data = UserManage.objects.get(id=id) role_name = data.user_role.name query_name_list_set = RolesManage.objects.values("name") data_list = [] for name_dict in query_name_list_set: data_list.append(name_dict.get("name")) return render(request, "users_manage/edit.html", {"data": data, "data_list": data_list, "role_name": role_name})
贴上代码,为了防止自己忘记了好回过头来翻看