Python 如何设置在django或使用哪个小部件中有选择的charfield的样式?
好的,我真正想做的是设计一个charfield,它可以从forms.py modelform类中进行选择 My models.py有这段代码它Python 如何设置在django或使用哪个小部件中有选择的charfield的样式?,python,django,django-models,django-forms,django-templates,Python,Django,Django Models,Django Forms,Django Templates,好的,我真正想做的是设计一个charfield,它可以从forms.py modelform类中进行选择 My models.py有这段代码它 from django.db import models from django.contrib.auth.models import User # Create your models here. cat_choices = ( ("Stationary","Stationary"), (&q
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'})
因此,我需要一个解决方案,我可以如何风格它或更适当地使用哪个小部件。我已尝试选择,但它不起作用。您应该将模型中的
类别更改为整型字段
:
cat_choices = (
(0, "Stationary"),
(1, "Electronics"),
(2, "Food"),
)
class Product(models.Model):
...
category = models.IntegerField(choices=cat_choices, null=True)
...
然后您可以使用表单。选择