为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

aluckdog 2022-07-26 17:08:57
是否可以排除用户已经选择并存储在表中的选项?这是来自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.pyclass 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 排除。但是看起来很俗气。非常感谢您的想法!
查看完整描述

1 回答

?
FFIVE

TA贡献1797条经验 获得超6个赞

是的。例如,您可以将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_lazy


class 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


查看完整回答
反对 回复 2022-07-26
  • 1 回答
  • 0 关注
  • 57 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信