Google App Engine Interactive Console: ImportError: No module named models - django

I have a django project running on my local server under the google app engine python SDK 1.9.7.
I want to run a query in the interactive console. I have a model called Flatpage
I put the seemingly appropriate handler in the app.yaml file, namely:
url: /admin/.*
script: google.appengine.ext.admin.application
login: admin
From the docs i understood that when the local development server is running the interactive console on the admin server would be running in the same environment as the a project. Yet:
the interactive console does not recognize any of my model classes and when i try to import models I get an error: ImportError: No module named models
I have tried adding the local path to the models.py file to the directory as well as various names like app.models, appname.models and projectname.models to no avail.
However. when I copy and paste the models file into the interactive console it works.
Would someone explain how to import the models file into the interactive console,
and, secondly, why the interactive console, which seemingly should already have the models defined when the server starts, needs to have the models defined again, anyway, thanks!

I'm not sure why you're adding that handler to use the console locally, but what I do is use the Development Console (available since last year), which by default runs on port 8000, from there (localhost:8000/console most likely) you can import modules from your project.
For example if you have models.py in the same directory as app.yaml, you should be able to do:
import models
entity = models.Flatpage()
with no problem.

Related

How to call a function before a django app start?

In my django project i have to check if a database/table exist before starting application, i don't know how is better insert the code for check.
I try to add in views.py into login function a try except block but i was try to find an elegant and more effective solution.
Thanks in advance
To check before the app starts then you can use the AppConfig.ready() function. This gets called before the application starts, but after your project has started. If you want to check before the project starts then you will have to hook into the method you use to start your project, eg within wsgi.py or even manage.py
AppConfig.ready() docs Note that the docs specifically say
avoid interacting with the database in your ready() implementation.
But your use case may justify doing this.
The ready function is called when you run the commands from manage.py eg
manage.py shell / manage.py migrate / etc
It won't get called when your site is visited of course. If you want to run a DB check in response to a visitor action then that code should go into your view
You put the ready() function in your apps.py:
from django.apps import AppConfig
from django.db import connection
class MyAppConfig(AppConfig):
name = 'MyApp'
def ready(self):
print("i am the ready function and the database test code goes here")
# put your test code here, eg you could read all the tables from sqlite
with connection.cursor() as cursor:
cursor.execute("SELECT name FROM sqlite_master;")
rows=cursor.fetchall()
print (rows)
You can write your custom django admin commands and run it by using python manage.py your_command right before calling python manage.py runserver. There are detailed examples at the official documentation.
One of the advantages of using commands is that testing commands are fairly easy. Django has a package for calling commands django.core.management.call_command which enables funtionally test your command.

how to access django models with script outside of the project

I have two projects. The new one bases on Django and the old one based on PHP. Both are alive. I want to synchronize all info between these projects. I have a python script which parse all info from the PHP project but I can't load it to the Django project.
The only way I found to solve the problem is to connect to sqllite DB of the django project from my python script. But I feel that this solution is not the best&
Is there a way to write smth like this in my python script:
from .models import MyModel
for (f1, f2, f3) in parse_results:
result = MyModel.objects.create(field1=f1, field2=f2, field3=f3)
For now when i try to import MyModel i see
ModuleNotFoundError: No module named '__main__.models'; '__main__' is not a package
You can write your script code in a Django custom command, in this way you have access to your Django models.

How to execute a python program by a button click on html page generated by django

I created a Django project to launch a htmlpage which has a button with name run test. I would like to run a python script file hello.py(located outside the django project) when the button is clicked. I am quite new to this scripting.
Can anyone help me with this question as soon as possible? Your help would be appreciated.
My django project consists of following files:
TestProject(project folder)
myapp(folder)
int.py
admin.py
models.py
tests.py
urls.py
views.py
Templates(folder)
index.html
Testproject(folder)
int.py
urls.py
settings.py
views.py
wsgi.py
admin.py
manage.py
The python script file-helllo.py is located C:/hello.py
There are two basic approaches you could take to do this:
(1) Run the script as a subprocess (i.e. execute a separate program outside of your django application) - this is documented in the Python docs on subprocesses. Below is a brief example, you will need to go through the docs to understand exactly how you want to call your script (i.e. to handle return codes, output to stdout and stderr, etc)
import subprocess
subprocess.call(["python", "C:/hello.py"])
(2) If there is a specific function in this script that you could call, then you could add the directory containing the python script to sys.path, and then import the script and call the relevant function. This is detailed in this stack overflow question, and would be arguably the cleaner approach (As a sidenote, would advise moving hello.py to a more suitable location, the root of your C: drive probably isn't the right place to store scripts).
import sys
sys.path.append("C:/")
from hello import function_to_call
function_to_call()
If you are struggling to put together the web page that allows you to display the button and react to the button press by calling the script, it would be advisable to work through the excellent Django tutorial writing your first Django application.

Django Import Model Error

I have Created an App inside my project folder, in the same directory where manage.py exists.
i have also created model for my app, when i import it in python shell like Import Poll
it gives this error:
ImportError: No module named poll
Supposing your app name is 'App' you have to type:
from App.models import Poll
in order to successfully import your Poll model. Change App with your current application name
Also, two things to bear in mind
1) Poll is different from poll: check that your capitalization is consistent with your model definition
2) You should have created the app using django startapp command. If not, at least make sure you have an empty init.py file inside your App folder.

Django ImportError while adding guardian module

Being a beginner of using Django, i am trying to add some module for the purpose of testing Django, but I've got a problem regarding the importError which I've googled for solution with no success. Below is my situation
The project is created to my PC J:\ while the python package is installed on C:. According to guardian's installation guide following code have to be added in django's backend:
AUTHENTICATION_BACKENDS = (
'django.contrib.auth.backends.ModelBackend', # default
'guardian.backends.ObjectPermissionBackend',)
The problem's come, when I put the guardian's app under the directory of mysite, configurate the install_apps setting with 'guardian' and start syncdb, the error claim as below which i believe that it is because the django's filw do not understand what is "guradian" really is
File "J:\mysite\guardian\conf\settings.py", line 6, in
raise ImproperlyConfigured("In order to use django-guardian's "
django.core.exceptions.ImproperlyConfigured: In order to use django-guardian's O
bjectPermissionBackend authorization backend you have to configure ANONYMOUS_USE
R_ID at your settings module
So, I move the 'guardian' folder under Django's contrib folder, adding the sys path and configurate the install_app setting with 'django.contrib.guardian'. However, I end up with the importerror.
As it seems from the error message, you need to add the user id for anonymous user for you site.
Create a user (named maybe anonymous) and put the id of user in the settings.py file.
Obtain the user id from the database using the shell.
Put the id in the settings file:
ANONYMOUS_USER_ID = <Your anonymous USER_ID>
EDIT:
Just looked through the documentation of the django-guardian app. It also specifies this:
http://packages.python.org/django-guardian/configuration.html