我需要获取试图创建评论以存储在模型中的用户的 profile_id。我可以获取用户的属性,因为它们内置在 django 中,但是当我尝试使用下面的内容来获取 profile_id 时,我得到“prof is not defined”错误。views.py class ReviewCreateView(LoginRequiredMixin, CreateView): model = Review fields = ['rating', 'reviewtext'] def get_context_data(self, **kwargs): context = super(ReviewCreateView, self).get_context_data(**kwargs) context['prof'] = Profile.objects.values_list('id', flat=True).filter(user_id=self.request.user.id) return context def form_valid(self, form): form.instance.product = self.request.GET.get('pk') form.instance.author = self.request.user form.instance.profile = prof return super().form_valid(form)models.pyclass Profile(models.Model): user = models.OneToOneField(User, on_delete = models.CASCADE)class Review(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) profile = models.ForeignKey(Profile, on_delete=models.CASCADE) author = models.ForeignKey(User, on_delete=models.CASCADE) rating = models.PositiveSmallIntegerField(default=1, validators = [MinValueValidator(1), MaxValueValidator(5)]) reviewtext = models.TextField()class Product(models.Model): name = models.CharField(max_length=100)
1 回答
江户川乱折腾
TA贡献1851条经验 获得超5个赞
配置文件通过外键链接到用户,所以我可以写下面的行,product_id 也得到一个空约束,直到我添加了 self.kwargs 行。
def form_valid(self, form, **kwargs): form.instance.product_id = self.kwargs['pk'] form.instance.author = self.request.user form.instance.profile = self.request.user.profile return super().form_valid(form)
添加回答
举报
0/150
提交
取消