What is this code snippet doing? (from Google App Engine Django example) - django

I was wondering what this snippet exactly does?
(found here: http://code.google.com/p/google-app-engine-samples/source/browse/trunk/django_example/django_bootstrap.py)
# Make sure we can import Django. We may end up needing to do this
# little dance, courtesy of Google third-party versioning hacks. Note
# that this patches up sys.modules, so all other code can just use
# "from django import forms" etc.
try:
from django import v0_96 as django
except ImportError:
pass

As I stated in another question before, you can use different django versions in app engine (starting from 0.96 up to 1.2 currently). By default it is still using 0.96 as django (and this is what this code snippet does). Though you can change this by adding something like the following to your main.py:
import os
os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'
from google.appengine.dist import use_library
use_library('django', '1.2')

Related

Moving from Django 1.6.x to 1.9.x import model errors

I have a few defined apps in my Django project, each with their own sub-directory (created with startapp)
In the views.py of app1 I have an import to a model from app2
from app2.models import MyModel
This worked in Django 1.6.x. In version 1.9 I get:
Could not resolve variable
sometimes on MyModel, sometimes on the filter(..) method, or on both.
If I change the import to
from app2.models import * ##UnusedWildImport
then everything works just fine.
Has anything changed in 1.9.x (or before) that requires a different mode of importing models external to the app?
I think I can rule our circular import problems as this would have failed in 1.6...
Edit: Based on the comments I started wondering whether this might be a PyDev problem.
I tried:
Removing and re-adding Python to PyDev - it did not help
This https://stackoverflow.com/a/8534599/5958359 - removing the myproject/src folder from PYTHONPATH worked ... with a caveat.
The error did not appear when I completely removed the import statement, so this is not a good solution
This is a PyDev error.
Searches haven't yielded an adequate solution - most simply explain how to disable the error - so I will not link to any solution here.
My workaround, as much as I don't like from xxx import * seems like the best temporary solution.

Cannot import serializers.ListSerializer

When trying to use ListSerializer, according to this doc, I get an error:
Cannot find reference 'ListSerializer' in 'serializers.py'
Here is my import statement:
from rest_framework import serializers
What am I doing wrong?
Make sure you are using Django REST Framework 3. The ListSerializer was added in DRF 3 and did not exist in earlier version.
You can check this using pip freeze, and you should see a line similar to...
djangorestframework==3.0
...in the the output. If you are using an earlier version, you can upgrade to get the new ListSerializer, as well as many other features that were recently introduced.

Relative Imports

I'm reading Two Scoops Django Best Practices to make my coding style improve. I'm in relative imports and here is the sample code to make it reusable.
Old Way:
from cones.foo import bar
New way:
from .foo import bar
The code above is for cones app, what if I call the other model in other app? Do I have to put like this:
from .foo import bar
from .other import sample
OR
from .foo import bar
from test.other import sample
What is the correct way?
I usually use imports like this only for one reason
from .foo import bar
from .other import sample
The reason being
If Tomorrow, my module name changes from say 'test' to 'mytest' then the code does not require a refactoring. The code works without breaking.
Update
All imports starting with a '.' dot, only works within that package.
Cross package imports need require the whole path.
If test is another app,
from .other import sample
wont work.
Update:
You can only use relative imports when you're importing from the same app.
Inside test app
from .other import sample
will work. But you'll still need the complete form
from cones.foo import bar
if you import method defined in foo from test app.
So answering your question the second way is the correct way.

Use models outside a view

To send emails and stuff, I use code outside the views.py file (too much code there). I created a file named "tools.py" in the app folder where I start with
from django.shortcuts import render_to_response
from django.core.mail import send_mail
from mysite.myapp.models import MyModel
With runserver, I have an error ImportError: cannot import name MyModel
This is strange as I use the same import in the views.py file and there is no problem...
Any idea ? Thanks
Most likely, you have a circular import. Are you importing this tools.py file in your myapp/models.py?
A couple of things:
Make sure you have your init.py file in the folder where your
"tools.py" file is located, this is a common reason why something might not be found.
I'm working on setting up something that requires something very similar to your requirements.
If you are trying to have this as a on/off process eg.) cronjob, worker etc. Do the following.
#!/usr/bin/env python
#########################################################################
# Required DO NOT REMOVE
#########################################################################
import os
import sys
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "appname.settings")
#########################################################################
# Import My Models, or Run an Include to Handle Processing.
from app.models.model import *
# Do Stuff to Test ( I suggest a simple insert into the model or pull and return content )
Save this file in the same folder that your "manage.py" is saved in, you can call this directly and it should process, you can setup a cronjob for it to run, etc. This allows you
to have a little less code as it doesn't run some of the processes that django runs prior to rendering a view from the urls.py file.
If this is unclear please feel free to comment and I will edit with correction or further details.
All the best

