Django: no such table snippets_snippet - python

I'm following this Django Rest tutorial on serialization: http://www.django-rest-framework.org/tutorial/1-serialization/#getting-started
I followed it pretty much to the letter. It gives the above error when I try to save a snippet.
from snippets.models import Snippet
from snippets.serializers import SnippetSerializer
from rest_framework.renderers import JSONRenderer
from rest_framework.parsers import JSONParser
snippet = Snippet(code='foo = "bar"\n')
snippet.save()
I'm working on Windows. The tutorial is made for Apple. I have had to enter some commands slightly differently for this reason. I have no idea if this has to do with what is wrong in this case.
I don't know where to even start in figuring out the problem here, so I could use any help. Thanks.

You need to make the migration (ie: forcing the db to corespond to what is defined by your new python code)
Do the following:
python manage.py makemigrations snippets
python manage.py migrate

You should remove db.sqlite3 as well as snippets/migrations. Later, create a folder named migrations inside snippets folder and create a __init__.py file inside snippets/migrations/ folder. Finally run:
python manage.py makemigrations && python manage.py migrate
Be sure you are into the virtual environment with the correct python version.

I believe the error refers to the models.py. Could you show the file so I can double check that too. Also there is a chance for unapllied migartions, double check if you've done this as well.

Related

Django Cannot Import Local Module During Migrations

In my project i've got two custom objects, defined in a local fields.py file & blocks.py file. I import them in my models.py as such:
from . import fields as blockfields
from . import blocks
and when running migrations, the autogenerated migrations look like this:
import PROJECTNAME.fields
import blocks
and since blocks isnt in the local scope of the migrations folder, it throws an error. If i manually change it to "import PROJECTNAME.blocks as blocks" then it runs fine, but it'd be silly to have to do that every time. Any thoughts?
Updates:
Using Django 2.1.4, Python 3.6.7
Folder structure is thus:
PROJECTNAME
-fields.py
-models.py
-blocks/
--__init__.py
--*.py
-migrations/
--*.py
Ive variably tried having a blocks.py file which just points to the folder, but it doesn't change the import scope for the automigration.
In my blockfields, i refer to blocks also, which is how the references get baked into the migrations. The fields.py file has an extension of django's generic models.Field, while the blocks are custom types from scratch.

How to execute external script in the Django environment

I am trying to execute an external snippet for debugging and terminal-like purposes in the environment the Django console uses so it can connect to the db, etc.
Basically, I am just using it for the same reason one would fiddle with the console but I am using longer snippets to output some formatted information so it is handy to have that code in an actual file manipulated with an IDE.
An answer said you could do that by executing python manage.py shell < snippet.py but I did not see a successfull result. And although no errors are reported, I am not getting the excepted output, but only a series of >>> prompts.
So how can I do this?
By the way, I am using PyCharm, in case this IDE has a shorthand way of doing this or any special tool.
I would say creating a new Custom management command is the best way to achieve this goal.
But you can run your script in a django environment. I use this sometimes to run a oneoff script or some simple tests.
You have to set the environment variable DJANGO_SETTINGS_MODULE to your settings module and then you have to call django.setup()
I copied these lines from the manage.py script, you have to set the correct settings module!
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "project.settings.local")
django.setup()
Here is a simple template script which I use sometimes:
# -*- coding: utf-8 -*-
import os
import django
# you have to set the correct path to you settings module
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "project.settings.local")
django.setup()
from project.apps.bla.models import MyModel
def run():
# do the work
m = MyModel.objects.get(pk=1)
if __name__ == '__main__':
run()
It is important to note that all project imports must be placed after calling django.setup().
Many times you need scripts to play with db or more. But you need to the the django way i.e. the ORM and play with every thing that your project has.
You can checkout https://github.com/django-extensions/django-extensions
You create a scripts folder in your project home and write down a method run . the app provide you a way to run those scripts easily.
How to do it.
Step 1 - Install the package.
Step 2 - Create a scripts folder with init.py in project root, and add 'django_extensions' in your applications
Step 3- Create a file send_email_to_users.py in scripts folder. Simple Example.
from project.models import MyModel
from django.contrib.auth.models import User
from project.utils import send_email
def run():
results = MyModel.objects.all()
for res in results:
send_mail(res.email)
Now from command line you can run
python manage.py runscript send_mail_to_users
If its just a one off script,
import django
django.setup()
from myapp.models.import MyModel
You need to have your environmental variable set up, so its easiest to run it from the IDE (make it part of the same project, right click on teh file and there should be a run option).
If you are looking for something to run on a production environment I would create a management command as suggested by DanEEStar.

