在选择中排除用户已经选择的选项

是否可以排除用户已经选择并存储在表中的选项?


这是来自models.py的表格


class Fruit(models.Model):

name = models.CharField(max_length=250, unique=True, blank=False, null=False)

sort= models.ForeignKey('FruitSort', on_delete=models.SET_NULL, null=True, blank=False)


def __str__(self):

    return '%s (%s)' % (self.name, self.sort.name)


class UserFruit(models.Model):

    Comment = models.CharField(max_length=55)

    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)

    fruit = models.ForeignKey('Fruit', on_delete=models.CASCADE)


    class Meta:

        unique_together = (("user", "fruit",),)

这是生成我的表单的 forms.py。


class UserFruit(forms.ModelForm):


class Meta:

    model = UserFruit

    fields = ('comment', 'fruit')


def __init__(self, *args, **kwargs):

    super(UserFruit, self).__init__(*args, **kwargs)

    for visible in self.visible_fields():

        visible.field.widget.attrs['class'] = 'form-control form-style-alt'

        self.fields['comment'].widget.attrs['placeholder'] = 'comment'

        self.fields['fruit'].empty_label = 'Please, choose fruit'

现在views.py


class Fruit(generic.CreateView):

    form_class = UserFruit

    template_name = 'fruit.html'


    def get(self, request, *args, **kwargs):

        form = self.form_class(instance=UserFruit.objects.filter(user=request.user).first())

        fruit = UserFruit.objects.filter(user=request.user)

        return render(request, self.template_name, {'form': form, 'fruit': fruit})


    def post(self, request, *args, **kwargs):

        form = self.form_class(request.POST)

        if form.is_valid():

            post = form.save(commit=False)

            post.user = request.user

            post.save()

        return redirect('fruit')

最后是模板。

我想排除或禁用用户已经添加的水果。我似乎没有找到一个干燥和顺利的解决方案。我可以从数据库中循环并通过 javascript 排除。但是看起来很俗气。


非常感谢您的想法!


aluckdog
浏览 58回答 1
1回答

FFIVE

是的。例如,您可以将user参数传递给表单,并作为Fruit尚未选择的查询集选择,例如:class UserFruitForm(forms.ModelForm):    class Meta:        model = UserFruit        fields = ('comment', 'fruit')    def __init__(self, user, *args, **kwargs):        super(UserFruit, self).__init__(*args, **kwargs)        for visible in self.visible_fields():            visible.field.widget.attrs['class'] = 'form-control form-style-alt'        self.fields['comment'].widget.attrs['placeholder'] = 'comment'        self.fields['fruit'].empty_label = 'Please, choose fruit'        self.fields['fruit'].queryset = Fruit.objects.exclude(            userfruit__user=user        )但是,您在CreateView. 您可以简单地让 theCreateView完成几乎所有的工作:from django.urls import reverse_lazyclass Fruit(generic.CreateView):    form_class = UserFruitForm    template_name = 'fruit.html'    success_url = reverse_lazy('fuit')    def get_form_kwargs(self):        kwargs = super().get_form_kwargs()        kwargs.update(user=self.request.user)        return kwargs    def get_context_data(self, *args, **kwargs):        context = super().get_context_data(*args, **kwargs)        context.update(fruit=UserFruit.objects.filter(user=self.request.user))        return context    def form_valid(self, form):        form.instance.user = self.request.user        super().form_valid(form)请将表格重命名为UserFruitForm. 现在,您在模型和表单之间引入了名称冲突。通过重命名它,您所指的内容就很清楚了。UserFruitUserFruit
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python