Django:关系" "列"user_id"中的完整性错误空值违反了非空约束



我正试图将数据保存到数据库中,但遇到了此错误。我想我理解这个错误,但不知道如何纠正。基本上,我试图发布一个产品的评论,当试图保存到数据库时,它似乎不知道哪个用户正在保存这个评论?无论出于何种原因,我认为user_id为null。但老实说,我可能错了,我有点陷入了困境。我觉得简单的解决方案就是在我的用户模型中设置null=true,但我不想这样做。非常感谢任何帮助

型号:

class Review(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
product = models.ForeignKey(Product, on_delete=models.SET_NULL, null=True)
rating = models.DecimalField(max_digits=2, decimal_places=1, validators=[MinValueValidator(Decimal('0.1'))])
comment = models.TextField(validators=[MinLengthValidator(10)])
date = models.DateField(auto_now=True)
def __str__(self):
return str(self.user) 
class Product(models.Model):
name = models.CharField(max_length=120)
shortened_name = models.CharField(max_length=50)
date_of_creation = models.CharField(max_length=20, null=True)
history = models.CharField(max_length=255)
price = models.DecimalField(max_digits=9, decimal_places=2)
discount_price = models.FloatField(blank=True, null=True)
style = models.CharField(max_length=50)
artist = models.ForeignKey(Artist, on_delete=models.SET_NULL, null=True)
image = models.ImageField(upload_to='images', null=True)
slug = models.SlugField()


def __str__(self):
return self.name

def get_absolute_url(self):
return reverse('product', args=[self.slug])
def save(self, *args, **kwargs):
self.slug = slugify(self.shortened_name)
super().save(*args, **kwargs)
def get_add_to_cart_url(self):
return reverse('add_to_cart', kwargs={
'slug': self.slug
})
def get_remove_from_cart_url(self):
return reverse('remove_from_cart', kwargs={
'slug': self.slug
})

形式:

class ReviewForm(forms.ModelForm):
class Meta:
model = Review
exclude = ['user', 'date']
widgets = {
'product': forms.Select(attrs={
'class': 'form-control'
}),
'rating': forms.NumberInput(attrs={
'class': 'form-control',
'placeholder': '5.0..'
}),
'comment': forms.Textarea(attrs={
'class': 'form-control'
})
}

视图:

class MyOrdersView(LoginRequiredMixin, View):
def get(self, request, *args, **kwargs):
try:
order = ShoppingCartOrder.objects.filter(user=self.request.user, ordered=True)
form = ReviewForm()
context = {
'object': order,
'form': form
}
return render(request, 'my_site/my_orders.html', context)
except ObjectDoesNotExist:
messages.warning(request, 'You do not have any orders')
return redirect('all_products')
def post (self, request, *args, **kwargs):
form = ReviewForm(request.POST)
if form.is_valid():
test = form.save()
return redirect('starting_page')
return redirect('my_orders')

您使用的ReviewForm不包括user字段,所以我认为您只是忘记保存user字段。尝试更改:

test = form.save()

进入:

test = form.save(commit=False)
test.user = request.user
test.save()

相关内容

  • 没有找到相关文章

最新更新