-1

我正在建立一个博客,我想统计任何访问我的页面的用户并显示

访问该页面的用户。并按填充显示内容。我GenericForeignKey用来访问我的hitcount包上的模型

基于hitcount包的文档。在我完成创建模型并尝试运行我的服务器后,出现以下错误。

文件“F:\professional blog in django\BLOG\blog\blogapp\models.py”,第 48 行,在 Post site_visitor = GenericForeignKey( TypeError: init () got an unexpected keyword argument 'object_id_fields'

有什么我做错了吗,请帮忙

model.py

    from django.db import models from django.contrib.auth.models import
    User from datetime import datetime, date from django.db.models.fields
    import related from django.urls import reverse from
    django.contrib.contenttypes.fields import GenericForeignKey from
    hitcount.models import HitCountMixin, HitCount
    # Create your models here. from django.core.exceptions import ValidationError 

    class Post(models.Model):
        title = models.CharField(max_length=100)
        author = models.ForeignKey(
            User, on_delete=models.CASCADE, null=True, blank=True)
        body = models.TextField()
        category = models.ForeignKey(
            Category, on_delete=models.CASCADE, default=1)
        date = models.DateField(auto_now_add=True)
        image = models.ImageField(upload_to="image", validators=[image_vailid])
        likes = models.ManyToManyField(User, related_name="like_post")
        site_visitor = GenericForeignKey(
            HitCountMixin, object_id_fields="object_pk", content_type_field="content_type")

     def numbers_of_likes(self):
         return self.likes.count()
 
     def __str__(self):
         return self.title + '| ' + str(self.author)
 
     def get_absolute_url(self):
         return reverse("home")
 
 

Error:

     File "F:\professional blog in django\BLOG\blog\blogapp\models.py",
     line 48, in Post
        site_visitor = GenericForeignKey( TypeError: __init__() got an unexpected keyword argument 'object_id_fields'
4

1 回答 1

1

问题正是它所说的:您正在尝试使用该类不接受的关键字参数创建一个类(来源)

class GenericForeignKey(object):
    # truncated
    def __init__(self, ct_field="content_type", fk_field="object_id", for_concrete_model=True):

如您所见,GenericForeignKey该类仅接受 3 个参数(类除外)ct_fieldfk_fieldfor_concrete_model. 所以只有这三个可以用作关键字参数。

您需要传递不带关键字的参数,或者确保在正确的位置传递此参数。从 django 文档和API 参考开始。

如果您不了解关键字参数和位置参数之间的区别,请转到 python 文档页面:参数

编辑:这是代码中的错误部分:

site_visitor = GenericForeignKey(
            HitCountMixin, object_id_fields="object_pk", content_type_field="content_type")

请阅读我为您提供的链接。

于 2021-06-18T14:39:22.430 回答