How do i fix this error in my Comments view in my Django app?

假如想象 提交于 2019-12-24 00:45:03

问题


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 :

IntegrityError at /myapp2/2/ NOT NULL constraint failed: myapp2_comentario.pelicula_id

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)

my Forms.py

class CommentForm(forms.ModelForm):
    class Meta:
        model = Comentario
        fields = ['texto']

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="")

Note: the users are taken from the Django authentification system.

Help is very much appreciated.


回答1:


# remove this line to fix the problem
comentario.save() 

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) 

has already created the comment.




回答2:


comment_form.save()

will try to create a new Comment, but the form doesn't have usuario or pelicula set, hence the error. It would be best to include pelicula in the form as a hidden field. But for User, you can do this:

    if comment_form.is_valid():
        comentario = comment_form.save(commit=False)
        comentario.usuario = self.request.user
        comentario.save()

If your code reached Comentario.objects.create that would create a second Comment, so if the first works that is not needed.




回答3:


in line of code CommentForm(data=request.POST) you can try CommentForm(request.POST or None). Then in the line comment_form.save() replace using instance new object comentario comentario = comment_form.save(commit=False)

Please following the completed of code

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')

    # initialize form to generate form template and validation form on view
    # request.POST or None (request.POST for POST method and None for GET method)
    comment_form = CommentForm(request.POST or None)

    if request.method == 'POST':
        if comment_form.is_valid():

            # instance new object comentario
            comentario = comment_form.save(commit=False)

            # to assign usuario attribute Comentario object from current user session
            comentario.usuario = request.user
            # assign pelicula attribute
            comentario.pelicula = comentario
            # commit comentario object to database
            comentario.save()

            return HttpResponseRedirect(pelicula.get_absolute_url())

    context = {'pelicula': pelicula, 'peliculas': peliculas, 
               'comentarios':comentarios,'comment_form':comment_form}

    return render(request, 'detallesPelicula.html', context)


来源:https://stackoverflow.com/questions/59338581/how-do-i-fix-this-error-in-my-comments-view-in-my-django-app

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!