一、编写model模型
from django.db import models
class TBest(models.Model):
name = models.CharField(max_length=128)
def __init__(self, *args, **kwargs):
super(TBest, self).__init__(*args, **kwargs)
二、 编写forms表单
from login import models
from django.forms import ModelForm
from django import forms
class TBest(ModelForm):
class Meta:
model = models.TBest
fields = "__all__"
labels = {
'name': "名称",
}
widgets = {
'name': forms.Select(attrs={
"class": "form-control select2",
"multiple": "multiple",
"data-placeholder": "Select a State",
"style": "width: 100%;",
}),
}
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields["name"].widget.choices=models.TBest.objects.all().values_list("id", "name")
三、编写view视图层
from .forms import TBest
from django.views import View
from django.shortcuts import render, redirect
class TestDal(View):
def get(self, request, *args, **kwargs):
form = TBest()
return render(request, 'login/test.html', locals())
def post(self, request, *args, **kwargs):
return redirect("login:TestDal")
四、编写urls路由
from login import views
from django.urls import path
from django.urls import include
app_name = 'login'
urlpatterns = [
path('TestDal/', views.TestDal.as_view(), name="TestDal"),
]
五、添加数据
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/c7b5daad24a1b32e95bc4cbefa813f72.png)
六、编写静态页面
拷贝css、js插件到指定目录
<link rel="stylesheet" href="{% static 'AdminLTE/plugins/selec2/css/select2.min.css' %}">
<link rel="stylesheet" href="{% static 'AdminLTE/plugins/select2-bootstrap4-theme/select2-bootstrap4.min.css' %}">
<div class="col-md-12">
<form action="{% url 'login:TestDal' %}" method="post">{% csrf_token %}
<div class="form-group">
{{ form.name.label }} {{ form.name }}
</div>
<button type="submit" class="btn btn-info">Sign in</button>
<button type="submit" class="btn btn-default float-right">Cancel</button>
</form>
</div>
<script src="{% static 'AdminLTE/plugins/select2/js/select2.full.min.js' %}"></script>
<script>
$(function () {
$('.select2').select2()
$('.select2bs4').select2({
theme: 'bootstrap4'
})
})
</script>
七、效果图
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/452534d373acb4d54519b3d486931d30.png)
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/3beb0787e755658aaaeb6aa04c1f002a.png)