我需要获取正在尝试创建要存储在模型中的评论的用户的profile_id。我可以获取django中内置的User属性,但是当我尝试使用以下内容获取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)
答案 0 :(得分:0)
个人资料通过外键链接到User,因此我可以在下面写这行,在我添加self.kwargs行之前,product_id也受到了空约束。
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)