Невозможно назначить "'post": "Comment.content_type" должен быть экземпляром ContentType. - PullRequest
0 голосов
/ 21 июня 2020

Я хочу создать опцию комментариев в моем подробном представлении сообщения для блога. Я унаследовал FormMixin, чтобы использовать CommentForm в PostDetailView. Кроме того, мне пришлось унаследовать HitCountDetailView для hitcount. Теперь, когда я пытаюсь добавить комментарий, он показывает эту ошибку «Cannot assign» 'post' »:« Comment.content_type »должен быть экземпляром« ContentType ». Я несколько раз пытался решить эту проблему но не удалось.Как я могу решить эту ошибку? Любые предложения. Заранее спасибо. Вот мой код:

Views.py:

class PostDetailView(FormMixin, HitCountDetailView):
    model = Post
    form_class = CommentForm
    template_name = "blog/published/post_detail.html"
    context_object_name = 'post'
    slug_field = 'slug'
    # set to True to count the hit
    count_hit = True

def get_initial(self):
    instance = self.get_object()
    print(instance.title)
    return {
      "content_type": instance.get_content_type,
      "object_id": instance.id,
       }

def get_success_url(self):
    return reverse("post-detail", kwargs={"slug": self.object.slug})

def get_context_data(self, *args, **kwargs):
    context = super(PostDetailView, self).get_context_data(*args, **kwargs)
    stuff = get_object_or_404(Post, slug=self.kwargs['slug'])
    comments = Comment.objects.filter_by_instance(stuff)
    context['comments'] = comments
    context["form"] = self.get_form()

    return context

def post(self, request, *args, **kwargs):
    self.object = self.get_object()
    form = self.get_form()
    if form.is_valid():
        return self.form_valid(form)
    else:
        return self.form_invalid(form)


def form_valid(self, form):
    return super().form_valid(form)   

models.py

@python_2_unicode_compatible
class Post(models.Model):
    title = models.CharField(max_length=250)
    slug = models.SlugField(max_length=250, unique=True)
    author = models.ForeignKey(User, on_delete=models.CASCADE)
    body = RichTextUploadingField(blank=True, null=True)
    created = models.DateTimeField(default=timezone.now)
    updated = models.DateTimeField(auto_now=True)
    published = models.DateTimeField(blank=True,null=True)
   
    hit_count_generic = GenericRelation(HitCount, object_id_field='object_pk',
    related_query_name='hit_count_generic_relation')

    class Meta:
        ordering = ('-published',)

    def publish(self):
        self.published = timezone.now()
        self.status = 'published'
        self.save()


    def get_absolute_url(self):
        return reverse('post_detail', args=[self.slug])

    @property
    def get_content_type(self):
        instance = self
        content_type = ContentType.objects.get_for_model(instance.__class__)
        return content_type



class CommentManager(models.Manager):
    def filter_by_instance(self, instance):
        content_type = ContentType.objects.get_for_model(instance.__class__)
        object_id = instance.id
        qs = super(CommentManager, self).filter(content_type=content_type, object_id=object_id)
        return qs



class Comment(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)

    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)
    objects = CommentManager()


    def __str__(self):
        return self.user.username

forms.py:

class CommentForm(forms.ModelForm):
    content_type = forms.CharField(widget=forms.HiddenInput)
    object_id = forms.IntegerField(widget=forms.HiddenInput)
    content = forms.CharField(widget=forms.Textarea(
    attrs={
     'class': 'form-control',
     'id': 'body',
     'rows': 5,
     'cols': 40
     }))
    class Meta:
        model = Comment
        fields = ['content_type','object_id','content']

post_detail. html:

<form action="." method="POST">
         {% csrf_token %}
         {{ form.as_p }}
         <input type="submit" class="btn btn-default" value="Add Comment">
   </form>
...