1 回答
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
添加回答
举报