从管理面板的选择字段中删除选择的选项

时间:2019-07-18 00:26:47

标签: django django-2.1

如果要选择一次,我想减少管理面板中的选择选项。

admin.py

    DateTimeFormatter customFormatter1 = DateTimeFormatter.ofPattern("MM/dd/yy");
    String parseEndDate = LocalDate.now(ZoneId.of(zoneID_EST)).format(customFormatter1);
    String parseStartDate = LocalDate.now(ZoneId.of(zoneID_EST)).minusDays(100).format(customFormatter1);

model.py

class MyModelForm(forms.ModelForm):
    LOC = [('op1', 'op1'), ('op2', 'op2'),...]

    location = forms.ChoiceField(choices=LOC)


class DataModelAdmin(admin.ModelAdmin):
    form = MyModelForm
    list_display = ('location',)
    search_fields = ['location']

    def get_ordering(self, request):
        return ['location']


admin.site.register(DataModel, DataModelAdmin)

我正在尝试这样做,但是它在重新启动服务器时删除了选定的选项

2 个答案:

答案 0 :(得分:0)

如果我正确地解释了您的问题,那么您想从字段选择中删除对象的位置...

class MyModelForm(forms.ModelForm):
    LOC = [('op1', 'op1'), ('op2', 'op2')]

    location = forms.ChoiceField()

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        if self.instance:
            self.fields['location'].choices = [
                choice for choice in self.LOC
                if choice[0] != self.instance.location
            ]
        else:
            self.fields['location'].choices = self.LOC

实际上是二读,也许您正在寻找filter

from django.contrib.admin import SimpleListFilter

class LocationFilter(SimpleListFilter):
    title = 'location'
    parameter_name = 'location'

    def lookups(self, request, model_admin):
        locations = DataModel.objects.values_list('location', flat=True)
        return locations

    def queryset(self, request, queryset):
        if self.value():
            return queryset.filter(location=self.value())

然后将list_filter = (LocationFilter,)添加到您的管理类中。

答案 1 :(得分:0)

通过将 init 添加到MyModelForm类中,我可以删除选择字段中的选项

def __init__(self, *args, **kwargs):
    super(MyModelForm, self).__init__(*args, **kwargs)
    item = [i.location for i in DataModel.objects.all()]
    if self.instance.id:
        item.remove(self.instance.location)
    self.fields['location'].choices = [(i, j) for i, j in self.LOC if i not in item]