python 导入错误: cannot import name 'Faker' from 'faker'

标签 python django django-models faker python-datamodel

你好,我一直在编写这个脚本来预填充我的 Django 数据库,但是当我停止编写它时,我得到了一个奇怪的错误: 我的脚本:

import os
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'first_project.settings')

import django
django.setup()

## FAKE POPULATION SCRIPT:

import random
from first_app.models import AccessRecord,Webpage,Topic
from faker import Faker

# Creating a fake generator:
fakegen = Faker
topics = ['Search', 'Social', 'Marketplace', 'News', 'Games']


def add_topic():
    t = Topic.objects.get_or_create(top_name=random.choice(topics))[0]
    t.save()
    return t

def populate(N = 5):

    for entry in range(N):

        # GET THE TOPIC FOR THE ENTRY:
        top = add_topic()

        # Create the fake data for that entry:
        fake_url = fakegen.url()
        fake_date = fakegen.date()
        fake_name = fakegen.company()

    # Create the new webpage entry:
    webpg = Webpage.objects.get_or_create(topic = top, url = fake_url, name = fake_name)[0]

    # Create a fake access record for that webpage
    acc_rec = AccessRecord.get_or_create(name = webpg, date = fake_date)[0]


if __name__ == '__main__':
    print("Populating Script!")
    populate(20)
    print("Populating Complete!")

我得到的错误:

python populate_first_app.py
Traceback (most recent call last):
  File "populate_first_app.py", line 11, in <module>
    from faker import Faker
  File "E:\Python\Projects\Python And Django FullStack\Django\first_project\faker.py", line 1, in <module>
    from faker import Faker
ImportError: cannot import name 'Faker' from 'faker'

我从来没有见过这样的错误我在虚拟环境的影响下使用这个脚本我已经安装了所有的包我已经检查了一些东西,比如再次卸载和安装'faker'库但是它没有' 工作,我仍然得到错误。

最佳答案

您的项目中有一个名为“faker.py”的文件,它隐藏了您安装的库。重命名该文件。

关于 python 导入错误: cannot import name 'Faker' from 'faker' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53594210/

相关文章:

python - 在 django ORM 中获取注释内的列表

python - 类型错误 : inputNames() takes no arguments (2 given)

python - 使用套接字进行以太网通信的最佳实践

Python 打印/写入包含 "\f"的字符串

django - nginx和gunicorn的worker数量

django - 403 由 Graphite 烯-django。不要使用 csrf_exempt

python - Django:以编程方式/动态创建数据库表

python - Django-compressor/django-storages 链接被错误缓存;即将到期

python - Django 1.6 for_concrete_model 解释

python - 批量创建失败并显示 100 万行