我将销售订单添加到我的项目中,只有经过身份验证的用户才能使用他们的商品(例如联系人客户,商品等)创建销售订单,但是在UI中,它也向我显示了另一个用户选项。例如,我要创建销售订单,并且我有1个客户联系人和1个项目。在模板中,而不是显示1个客户联系人和1个项目,它也显示了许多其他用户的东西。
models.py 在这里
class SalesOrder(TimeModel):
customer = models.ForeignKey(ClientContact, on_delete=models.CASCADE)
so_date = models.DateField(default=datetime.date.today)
so_items = models.ForeignKey(Item, on_delete=models.CASCADE)
author = models.ForeignKey('users.CustomUser', on_delete=models.CASCADE)
class Meta:
unique_together = ('so_items', 'author')
我添加了unique_together,但没有帮助。对于我正在使用CBV的视图
views.py
class Sales(LoginRequiredMixin, CreateView):
model = SalesOrder
template_name = 'sales/sales_order.html'
fields = ['customer', 'so_date', 'so_items',]
def get_queryset(self):
return super(Sales, self).get_queryset().filter(author=self.request.user)
def form_valid(self, form):
form.instance.author = self.request.user
return super().form_valid(form)
def test_func(self):
so_order = self.get_object()
if self.request.user == so_order.author:
return True
return False
我该如何解决这个问题?有帮助吗?
答案 0 :(得分:0)
答案是通过在视图中添加get_context_data()
def get_context_data(self, **kwargs):
context = super(Sales, self).get_context_data(**kwargs)
context['form'].fields['customer'].queryset = ClientContact.objects.filter(author=self.request.user)
context['form'].fields['so_items'].queryset = Item.objects.filter(author=self.request.user)
return context