在我的Django项目中,我有一个名为“ catalog”的应用,这是models.py
中的模型:
from django.db import models
class Catalog(models.Model):
brand = models.CharField(max_length=255)
supplier = models.CharField(max_length=255)
catalog_code = models.CharField(max_length=255, null=True, blank=True)
collection = models.CharField(max_length=255)
season = models.CharField(max_length=255)
size_group_code = models.CharField(max_length=2)
currency = models.CharField(max_length=3)
target_area = models.CharField(max_length=255)
我想创建一个Catalog对象,但是我不想使用管理面板或表单来创建它,所以在同一应用程序“目录”中,我创建了tools.py
,它只是一个脚本,它会读取一个csv文件,并创建一个Catalog()
距离。
from catalog.models import Catalog
def create_catalog(file):
with open(file, 'r') as f:
f = f.readlines()
catalog = Catalog(# all my keyword args)
catalog.save()
我不知道脚本是否合适,但这并不重要,我的问题是当我尝试在IDE中运行tools.py
时出现此错误:
raise ImproperlyConfigured(
django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.
我尝试使用以下命令从外壳运行它:
exec(open('catalog/tools.py').read())
但是什么也没有发生,也没有回溯。
那么我如何在Django项目中运行Python脚本,该项目在我的数据库中创建objs? 我已经知道: How to execute a Python script from the Django shell?和this。但没有解决方案。
答案 0 :(得分:0)
最好的解决方案是使管理命令可以通过键入来运行
Initial value of a = [0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.
0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
Final value of a = [ 1. 3. 5. 7. 9. 11. 13. 15. 17. 19. 21. 23. 25. 27. 29. 31. 33. 35.
37. 39. 41. 43. 45. 47. 49. 51. 53. 55. 57. 59. 61. 63. 65. 67. 69. 71.
73. 75. 77. 79.]
您可以在此处了解更多信息:
https://docs.djangoproject.com/en/3.1/howto/custom-management-commands/