是否可以排除用户已经选择并存储在表中的选项?
这是来自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 排除。但是看起来很俗气。
非常感谢您的想法!
FFIVE
相关分类