【问题标题】:Django model form field to have a user dropdown list based on a conditionDjango模型表单字段具有基于条件的用户下拉列表
【发布时间】:2019-03-09 07:13:12
【问题描述】:

在 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

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

【问题讨论】:

    标签: python django django-models django-forms


    【解决方案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__'
    

    【讨论】:

    • 在尝试迁移时,我得到“invalid literal for int () with base 10”。在添加此表单之前,我能够迁移。我也将所有整数字段替换为 FloatField 但它没有解决错误
    猜你喜欢
    • 2013-01-07
    • 2013-04-09
    • 1970-01-01
    • 1970-01-01
    • 2020-12-10
    • 2011-03-12
    • 2012-02-10
    • 2011-06-11
    • 1970-01-01
    相关资源
    最近更新 更多