contenttypes.models.DoesNotExist:ContentType matchingquery不存在如何改进

时间:2017-07-13 13:44:54

标签: django content-type django-contenttypes

通过另一个项目这个评论系统工作了!但没有,如何解决这个问题?

完全追溯

> Traceback (most recent call last):   File
> "C:\Users\P.A.N.D.E.M.I.C\Desktop\td11\lib\site-packages\django\core\handlers\exception.py",
> line 41, in inner
>     response = get_response(request)   File "C:\Users\P.A.N.D.E.M.I.C\Desktop\td11\lib\site-packages\django\core\handlers\base.py",
> line 187, in _get_response
>     response = self.process_exception_by_middleware(e, request)   File "C:\Users\P.A.N.D.E.M.I.C\Desktop\td11\lib\site-packages\django\core\handlers\base.py",
> line 185, in _get_response
>     response = wrapped_callback(request, *callback_args, **callback_kwargs)   File "C:\Users\P.A.N.D.E.M.I.C\Desktop\td11\newstudio\serials\views.py",
> line 78, in post_of_serie
>     content_type                                = ContentType.objects.get(model=c_type)   File
> "C:\Users\P.A.N.D.E.M.I.C\Desktop\td11\lib\site-packages\django\db\models\manager.py",
> line 85, in manager_method
>     return getattr(self.get_queryset(), name)(*args, **kwargs)   File "C:\Users\P.A.N.D.E.M.I.C\Desktop\td11\lib\site-packages\django\db\models\query.py",
> line 380, in get
>     self.model._meta.object_name django.contrib.contenttypes.models.DoesNotExist: ContentType matching
> query does not exist.

这是views.py

initial_data        = {
                            "content_type": serie.get_content_type,
                            "object_id": serie.id

                            }
    if request.method == 'POST':
        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")
            parent_obj                  = None
            try:
                parent_id               = int(request.POST.get("parent_id"))
            except:
                parent_id               = None

            if parent_id:
                parent_qs               = Comment.objects.filter(id=parent_id)
                if parent_qs.exists() and parent_qs.count() == 1 :
                    parent_obj          = parent_qs.first()
            new_comment, created        = Comment.objects.get_or_create(

                                                                user            = request.user,
                                                                content_type    = content_type,
                                                                object_id       = obj_id,
                                                                content         = content_data,
                                                                parent          = parent_obj

                                                                    )
            return HttpResponseRedirect(new_comment.content_object.get_absolute_url())
    form = CommentForm(initial=initial_data)
    comments            = Comment.objects.filter_by_instance(serie)
    context = { "serie":serie, 
                "full_path":full_path, 
                "title":title, 
                "poster":poster,
                "comments": comments,
                "comment_form": form,
                }
return render(request, 'series.html', context)

在html模板中,contenttype显示我在视图中使用的模型 但它不起作用。但一切都正确显示 when error is blow up

第二个img kkk

模型

class Series(models.Model):
    id                                          = models.AutoField(primary_key=True)
    rus_name                                    = models.CharField(max_length=60) 
    eng_name                                    = models.CharField(max_length=60) 
    slug                                        = models.SlugField(unique=False) 
    serial_of_this_series                       = models.ForeignKey(Serial, on_delete=models.CASCADE, default=True)
    season_of_this_series                       = models.ForeignKey(Season, on_delete=models.CASCADE, default=True)
    number_of_series                            = models.IntegerField(default=0)
    description                                 = models.TextField(max_length=700, blank=True, default=None)
    size_of_torent_file                         = models.CharField(max_length=60, default=None)
    link_for_dowloand_serie_in_quality_360p     = models.CharField(max_length=60, default=None)      
    link_for_dowloand_serie_in_quality_720p     = models.CharField(max_length=60, default=None)      
    link_for_dowloand_serie_in_quality_1080p    = models.CharField(max_length=60, default=None)      
    rating                                      = models.FloatField(default=0, blank=True)  
    is_active                                   = models.BooleanField(default=True)
    timestamp_rus                               = models.DateField(auto_now_add=True, auto_now=False)
    updated                                     = models.DateTimeField(auto_now_add=False, auto_now=True)
    timestamp_eng                               = models.CharField(max_length=60) 
    time_of_series                              = models.DecimalField(max_digits=10, decimal_places=2, default=42)
    new_or_old                                  = models.BooleanField(default=True)

    def save(self, *args, **kwargs):
        name_of_serial                          = self.serial_of_this_series.rus_name_of_seriall
        number_of_season                        = self.season_of_this_series.number_of_season
        number_of_series                        = self.number_of_series

        if self.new_or_old:
            #notification_for_new_series_task.delay(name_of_serial, number_of_season, number_of_series)
            season_module                       = Season.objects.get(slug=self.season_of_this_series.slug, serial_for_this_season=self.serial_of_this_series)               
            season_module.number_of_series_released += 1
            season_module.save()
            self.new_or_old                         = False
        return super(Series, self).save(*args, **kwargs)

    def get_absolute_url(self):
        return reverse('series:post_of_serie', kwargs=
                      {'serial_slug': self.serial_of_this_series.slug,
                       'season_slug': self.season_of_this_series.slug,
                       'series_slug': self.slug})


    def __str__(self):
        return "%s | %s" % (self.rus_name, self.number_of_series)

    @property 
    def comments(self):
        instance    = self
        qs          = Comment.objects.filter_by_instance(instance)
        return qs

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



    class Meta:
        ordering                                = ["-timestamp_rus"]
        verbose_name                            = 'Series'
        verbose_name_plural                     = 'Series'

1 个答案:

答案 0 :(得分:1)

我希望content_type值为小写,即series而不是Series

您的Serie.get_content_type属性返回内容类型实例。您应该使用model字段。

initial_data = {
    "content_type": serie.get_content_type.model,
    "object_id": serie.id,
}

目前尚不清楚为什么需要在表单中包含content_typeobject_id。您已在视图中拥有serie,因此您应该可以从表单中删除这些字段,然后按如下方式更新视图:

if form.is_valid():
    content_type                = serie.get_content_type
    obj_id                      = serie.id
    content_data                = form.cleaned_data.get("content")
    ...