Django:如何在管理员表单

时间:2017-09-14 10:45:04

标签: django django-admin

以下是我的应用的模型:

class Store(models.Model):
    store_owner = models.ForeignKey(User, null=False, verbose_name='User')
    store_name = models.CharField(max_length=200, null=False, 
                                 verbose_name='Store name')
    store_address_line_1 = models.CharField(max_length=200, null=False, 
                                           verbose_name='Address line 1')
    store_address_line_2 = models.CharField(max_length=200, null=False, 
                                            verbose_name='Address line 2')
    store_city = models.CharField(max_length=200, null=False, 
                                  verbose_name='City')
    store_state = models.CharField(max_length=200, null=False, 
                                   verbose_name='State')
    store_zip_code = models.CharField(max_length=200, null=False, 
                                      verbose_name='Zip/Pin Code')
    store_country = models.CharField(max_length=200, null=False, 
                                     verbose_name='Country')
    store_phone = models.CharField(max_length=12, verbose_name='Phone')
    store_email = models.EmailField(verbose_name='Email')
    store_website = models.URLField(verbose_name='Website')


class StoreDepartment(models.Model):
    store = models.ForeignKey(Store, verbose_name='Store')
    department_name = models.CharField(max_length=200, null=False, 
                                      verbose_name='Department name')
    department_description = models.TextField(max_length=250, null=False, 
                                              verbose_name='Description')

+++++++++

我只使用django framwork提供的dfault Admin。

我有2个用户,对于我已创建商店的两个用户。 但是当我尝试创建StoreDepartment时,我会在为" Store"创建的选择框中看到所有商店的列表。 StoreDepartment模型中的外键字段。

如何自定义默认表单,以便用户只能在选择框中看到由他们创建的商店。

1 个答案:

答案 0 :(得分:0)

我在模型管理员中使用了以下 formfield_for_foreignkey ,现在它正在为我工​​作。用户只能看到他拥有的商店。

class StoreDepartmentAdmin(admin.ModelAdmin):
    list_display = ['department_name', 'store']
    ordering = ['id']

    def formfield_for_foreignkey(self, db_field, request, **kwargs):
        if db_field.name == "store":
            kwargs["queryset"] =Store.objects.filter(store_owner=request.user)

    return super(StoreDepartmentAdmin,self).formfield_for_foreignkey(db_field, request, **kwargs)