Django模型表单字段具有基于条件的用户下拉列表

时间:2019-03-09 07:13:12

标签: python django django-models django-forms

在Django Modelform(Product_definition)中,我想要一个下拉列表(商人名称),该下拉列表仅在用户在“用户”表格中的名称为“商人”时显示给用户。 是否有可能基于此条件获取下拉列表的用户列表。请注意,由于连接模型不是必需的,因此我不需要将其作为外键。 这是包含名称的表格:

from django.contrib.auth.models import User

class UserProfileInfo(models.Model):
    user = models.OneToOneField(User,on_delete = models.CASCADE)

    #extra UserAttribute
    MERCHANT = 'MR'
    FABRIC = 'FR'
    WASHING = 'WS'
    PRINT = 'PR'
    PLANNER = 'PL'

    DESIGNATION_CHOICES =(
        (PLANNER,'Planner'),
        (MERCHANT,'Merchant'),
        (FABRIC,'Fabric'),
        (WASHING,'Washing'),
        (PRINT,'Printing'),

    )

    Designation =models.CharField(
        max_length = 20,
        choices = DESIGNATION_CHOICES,
        default= 'PLANNER'
    )
    def __str__(self):
        return self.user.username

这是带有“商家名称”的表格,我要在其中显示所有商家的名称。

class Product_definition(models.Model):

Order_number = models.CharField(max_length=25,unique = True, blank = True, null = True)
style_name = models.CharField(max_length=15, blank = True, null = True)
color = models.CharField(max_length=15, blank = True, null = True)
Order_qty = models.PositiveIntegerField()
SMV = models.FloatField()
MERCHANT = models.ForeignKey(UserProfileInfo,on_delete= models.CASCADE,default='Select')
def __str__(self):
    return self.Order_number

我现在已经创建了一个外键,但是我并不需要它,并且在下拉列表中仅列出了商家的名称。

1 个答案:

答案 0 :(得分:1)

我认为您可以使用ModelChoiceField来做到这一点:

class ProductForm(forms.ModelForm):  # please use CamelCase when defining Class Names
    MERCHANT = forms.ModelChoiceField(queryset=UserProfileInfo.objects.filter(Designation=UserProfileInfo.MARCHENT))  # Please use sname_case when naming attributes
    class Meta:
       model = Product_definition  # Please use CamelCase when defining model class name
       fields = '__all__'