models.py
class Genre(models.Model):
name = models.CharField(max_length=30)
def __unicode__(self):
return self.name
Genres.py
from MyVideoGames.models import Genre
from ClientIGDB import ClientIGDB
genres = ClientIGDB.api_call("genres", ["name"], 50)
for genre in genres:
g = Genre.objects.create(name=genre["name"])
g.save()
When I'm trying to add some models to sqlite db i'm not able to do this import:
from myproj.models import Genre. I don't know why...
When I do it this error is shown:
% (desc, ENVIRONMENT_VARIABLE))
django.core.exceptions.ImproperlyConfigured: Requested setting DEFAULT_INDEX_TABLESPACE, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.
If someone can help me I'll be really gratefull
Whenever you run a script that uses python models you need to tell python that django exists first. Try this at the beginning of your script:
import os
import sys
import django
sys.path.append("/path/to/your/project")
os.environ["DJANGO_SETTINGS_MODULE"] = "yourProjectName.settings"
django.setup()
It's like a mini settings.py. You are not running something 'inside' django, so you need to start things up first. I wonder if anybody else could refine this to a solution that we don't need to hard code this every time we write a new script.
Related
If I do that :
from myapp import models
User.objects.first()
I got that error :
NameError : name 'User' is not defined
whereas if I do that
import myapp
myapp.models.User.objects.first()
it works
I don't understand at all why I have that problem
Thank you very much for your help !
Replace:
from myapp import models
with the following:
This way, you are telling Django which model classes to import rather than leaving Django guessing what to do with it.
It prevents you from loading unnecessary models which might not be used right away and could potentially increase load time.
from myapp.models import User
In your example, your have not imported class User actually. You have imported it's module called models
You can do one of these:
from myapp import models
models.User.objects.first()
Or:
from myapp.models import User
User.objects.first()
When I'm trying to migrate a new app onto the server i get this error
AttributeError: module 'django.db.models' has no attribute 'Models'- in terminal
I'm using PyCharm. I am very fresh to Django and web development so any tips will help. Thanks!
from django.db import models
# Create your models here.
class product(models.Model):
item = models.Textfiels()
description = models.Textfields()
price = models.Textfields()
There's no such class django.db.models.TextFields but this works for me on any recent version :
from django.db import models
class product(models.Model):
item = models.TextFiel()
description = models.TextField()
price = models.TextField()
You made 2 typos : the correct name is TextField and you typed Textfields (Python is case sensitive)
I suspect you didn't setup correctly your project under PyCharm. When correctly setup, it shows warnings on misspelled names (names underlined with red dots with default setting).
There's another variation to this question and that is in the form of:
AttributeError: module 'django.contrib.auth' has no attribute 'models'
As far as I can tell this is typically caused by conflicting imports or improperly imported files. Another cause could be changes to Django's updates but I'm not sure about that as I didn't find any documentation that changed that aspect of the Django library.
Short term solution to this is as follows:
from django.contrib.auth import models
class MyClass(models.User): """ """
This will allow you to at least test your runserver command and website on a browser of your choosing.
I'm still trying to figure out any other solutions to this problem that can be a fix for individually importing the 'auth' module itself.
At the time of this writing I'm using Django 2.2.6 whereas Django 2.2.7 is out and 2.2.8 is on the way to be released.
I'm not sure if this is the solution , but when I had this problem it was because in my admin.py file I had
from django.contrib import admin
from meetings.models import Meeting, Room
admin.site.register(Meeting, Room)
But changing it to solved the issue
from django.contrib import admin
# Register your models here.
from meetings.models import Meeting, Room
admin.site.register(Meeting)
admin.site.register(Room)
I created following custom user model by using "AbstractUser" model.
from django.conf.global_settings import AUTH_USER_MODEL
MyCustomUser(AbstractUser):
regions = models.ManyToManyField(to='SomeModel')
class Meta:
app_label = 'myapp'
MyObject(models.Model):
owner = models.ForeignKey(to=AUTH_USER_MODEL)
And I set AUTH_USER_MODEL to settings/base.py (I separated setting file each environment. e.x: settings/base.py, settings/development.py).
AUTH_USER_MODEL = 'myapp.MyCustomUser'
When I executed python manage.py syncdb, my console window has flared up by Django!
myapp.MyObject: 'owner' defines a relation with the model 'auth.User', which has been swapped out. Update the relation to point at settings.AUTH_USER_MODEL.
So, I had two questions.
Is the problem is that I separated settings.py each environment.
Does from django.global_settings import AUTH_USER_MODEL import myproject.settings?
And I resolved from myproject.settings.base import AUTH_USER_MODEL in this time.
global_settings is, as the name implies, the global default settings supplied by Django. So of course the default is 'auth.User'.
Since you override it in your own settings, you should import that instead. But as the documentation says, the way to import the current settings is always from django.conf import settings, rather than explicitly importing a settings file in your project.
Also note though that rather than using the settings at all here - which could lead to some dependency issues on startup - you should be using get_user_model() from django.contrib.auth, as explained in the documentation.
I use mongoengine with django. I have two applications with models.
app1/models.py:
from mongoengine import fields
from mongoengine.document import Document
class Model1(Document):
name = fields.StringField()
lists = fields.ListField(fields.ReferenceField("Model2", dbref=False))
app2/models.py:
from mongoengine import fields
from mongoengine.document import Document
class Model2(Document):
name = fields.StringField()
All applications were added to INSTALLED_APPS. When I use the django dev-server, everything is fine. But using this code with uwsgi-server there is an error:
Model2 has not been registered in the document registry.
Importing the document class automatically registers it, has it
been imported?
What I should do?
You should import app2.models somewhere. Put a comment by the import saying why it's there, so nobody removes the useless-looking import in the future.
When the django dev server starts up it imports the models from all installed apps and validates them. You'll see
Validating models...
0 errors found
This does not happen in a production environment. It is just a nicety of the dev server.
I would like to create a simple dynamic Sudoku game. Idea is to create new "puzzle" every hour then put it to database and let users solve it. Each solve attempt is compared with database for verification. For that purpose I would like to create python script that generates puzzle and puts it to the database. My database set in models looks like this:
from django.db import models
class user(models.Model):
name = models.CharField(max_length=30)
password = models.CharField(max_length=30)
time_registered=models.DateTimeField()
time_uploaded=models.DateTimeField()
points=models.IntegerField()
saved_sudoku=models.CommaSeparatedIntegerField(max_length=81)
solved=models.BooleanField()
def __str__(self):
return self.name
class server_sudoku(models.Model):
time_uploaded=models.DateTimeField()
generated_sudoku=models.CommaSeparatedIntegerField(max_length=81)
Now, when I use :
name1=request.POST["name"]
pass1=request.POST["password"]
newuser=user(name=name1,password=pass1,time_registered=datetime.datetime.now(),time_uploaded=datetime.datetime.now(),points=0,saved_sudoku="",solved=False)
newuser.save()
in views.py it creates new user. So to verify my idea I created application "generate_sudoku.py". To test its connection to database I just try to add user. Code looks as follows:
#!/usr/bin/env python
from db_interface.models import user
import random
import datetime
newuser=user(name="name", password="pass", time_registered=datetime.datetime.now() ,time_uploaded=datetime.datetime.now(), points=0, saved_sudoku="", solved=False)
newuser.save()
This simple app gives me this error:
raise ImportError("Settings cannot be imported, because environment variable %s is undefined." % ENVIRONMENT_VARIABLE)
ImportError: Settings cannot be imported, because environment variable DJANGO_SETTINGS_MODULE is undefined.
Hope I made it clear, I would like to run this application by windows scheduler so that it is automatically run every hour...
Use a custom manage.py command.
First link on google : http://eliasbland.wordpress.com/2010/01/25/importerror-settings-cannot-be-imported-because-environment-variable-django_settings_module-is-undefined/ ;)
This works for me (in a lambda script, not _ _init _ _.py file) :
import os
os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'
from django.contrib.auth.models import User #import django stuff after
print User.objects.all()