[Solved] local variable ‘content_type’ referenced before assignment


You only set content_type when your form is valid:

if comment_form.is_valid():
    # ...
    content_type = ContentType.objects.get_for_id(content_type_id)
    # ...
else:
    print(comment_form.errors)

So when comment_form.is_valid() is false, the variable is never set. You have the same issue with object_id_data and content_data.

Perhaps you need to re-think what should be returned when the form is not correct? It seems to me that the Comment.objects.get_or_create() call should only be exected when your form is valid:

def post(self, request, **kwargs):
    comment_form = CommentForm(request.POST)

    if comment_form.is_valid():
        content_type_id = comment_form.cleaned_data.get('content_type')
        object_id_data = comment_form.cleaned_data.get('object_id')
        content_data = comment_form.cleaned_data.get('content')

        content_type = ContentType.objects.get_for_id(content_type_id)
        print(object_id_data)
        print(content_data)

        new_comment, created = Comment.objects.get_or_create(
            user=request.user,
            content_type=content_type,
            object_id=object_id_data,
            content=content_data,
        )

    else:
        print(comment_form.errors)


    return self.get(request, **kwargs)

Now it doesn’t matter that those variables are not set outside the if block, they are simply not needed elsewhere.

4

solved local variable ‘content_type’ referenced before assignment