class IdcInfo(models.Model):
virtual_choice = (
(0, '否'),
(1, '是'),
)
idc_name = models.CharField(max_length=50, verbose_name=('机房名字'), default=u"", null=True, blank=True)
is_virtual = models.IntegerField(verbose_name=("是否云主机"), choices=virtual_choice, default=0)
class IdcAddView(View):
"""
添加 IDC 信息
"""
def get(self, request):
if request.user.is_superuser:
is_virtual_list = IdcInfo.objects.all()
print is_virtual_list
return render(request, "assets/idcadd.html", {is_virtual_list: 'is_virtual_list'})
else:
return HttpResponse("用户无权限")
前端 html 内容
<select class="form-control m-b" name="is_virtual">
{% for is_virtual_i in is_virtual_list %}
<option>{{ is_virtual_i.get_is_virtual_choices_displa }}</option>
{% endfor %}
<option>option 2</option>
</select>
1
versionzhang 2018-08-27 19:17:22 +08:00 via Android
看下 django-crispy-forms 库
|
2
chengxiao 2018-08-27 19:33:58 +08:00
is_virtual_i.is_virtual.get_is_virtual_display
还是 is_virtual_i.get_is_virtual_display 来着,忘了是哪个了 可以试试 就记得是 obj.get_字段_display |
4
chengxiao 2018-08-27 21:54:52 +08:00
|
5
Faiz555 2018-08-27 22:08:52 +08:00
首先,我推荐视图直接使用 ListView,简单易用
```python class IdcAddView(ListView): """ 添加 IDC 信息 """ model = IdcInfo context_object_name = 'is_virtual_list' template_name = 'lib/idcadd.html' def get_queryset(self): return IdcInfo.objects.all() ``` 然后,模板部分书写有误,应为: ```html <select class="form-control m-b" name="is_virtual"> {% for is_virtual_i in is_virtual_list %} <option>{{ is_virtual_i.get_is_virtual_display }}</option> {% endfor %} <option>option 2</option> </select> ``` 效果图: ![option]( https://a.photo/images/2018/08/27/-2018-08-27-22.07.05.png) |
8
fanne OP @Faiz555 #5 我继承的是这个 from django.views.generic.base import View
后面还有一个 def post (self, request): pass 能否基于我原本的,帮我定位问题所在么 |
9
Faiz555 2018-08-27 23:02:40 +08:00
使用内建视图导入这个就行了 `from django.views.generic import ListView`
视图的 context 写错了,是`return render(request, "lib/idcadd.html", {'is_virtual_list': is_virtual_list})` context 类似于字典,前面是 key,后面才是 value |
11
Faiz555 2018-08-27 23:09:15 +08:00
@fanne <option>{{ is_virtual_i.get_is_virtual_display }}</option> 这里你改了吗
你原来模板里写的含有 choices,这是多余的 |
12
fanne OP @Faiz555 #11 改了的,方便加 Q 或者邮箱沟通么,从下午调到现在了
<option>{{ is_virtual_i.get_is_virtual_display }}</option> return render(request, "assets/idcadd.html", {'is_virtual_list': is_virtual_list}) 这两个地方都改了 |
14
fanne OP @Faiz555 #11
In [4]: from assets.models import IdcInfo In [5]: IdcInfo.objects.all()[0].is_virtual --------------------------------------------------------------------------- IndexError Traceback (most recent call last) <ipython-input-5-73f9e2b4c7bb> in <module>() ----> 1 IdcInfo.objects.all()[0].is_virtual /Users/apple/OneDrive/Code_7zGame/Envs/tdops/lib/python2.7/site-packages/django/db/models/query.pyc in __getitem__(self, k) 287 qs = self._clone() 288 qs.query.set_limits(k, k + 1) --> 289 return list(qs)[0] 290 291 def __and__(self, other): IndexError: list index out of range |
15
Faiz555 2018-08-28 09:46:45 +08:00
我能查到,你确认数据是存在的?
|