django之form表单select配合model的使用
程序员文章站
2022-04-25 15:21:38
...
forms.py文件
class HostForm(forms.Form):
hostname = forms.CharField(label=_('主机名'), max_length=128, widget=forms.TextInput(attrs={'class': 'form-control', "placeholder": "主机名", 'autofocus': ''}))
ip = forms.CharField(label=_('ip地址'), max_length=128, widget=forms.TextInput(attrs={'class': 'form-control', "placeholder": "ip地址"}))
remoteuser = forms.CharField(label=_('用户'), max_length=128, widget=forms.TextInput(attrs={'class': 'form-control', "placeholder": "用户", 'autofocus': ''}), initial="root")
password = forms.CharField(label=_('密码'), max_length=128, widget=forms.TextInput(attrs={'class': 'form-control', "placeholder": "密码", 'autofocus': ''}), required=False)
port = forms.CharField(label=_('端口'), max_length=128, widget=forms.TextInput(attrs={'class': 'form-control', "placeholder": "端口"}), initial=22)
private_key = forms.CharField(label=_('私钥'), max_length=2048, widget=forms.Textarea(attrs={'class': 'form-control', "placeholder": "私钥"}), required=False)
# platform = forms.CharField(label=_('平台'), max_length=2048, widget=forms.Select((), attrs={'class': 'form-control', "placeholder": "平台"}), required=False)
platform = forms.CharField(label=_('平台'), max_length=2048, widget=forms.Select(attrs={'class': 'form-control', "placeholder": "私钥"}))
def __init__(self, *args, **kwargs):
super(HostForm, self).__init__(*args, **kwargs)
self.fields["platform"].widget.choices = models.Platform.objects.all().values_list("id", "platform")
model.py文件
class Platform(models.Model):
id = models.AutoField(primary_key=True)
platform = models.CharField(max_length=128, default="内网")
view.py文件
@method_decorator(login_required(), name='dispatch')
class CreateHost(View):
template_name = "assets/create.html"
form = forms.HostForm()
def get(self, request, *args, **kwargs):
form = forms.HostForm()
hosts_list = []
return render(request, 'assets/create.html', locals())
# return super().get(request, *args, **kwargs)
def post(self, request, *args, **kwargs):
hostname = request.POST.get("hostname")
ip = request.POST.get("ip")
remoteuser = request.POST.get("remoteuser")
password = request.POST.get("password")
port = request.POST.get("port")
private_key = request.POST.get("private_key")
# 获取到id(主键)
platformid = request.POST.get("platform")
# 根据id获取对应的数据
platform = Platform.objects.filter(id=platformid)[0].platform
前端引用
<div class="form-group">
{{ form.platform.label }}
<!--指定 date标记-->
{{ form.platform }}```
效果图
上一篇: Django之Form表单
下一篇: Django框架实现用户登录验证