![](/img/trans.png)
[英]How to combine two nested tuples and use in Django's CharField choices?
[英]How to style a charfield which has choices in it django or which widget to use?
好的,所以我真正想做的是設置一個 charfield,它可以從我的 forms.py modelform class 中選擇。
我的models.py有這個代碼......
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
cat_choices = (
("Stationary","Stationary"),
("Electronics","Electronics"),
("Food","Food"),
)
class Product(models.Model):
name = models.CharField(max_length=100,null=True)
category = models.CharField(max_length=100, choices=cat_choices,null=True)
quantity = models.PositiveIntegerField(null=True)
class Meta:
verbose_name_plural = 'Product'
ordering = ['category']
我的 forms.py 有....
from django import forms
from .models import Product
class AddProduct(forms.ModelForm):
class Meta:
model = Product
fields = ['name','category','quantity']
def __init__(self, *args, **kwargs):
super(AddProduct,self).__init__(*args, **kwargs)
self.fields['name'].widget = forms.TextInput(attrs={'type':'text','id':'name','name':'name','class':'form-control','placeholder':'Product Name'})
# self.fields['category'].widget = forms.Select(attrs={'class':'form-select'})
所以我需要一個解決方案來解決我如何設置它的樣式或更合適地使用哪個小部件。 我已經嘗試過 Select 並且它不起作用。
您應該將 model 中的category
更改為IntegerField
:
cat_choices = (
(0, "Stationary"),
(1, "Electronics"),
(2, "Food"),
)
class Product(models.Model):
...
category = models.IntegerField(choices=cat_choices, null=True)
...
那么你可以使用forms.select
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.