TypeError at / cannot unpack non-iterable NoneType object (Django)

I'm trying to set up a system on my Django project where users can comment on individual posts on the main (index) page. However, I'm having an issue when it comes to trying to make it so the comment is automatically connected to the post.

This is the code I tried in views.py:

from django.core import paginator
from django.shortcuts import render, redirect, get_object_or_404
from django.http import HttpResponse
from .models import *
from django.views.generic import ListView, CreateView, UpdateView
from django.views.generic.detail import DetailView
from .forms import *
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth import login
from django.core.paginator import Paginator
from django.views import View
import random

def index(request, pk=None, *args, **kwargs):
    postdata = Post_Data.objects.all()
    profiledata = ProfileData.objects.all()
    likedata = Like.objects.all()
    dislikedata = Dislike.objects.all()
    comment = PostComment.objects.all()
    postid = Post_Data.objects.get(pk)   


    # Initialize the comment form
    if request.method == 'POST':
        comment_form = PostCommentForm(request.POST)
        if comment_form.is_valid():
            post = comment_form.save(commit=False)
            post.user = request.user
            post.save()
            return redirect('/')
    else:
        comment_form = PostCommentForm()  # Create an empty form

    # Pass the comment form to the template context
    return render(request, 'index.html', {
        'title': 'RoamTrip',
        'postdata': postdata,
        'profiledata': profiledata,
        'likedata': likedata,
        'dislikedata': dislikedata,
        'comment': comment,
        'comment_form': comment_form  # Make sure this is included
    })

models.py:

from django.contrib import admin
from django.db import models
from django.urls import reverse
from django.contrib.auth.models import User
from django.contrib.auth import get_user_model
from django.conf import settings
from .validators import validate_file_extension

# Create your models here.

class Post_Data (models.Model):
    user = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.CASCADE,  # Set the appropriate behavior here
        null=True
    )
    time_data = models.DateTimeField(help_text='Enter Time of Upload Here:', auto_now_add=True)
    text_data = models.TextField(help_text='Type Here:')
    image_data = models.ImageField(upload_to="website/media/", null=True, blank=True, help_text='Upload Image:')
    video_data = models.FileField(null=True, upload_to="website/media/", blank=True, validators=[validate_file_extension])
    public_data = models.BooleanField(help_text='Public?', null=True)
    approval = models.BooleanField(help_text='Is this post approved?', default=True)

class PostComment(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    post = models.ForeignKey(Post_Data, on_delete=models.CASCADE, related_name='post_comment_id')
    post_comment = models.CharField(max_length=500)
    timestamp = models.DateTimeField(auto_now_add=True)
    
    def __str__(self):
        return f"Comment by {self.user} on {self.post}"

urls.py:

urlpatterns = [
    path('', views.index, name='RoamTrip'),
]

urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

I got this error as a result:

TypeError: cannot unpack non-iterable NoneType object

Here's the faulty line:

postid = Post_Data.objects.get(pk)

.get() takes keyword arguments or Q objects. I guess you want to filter by PK, so the line should be:

postid = Post_Data.objects.get(pk=pk)
def index(request, pk=None, *args, **kwargs):
    postdata = Post_Data.objects.all()
    profiledata = ProfileData.objects.all()
    likedata = Like.objects.all()
    dislikedata = Dislike.objects.all()
    comment = PostComment.objects.all()

    if pk:
        post = get_object_or_404(Post_Data, pk=pk)
    else:
        post = None  

    if request.method == 'POST':
        comment_form = PostCommentForm(request.POST)
        if comment_form.is_valid():
            comment = comment_form.save(commit=False)
            comment.user = request.user
            if post:
                comment.post = post  
            comment.save()
            return redirect('/')
    else:
        comment_form = PostCommentForm()

    return render(request, 'index.html', {
        'title': 'RoamTrip',
        'postdata': postdata,
        'profiledata': profiledata,
        'likedata': likedata,
        'dislikedata': dislikedata,
        'comment': comment,
        'comment_form': comment_form,
        'target_post': post  
    }) 

can u try this? I'm waiting for your feedback

I think there are a many problems.

As @Michal's answer, this part should be revised as below.

postid = Post_Data.objects.get(pk=pk)

urls.py also has a problem.

The index function currently has a parameter called pk. If you look at this part, you are expected to try to use dynamic url for that logic.

def index(request, pk=None, *args, **kwargs):
    ...

That is why the path calling the index function must be in dynamic url form.

urlpatterns = [
    path('yourURL/<int:pk>/', views.index, name='RoamTrip'),
]
...

Since your code did not use dynamic url, I expect that when the index function was executed, pk would be None, resulting in a DoesNotExists error.

def index(request, pk=None, *args, **kwargs):
    ...
    postid = Post_Data.objects.get(pk=pk) # pk=None --> DoesNotExists 

And in the code you gave us, post_id is not currently used in index function.

Вернуться на верх