So when I create a model instance using the CLI, it works.
The model:
class Post(models.Model):
title = models.CharField(max_length=100)
cover = models.ImageField(upload_to='images/')
description = models.TextField(blank=True)
def __str__(self):
return self.title
Then I did:
$ python manage.py shell
>>>from blog.models import Post
>>>filename = 'images/s.png'
>>>Post.objects.create(title=filename.split('/')[-1], cover=filename, description='testing')
And it worked, it showed up on the page that I'm displaying these models at.
However, when I take this same code and put it in a file, portfolio_sync.py, it doesn't work.
from blog.models import Post
filename = 'images/s.png'
Post.objects.create(title=filename.split('/')[-1], cover=filename, description='testing')
I get this error:
Traceback (most recent call last):
File "portolio_sync.py", line 1, in <module>
from models import Post
File "/Users/rfrigo/dev/ryanfrigo/blog/models.py", line 4, in <module>
class Post(models.Model):
File "/Users/rfrigo/anaconda3/lib/python3.7/site-packages/django/db/models/base.py", line 87, in __new__
app_config = apps.get_containing_app_config(module)
File "/Users/rfrigo/anaconda3/lib/python3.7/site-packages/django/apps/registry.py", line 249, in get_containing_app_config
self.check_apps_ready()
File "/Users/rfrigo/anaconda3/lib/python3.7/site-packages/django/apps/registry.py", line 131, in check_apps_ready
settings.INSTALLED_APPS
File "/Users/rfrigo/anaconda3/lib/python3.7/site-packages/django/conf/__init__.py", line 57, in __getattr__
self._setup(name)
File "/Users/rfrigo/anaconda3/lib/python3.7/site-packages/django/conf/__init__.py", line 42, in _setup
% (desc, ENVIRONMENT_VARIABLE))
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.
How can I fix this, and create a model instance in a .py file? (Because I need to loop through a bunch of file names).
Thanks for your help!!