Django从choicefields中删除条目

时间:2019-05-19 19:19:51

标签: django forms django-models

我的下拉菜单处于模型状态: models.py

class Item(models.Model):
    DRAFT = "D"
    PUBLISHED = "P"
    CLOSED = "C"
    STATUS = (
        (DRAFT, _("Draft")),
        (PUBLISHED, _("Published")),
        (CLOSED, _("Closed")),
    )
    user = models.ForeignKey(
        settings.AUTH_USER_MODEL, null=True, related_name="articleauthor",
        on_delete=models.SET_NULL)
   ...
    status = models.CharField(max_length=1, choices=STATUS, default=DRAFT)
   ...

forms.py

class ItemForm(forms.ModelForm):
    #status = forms.CharField(widget=forms.HiddenInput())
    edited = forms.BooleanField(widget=forms.HiddenInput(), required=False, initial=False)
    content = MarkdownxFormField()
    class Meta:
        model = Item
        fields = ["title", "content", "image", "price", "currency", "status", "edited"]

但是现在我要通过创建新项来删除已关闭的条目。

views.py

class CreateItemView(LoginRequiredMixin, PermissionRequiredMixin, CreateView):
    """Basic CreateView implementation to create new articles."""
    permission_required = 'is_staff'
    model = Item
    message = _("Your article has been created.")
    form_class = ItemForm
    template_name = 'item_create.html'

    def form_valid(self, form):
        form.instance.user = self.request.user
        return super().form_valid(form)

    def get_success_url(self):
        messages.success(self.request, self.message)
        return reverse('offers:list')
    '''
    def get_queryset(self):
        form = self.form = self.form_class(self.request.GET)
        if self.request.user.is_authenticated():
            form.fields['status'].choices.pop("C")
            form.fields['status'].widget.choices.pop("C")
    '''

您将如何专门为一个视图隐藏“关闭”?

1 个答案:

答案 0 :(得分:1)

指定可用选项

STATUS_OPTIONS_NO_CLOSED = (
        (DRAFT, _("Draft")),
        (PUBLISHED, _("Published")),
    )

然后将其添加到表单中

status = forms.CharField(widget=forms.Select(choices=STATUS_OPTIONS_NO_CLOSED))