pythondjangocontenttype

ContentType matching query does not exist on django 2.2


I have been using django to build a Blog, and when i tried to make a comment section under each post i get the comment icon(where i can type some comments) but when i post the comment i get the error straight away, which is "ContentType matching query does not exist".

I tried to find the problem on stack and youtube but they said that solving this problem requires experience on dumpdata

class Comment(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL, default=1, null=True, on_delete=models.SET_NULL)
    content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
    object_id = models.PositiveIntegerField()
    content_object = GenericForeignKey('content_type', 'object_id')
    content = models.TextField()
    timestamp = models.DateTimeField(auto_now_add=True, auto_now=False)


    objects = CommentManager()


def blog_post_detail_view(request, slug):
    instance = get_object_or_404(BlogPost, slug=slug)
    share_string = quote_plus(instance.content)
    initial_data = {
        'content_type': instance.get_content_type,
        'object_id': instance.id
    }

    form = CommentForm(request.POST or None, initial=initial_data)

    if form.is_valid():
        c_type = form.cleaned_data.get('content_type')
        content_type = ContentType.objects.get(model=c_type)
        obj_id = form.cleaned_data.get('object_id')
        content_data = form.cleaned_data.get('content')
        new_comment, created = Comment.objects.get_or_create(
            user=request.user,
            content_type=content_type,
            object_id=obj_id,
            content=content_data
        )

    comments = instance.comments
    template_name = 'blog/detail.html'
    context = {
        "object": instance,
        'comments': comments,
        'share_string': share_string,
        'comment_form': form
    }

    return render(request, template_name, context)


from django import forms


from .models import Comment


    class CommentForm(forms.Form):
        content_type = forms.CharField(widget=forms.HiddenInput)
        object_id = forms.IntegerField(widget=forms.HiddenInput)
        content = forms.CharField(widget=forms.Textarea)

So basically i should have gotten my comment posted but instead i get that error:"ContentType matching query does not exist".


Solution

  • Your CommentForm should be a ModelForm, you can set the widgets in the Meta.widgets of the ModelForm

    class CommentForm(forms.ModelForm):
    
        class Meta:
            model = Meta
            fields = ('content_type', 'object_id', 'content')
            widgets = {
                'content_type': forms.HiddenInput,
                'object_id': forms.HiddenInput,
            }
    

    This way form.cleaned_data.get('content_type') will contain the actual ContentType object so you don't have to do ContentType.objects.get