Django 1.7 - makemigrations not detecting changes - managed models

I have just installed django 1.7 in my virtual env.
Then I manually created the following files:
service_bus/
service_bus/__init__.py
service_bus/django_settings.py
service_bus/models
service_bus/models/__init__.py
service_bus/models/dsp.py
service_bus/models/audience_type.py
service_bus/models/category.py
service_bus/models/audience.py
service_bus/models/dsp_config.py
service_bus/models/apsettings.py
So I have a settings file service_bus/django_settings.py and the service_bus app.
Then I did, on bash:
export DJANGO_SETTINGS_MODULE='service_bus.django_settings'
Then I just try to run makemigrations, but it says no changes are detected.
$ django-admin makemigrations
Loading properties from /etc/s1mbi0se/dmp.ini
System check identified some issues:
WARNINGS:
?: (1_6.W001) Some project unittests may not execute as expected.
HINT: Django 1.6 introduced a new default test runner. It looks like this project was generated using Django 1.5 or earlier. You should ensure your tests are all running & behaving as expected. See https://docs.djangoproject.com/en/dev/releases/1.6/#new-test-runner for more information.
No changes detected
$ django-admin makemigrations service_bus
Loading properties from /etc/s1mbi0se/dmp.ini
System check identified some issues:
WARNINGS:
?: (1_6.W001) Some project unittests may not execute as expected.
HINT: Django 1.6 introduced a new default test runner. It looks like this project was generated using Django 1.5 or earlier. You should ensure your tests are all running & behaving as expected. See https://docs.djangoproject.com/en/dev/releases/1.6/#new-test-runner for more information.
No changes detected in app 'service_bus'
In all my models I have something like
class APSettings(models.Model):
...
class Meta:
db_table = u'APSettings'
app_label = 'service_bus'
What could I be missing?
You need to run the migrate command first to scaffold the database schema. Then, you can run makemigrations for each app. Check the Django tutorial for more on this.
Make sure you update your models.py file to actually import the models. For example in models.py you'd have from service_bus.models.audience import *. The manage script goes over that file, imports all the models in audience.py and detects changes in there. If you did not add your new models to models.py then the manage script won't know about the new models in you models files.

Django settings.py Error: Import by filename is not supported

I am running Django in a virtual environment (using virtualenv), and I'm trying to add a custom development environment settings file to simplify app configuration when I'm developing. My plan was to do this with two lines of code
if os.environ.get('DEVELOPMENT', None):
from login import settings_dev
I've also tried import settings_def and from login.settings_dev import *. My settings_dev.py file is sitting in the same directory as my settings.py file and my app is sitting in a folder called login. When I run python login/manage.py syncdb I get this error:
Error: Import by filename is not supported.
My searching keeps bringing up DJANGO_SETTINGS_MODULE (though I'm not sure how it plays into all this - first Django app :]), so just an FYI it is set in my settings.py file like so:
os.environ['DJANGO_SETTINGS_MODULE'] = 'login.settings'
I've also tried exporting it in my terminal, but I get the same error.
Does anyone know how I can fix this/what I'm doing wrong here?
Make sure while passing relative address of file to use "." instead of "/".
I faced the same error what I actually did
"music/urls"
But it should be
"music.urls"
In the original settings.py, at the very end:
try:
from settings_dev import *
except ImportError:
pass
Create settings_dev.py in the same directory as settings.py, and in it, add these two lines at the very top:
import sys
globals().update(vars(sys.modules['settings']))
Now add whatever development settings you want in this file.
I had similar error in runserver command execution and finally I've found that this error raises because of python version incompatibility by the django version installed. There is two versions of python on my system and I had running django server by the wrong one. Hope it could be helpful to someone.

Trouble running example django code

Im trying to learn Django by looking at examples, but Im having a bit of a problem running the examples I find.
I downloaded 'cheeserator' from https://github.com/jacobian/cheeserater
and I tried running it with python manage.py runserver
but I get the following error -
Error: Can't find the file
'settings.py' in the directory
containing 'manage.py'. It appears
you've customized things. You'll have
to run django-admin.py, passing it
your settings module. (If the file
settings.py does indeed exist, it's
causing an ImportError somehow.)
What am I doing wrong?
You need to have a settings.py file.
As per the instructions in the link provided:
Then you'll want to create a settings.py file in this directory containing::
from settings_template import *
# Override any settings you like here.
Or if you don't want to override anything rename settings_template.py to settings.py

Categories