繁体   English   中英

如何设置一个有选择的字符域 django 或使用哪个小部件?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM