我需要获取试图创建评论以存储在模型中的用户的 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.py
class 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)
江户川乱折腾
相关分类