如何在Django应用的“评论”视图中解决此错误? [英] How do i fix this error in my Comments view in my Django app?
问题描述
我正尝试在Django中开发一个应用。目前,我正在尝试为用户创建评论部分,以便用户使用表单编写和提交评论。我制作了一个模板,用于显示电影的信息以及用户可以在电影上发表评论的形式。
I'm trying to develop an app in Django. At the moment I'm trying to create a comment section for the users to write and submit comments by using a form. I made a template which shows the info of a movie as well as a form through which users can write comments on the film.
问题是当我写评论时并尝试提交,显示此错误:
The problem is that when I write the comment and try to submit it this error shows up :
/ myapp2 / 2 / 中的IntegrityError
没有NULL约束失败:myapp2_comentario.pelicula_id
IntegrityError at /myapp2/2/ NOT NULL constraint failed: myapp2_comentario.pelicula_id
我的Views.py
my Views.py
def detallesPelicula(request, pelicula_id):
peliculas = get_list_or_404(Pelicula.objects.order_by('titulo'))
pelicula = get_object_or_404(Pelicula, pk=pelicula_id)
actor = get_list_or_404(Actor.objects)
comentarios = Comentario.objects.filter(pelicula=pelicula).order_by('fecha')
if request.method =='POST':
comment_form = CommentForm(data=request.POST)
if comment_form.is_valid():
comment_form.save()
texto = request.POST.get('texto')
comentario = Comentario.objects.create(
usuario=request.user, pelicula=pelicula, texto=texto)
comentario.save()
return HttpResponseRedirect(pelicula.get_absolute_url())
else:
comment_form= CommentForm()
context = {'pelicula': pelicula, 'peliculas': peliculas,
'comentarios':comentarios,'comment_form':comment_form}
return render(request, 'detallesPelicula.html', context)
我的表单.py
class CommentForm(forms.ModelForm):
class Meta:
model = Comentario
fields = ['texto']
my Models.py
my Models.py
class Comentario(models.Model):
usuario = models.ForeignKey(Usuario, on_delete=models.CASCADE)
pelicula =models.ForeignKey(Pelicula, on_delete=models.CASCADE)
fecha = models.DateTimeField(auto_now_add=True,null=True,blank=True)
texto = models.TextField(max_length=2000, default="")
注意:用户是从Django身份验证系统中获取的。
Note: the users are taken from the Django authentification system.
非常感谢帮助。
推荐答案
# remove this line to fix the problem
comentario.save()
上面的代码行没有设置 pelicula
字段。您的models.py将其定义为必填字段,这就是为什么您收到IntegrityError的原因。您可以删除代码,因为
代码的前行
The above line of code does not have pelicula
field set. Your models.py defines it as a required field, that is why you are getting IntegrityError. You can delete the code because
the preceding line of code
# this should be valid because it contains all the required fields
comentario =
Comentario.objects.create(usuario=request.user, pelicula=pelicula, texto=texto)
已经创建了注释。
这篇关于如何在Django应用的“评论”视图中解决此错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!