Calling a model's method from outside Django - django

I have a Django model with some static methods. I'd like to call the methods from outside the application (cronjob).
The model I have:
class Job(models.Job):
#Irrelevant information
#staticmethod
def methodIwantToCall():
#statements
I have the following python file that I'm using for the cron job:
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import os
os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'
from myapp.models import Job
Job.methodIwantToCall()
At first, I was having an error about DJANGO_SETTINGS_MODULE not being set and I fixed that, however, now I have the following error: No module named myapp.utils
I feel like I'm doing something that I'm not supposed to do. So how do I call that static method the way I want it to be called?
EDIT: It looks like the paths are getting messed up when I'm importing from outside Django. For example, I have an import in my models file, when I call the cron file it fails importing with the message ImportError: No module named myapp.utils even though it's working.

The proper solution is to create custom manage.py command.

Assuming your cron job code resides in the same directory as your settings file, use the following setup code at the beginning:
from django.core.management import setup_environ
import settings
setup_environ(settings)

Related

ModuleNotFoundError: No module named 'register'

I am working on a Django project. I am working on the register page. When I try to import my register/views.py to my mysite/urls.py file I get an error message. ModuleNotFoundError: No Module named 'register'. Both files are are in the same directory.
from django.contrib import admin
from django.urls import path, include
from register import views as v
Adding full exception message
Try the following:-
from . import views
Please add a blank __init__.py file in the register folder.
Only then python will understand that register is an importable package
Edit:
After seeing the exception, it looks like a working directory issue in pycharms. Please try the fix mentioned in this link

Django+Cython import cython module in django app views [duplicate]

