在 models.py 文件里,创建各个数据表 models
# 在 models.py 文件里
class AssetSet(models.Model):
"""
资产表
"""
name = models.CharField(verbose_name="名称", max_length=32)
price = models.IntegerField(verbose_name="价格")
# 只适用于固定的选择
category_choices = ((1, '文具类'), (2, '3C类'), (3, '房产类'))
category = models.SmallIntegerField(verbose_name="资产类型", choices=category_choices)
# 外键 depart_id
depart = models.ForeignKey(verbose_name="所属部门", to="Department", to_field="id", on_delete=models.CASCADE)
在 views.py 文件里
# 在 views.py 文件里
class AssetModelForm(forms.ModelForm):
#newField = forms.CharField()
class Meta:
model = models.AssetSet
fields = ['name', 'price', 'category', 'depart']
#fields = "__all__"
"""
# 单一的给某个field添加样式
widgets = {
'category': forms.Select(attrs={'style': "width: 300px;"})
}
"""
# 给所有的 field 提供样式
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
for name, field in self.fields.items():
if name == "price":
continue
field.widget.attrs['style'] = "width: 100px"
def asset_add(request):
"""
# 获取所有类型
cat_list = models.AssetSet.category_choices
dp_list = models.Department.objects.all()
form = AssetForm()
"""
cat_list = models.AssetSet.category_choices
dp_list = models.Department.objects.all()
form = AssetModelForm()
return render(request, 'asset_add.html', {'cat_list': cat_list, 'dp_list': dp_list, 'form': form})
显示到前端,可以这么操作
{% for field in form %}
<div>
<label>{{ field.label }}</label>
<div>
{{ field }}
</div>
</div>
{% endfor %}
最终的页面显示如下:
点个赞呗~
标签:category,__,verbose,models,list,Django,field,name From: https://blog.csdn.net/BSCHN123/article/details/139505384