In django, how do I query a separate project from within my main project?

I have a project (#1) with a couple apps in it using a mysql database #1. I also have another project (#2) whose django code is on the same server, but it uses a different mysql database (#2).
My goal is to be running a web app in project #1 and use the django models from project #2 for a simple query against db #2. However, when I import from project #2, it still uses the #1 database, even though the settings.py file for #2 is appropriately using database #2 (i.e. when I run the web app in project #2, it works fine).
Here is the entirety of a file that I can successfully run as a standalone script. Sadly, when I import the file into project #1 and run the function, it fails (because it is looking in db#1 for the table):
import sys
def get_stuff_from_project2(ids):
from django.core.management import setup_environ
from project2 import settings
setup_environ(settings)
from project2.myapp2.models import mymodel2
all_rows = mymodel2.objects.filter(id__in=ids).values()
return(all_rows)
# as a standalone script, run the main function
if __name__ == "__main__":
sys.path.append("/home/me/django")
print str ( get_stuff_from_project2( sys.argv[1:] ) )
Again, this works as a standalone script. But, from project #1 (using code below) it fails with a DatabaseError, Table 'db1.myapp2_mymodel2' doesn't exist:
from project1.myapp1.standalone_script import get_stuff_from_project2
all_rows = get_stuff_from_project2( ids )
My guess here is that the setup_environ function does not actually process the new DATABASE_NAME, or that it can't change an existing DATABASE_NAME once the settings have been set?
I'm a bit lost at this point and have been trying to search for a solution. I don't really want to go down the "multi-site" or "multi-database" approach, since I would really like to keep project 1 and project 2 as separate as possible. My alternative would be to call the standalone script as a system call from within project 1, or to make a view in project 2 which is an API and sends data out. But, I thought that just using a model would be simplest if it worked.
Thanks.
------- added April 13, 11:35 PST ----
Here's a simpler version of the question: How can I access two different projects from a single standalone script. The following code works ok for whichever project I do setup_environ on first, but it can't do the second one:
import sys
from django.core.management import setup_environ
sys.path.append('/home/me/django')
from project1 import settings
print setup_environ(settings) # shows /home/me/django/project1
print settings.DATABASE_NAME # shows db1
from project1.myapp1.models import mymodel1
mymodel1.objects.filter(id=9376544).values() # works fine
from project2 import settings
print setup_environ(settings) # shows /home/me/django/project2
print settings.DATABASE_NAME # shows db2
from project2.myapp2.models import mymodel2
mymodel2.objects.filter(id=6544).values() # fails with:
# django.db.utils.DatabaseError: (1146, "Table 'db1.myapp2_mymodel2' doesn't exist")
I was unable to solve this using a single script. I instead used two scripts: the first called the second as a shell command, and the second output formatted data as a list to stdout.
This has been robust enough for the problem of reading a single stream of data from another app's database, but would not be suitable for a larger problem such as requiring several queries or writing to the second app's data. For the more complex problem, add APIs (XMLRPC, REST are easy in Django) to make calls into the running apps.
You have to add that other project to your pythonpath (in your wsgi file, for example, if you are using mod_wsgi, or in projects manage.py file if you want to access that project in "python manage.py shell" too). If you have done that it works like a magic.