This question already has an answer here:
Python Package "No module named..."
(1 answer)
Closed 2 years ago.
a newbie to django and Cython. I am creating an app in django and need to import function in views.py from cythonized module. following is views.py inside my app.
from django.shortcuts import render
import sys
import numpy as np
import random
import math
from cython_node_val import node_val
def home(request):
return render(request,'Home.html',{"name":"user"})
def shortest_path1(request):
K=int(request.POST['number of layers'])
if ((K%2!=0) or (K < 0)):
return render(request,"shortest_path1.html",{'shortest_path1':"K must be an even integer"})
else:
......
Node_val=node_val(Hash,C,K) #node_val is from cython_node_val which is a .pyx file, Hash C and K
are defined in body after else statement.
sPath=np.zeros((K,3))
sPath[K-1,:]=Node_val[n-1,:]
for m in range(K-2,-1,-1):
sPath[m,:]=Node_val[int(sPath[m+1,1])]
return render(request,"shortest_path1.html",{'shortest_path1':sPath[:,3]})'''
the directory of my project is like following:
my app directory looks like this
cython_node_val.pyx works fine when importing into a normal .py file, but when doing the same inside views.py in my app it throws me following error
File "C:\Users\amit\projects\application_shortest_path\shortest_path\DS2P\urls.py", line 9, in <module>
from . import views
File "C:\Users\amit\projects\application_shortest_path\shortest_path\DS2P\views.py", line 6, in <module>
from cython_node_val import node_val
ModuleNotFoundError: No module named 'cython_node_val'
I believe if views.py is a python file and we can do operations, it should pull cython_node_val and associated functions. Where am i wrong?
Thanks for your time.
Use os.getcwd() to debug where you are running from your script views.py:
import os
print(os.getcwd())
ModuleNotFoundError: No module named 'cimport'
Then adjust the path to your needs
Is usually an error when you are trying to reference something that isn't in the python running path script + the path that you are giving inside your script.

Debugging while developing Django apps

I'm aware of pdb built-in Python library for debugging Python programs and scripts. However, you can't really use it for debugging Django apps (I get errors when I try to use it in views.py). Are there any tools that I can use when Django's traceback isn't helpful ?
EDIT:
from .forms import TestCaseForm, TestCaseSuiteForm
from .models import TestCase, TestSuite
from django.contrib.auth.forms import UserCreationForm
from django.views.generic import FormView, ListView
from django.contrib.auth.models import User
from django.utils.decorators import method_decorator
from django.contrib.auth.decorators import login_required
from django.contrib.auth import logout
import pdb
class ListAllTestSuites(ListView):
template_name = 'list.html'
context_object_name = 'username'
def get_queryset(self):
pdb.set_trace() # <-- setting a trace here to diagnose the code below
queryset = {'test_suites': TestSuite.objects.filter(user=self.request.user),
'username': self.request.user}
return queryset
you forgot the exact error message and full traceback, and, more importantly, you forgot to explain how you executed this code to get this result...
But anyway: from the error message, you're obviously trying to execute your view file as a plain python script (cf the reference to __main__). This cannot work. A view is a module, not a script, and, moreover, any module dependending on Django needs some setup done to be imported (which is why we use the django shell - ./manage.py shell - instead of the regular Python one).
For most case, you can just launch the django shell, import your module and use pdb.runcall() to execute some function / method under the debugger (no need to put a breakpoint then, but that's still possible).
Now views require a HTTPRequest as first argument which make them a bit more cumbersome to debug that way (well, there is django.tests.RequestFactory but still...), so your best bet here is to set your breakpoint, launch your devserver (or restart it - if it didn't already did, as it should), point your browser to the view's url, and then you should see the debugger's prompt in your devserver's terminal.

django import client

i am trying to import the client in django for testing. but when i do, i get this wierd error:
ImproperlyConfigured: Requested setting DATABASES, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.
from django.utils import unittest
from django.utils import simplejson as json
from django.test.client import Client
this is how i imported the client so that i could use it for testing. can someone explain this to me please.
Try this:
import os
import sys
sys.path.append('/home/username/www/site_folder')
os.environ['DJANGO_SETTINGS_MODULE'] = 'project.settings'
from django.utils import unittest
from django.utils import simplejson as json
from django.test.client import Client
But replace project with folder name, where your settings.py is
The Client is looking for the settings.py. You could simply load the client by typing this in your project folder:
python manage.py shell
In Pycharm which I use, after following this Running Django tests in PyCharm
my problem was solved.
It's in the file > settings > Django Support, and then select the right settings.

Could not import/No module named Django Error with Apache

I had a small proof of concept set up on a development server on a local machine. I'm now trying to move it over to django on a production server, which I'm using webfaction for. However, now that I'm switched over to apache from the built in django server I get the following:
ViewDoesNotExist: Could not import orgDisplay.views. Error was: No module named orgDisplay.views
But when check my orgDisplay apps folder there is a view.py in it. What am I doing wrong? I've tried adding the following to my settings.py by suggestion of the django IRC room.
import sys
sys.path.append(r"/home/user/webapps/django_project/myproject/orgDisplay")
which is the path to my app.
any ideas on how to even begin to trouble shoot this?
Thanks in advance.
I assume you're using mod_wsgi (which is recommended by Django authors), not mod_python. This is the way you should use your sys.path:
django.wsgi:
import os, sys
sys.path.append(r"/home/user/webapps/django_project/myproject/")
os.environ["DJANGO_SETTINGS_MODULE"] = "settings"
sys.stdout = sys.stderr # Prevent crashes upon print
import django.core.handlers.wsgi
application = django.core.handlers.wsgi.WSGIHandler()
urls.py:
from django.conf.urls.defaults import *
urlpatterns = (
("", include("orgDisplay.urls")),
# ...
)
orgDisplay/urls.py:
import views
urlpatterns = (
(r'^some_view/$', views.some_view), # It is actually orgDisplay.views.some_view
# many more records ...
)
It is a bad idea to add project dir itself to path since you're be getting name conflicts between multiple projects.
I think you're appending the wrong directory to sys.path. I think Python is looking in the .../myproject/orgDisplay folder for the orgDisplay package. Try removing the orgDisplay from your string, like this:
import sys
sys.path.append(r"/home/user/webapps/django_project/myproject")
The other option would be to simply add myproject (or whatever your project is actually called) in the import statement.
# instead of "from orgDisplay import views"
from myproject.orgDisplay import views
Also, make sure to restart Apache after every edit.
looking at manage.py, it does it like so:
import sys
from os.path import abspath, dirname, join
from django.core.management import setup_environ
# setup the environment before we start accessing things in the settings.
setup_environ(settings_mod)
sys.path.insert(0, join(PINAX_ROOT, "apps"))
sys.path.insert(0, join(PROJECT_ROOT, "apps"))
Provided your WSGI file is in your project directory, a slightly more flexible way is this:
import os, sys
sys.path.append(os.path.dirname(__file__))
This will enable you to change your project location later without having to modify your WSGI file.