manage.py shell and relative imports - django

I'm trying to load the following Python file with "manage.py shell". The manage.py script is in a parent directory and I'm using execfile('forms.py') from the directory containing the script.
from django.forms import ModelForm
from .models import Profile
class ProfileSearchForm(ModelForm):
class Meta:
model = Profile
fields = ['name']
This fails because of the explicit relative import:
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "forms.py", line 2, in <module>
from .models import Profile
ImportError: No module named models
but if I switch to implicit relative import, it works:
from django.forms import ModelForm
from apps.myprofile.models import Profile
class ProfileSearchForm(ModelForm):
class Meta:
model = Profile
fields = ['name']
My problem is that I thought that explicit relative imports are a good thing (see Two Scoops), and I still think they are.
But now I need a workaround with manage.py.

you need to change the current directory before the relative import in python shell. So this may works:
import os
os.chdir('apps/')
from django.forms import ModelForm
from .models import Profile

Related

ModuleNotFoundError for model class in django

I ran into the following ModuleNotFoundError error.
File "C:\django-project\CodingWithMitchBlog\demoproject\Blog\api\urls.py", line 3, in <module>
from demoproject.Blog.api.views import api_detail_BlogPost_view
ModuleNotFoundError: No module named 'demoproject.Blog'
'Blog' is my appname.
This is my project structure.
This might be due to incorrect import statements used in the files. If the import statements has the projectname prefixed try removing it and run again.
For example change:
from demoproject.Blog.models import ModelClass
to
from Blog.models import ModelClass
in the urls.py file

Django-inline-media get_model error

I am using Django 1.9 and for my project I need django-inline-media. I have done all stuff properly as per documentation. But I get this error.
File "/home/sifat/PycharmProjects/fear/profiles/models.py", line 3, in <module>
from inline_media.fields import TextFieldWithInlines
File "/home/sifat/PycharmProjects/fear/env/local/lib/python2.7/site- packages/inline_media/fields.py", line 4, in <module>
from django.db.models import fields, get_model
ImportError: cannot import name get_model
Now what to do? As it is error from a library
django.db.models.get_model has been deprecated in Django 1.7 and was removed in 1.9.
In Django 1.9, you can replace it with
from django.apps import apps
model = apps.get_model('app_name', 'model_name')

Django 1.9 and django.contrib.auth

I don't have django.contrib.auth in INSTALLED_APPS, and I don't want to do it because I'm using a custom user model and I don't need none of the builtin User, Group and Permission models.
I was hoping this was possible in Django 1.9, as the docs state in https://docs.djangoproject.com/en/1.9/releases/1.9/ under the django.contrib.auth section that:
AbstractBaseUser and BaseUserManager were moved to a new django.contrib.auth.base_user module so that they can be imported without including django.contrib.auth in INSTALLED_APPS (doing so raised a deprecation warning in older versions and is no longer supported in Django 1.9).
However, as of now I can't import anything from django.contrib.auth without raising errors. No middleware or form can be imported. I have to either add django.contrib.auth to INSTALLED_APPS or don't use anything from that module.
Whenever a model in django.contrib.auth is indirectly imported I get the classic error that: whatever_model_was_indirectly_imported doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS.
EDIT: Including last part of the traceback:
...
File "/usr/lib/python2.7/site-packages/django/contrib/auth/middleware.py", line 3, in <module>
from django.contrib.auth.backends import RemoteUserBackend
File "/usr/lib/python2.7/site-packages/django/contrib/auth/backends.py", line 4, in <module>
from django.contrib.auth.models import Permission
File "/usr/lib/python2.7/site-packages/django/contrib/auth/models.py", line 38, in <module>
class Permission(models.Model):
File "/usr/lib/python2.7/site-packages/django/db/models/base.py", line 102, in __new__
"INSTALLED_APPS." % (module, name)
RuntimeError: Model class django.contrib.auth.models.Permission doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS.
Any workarounds?
It looks like the only workaround as of now is including django.contrib.auth in INSTALLED_APPS and ignoring the three tables in database.

Attribute error while implementing filter in django manager

I have a manager in my django project and am implementing a filter as below.
I start the django shell and get this error:
>>> from django.http import HttpRequest
>>> r=HttpRequest()
>>> r.session=()
>>> from movierating.models import *
>>> RatingModel.statManager.RatingTimeLine(r)
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/data/dashapp/movierating/managers.py", line 27, in RatingTimeLine
(data,display,err)=self.getdatacache(request)
File "/data/dashapp/movierating/managers.py", line 11, in getdatacache
filterDict=request.session.get('RatingFilter',{})
AttributeError: 'tuple' object has no attribute 'get'
>>> from django.http import HttpRequest
>>> r=HttpRequest()
>>> r.session()
Traceback (most recent call last):
File "<console>", line 1, in <module>
AttributeError: 'HttpRequest' object has no attribute 'session'r code here
The file manager.py looks like this:
import json,datetime
from django.db import models
from django.db.models import *
from pandas import *
from urllib import urlencode
import hashlib
from django.core.cache import cache
from web.extras import *
class RatingManager(models.Manager):
def getdatacache(self,request):
filterDict=request.session.get('RatingFilter',{})
(fapply,display,err)=normalizeFilter(self.model,filterDict)
cache_id=urlencode(fapply.items())
cache_id=hashlib.md5('RatingFilter'+cache_id).hexdigest()
data=None
if data==None:
res=self.model.objects.order_by('date').filter(**fapply).values('date').annotate(
RatingCounts = Count('rating'),
RatingSum = Sum('rating'),
)
data=DataFrame(list(res))
data['AverageRating']=data['RatingSum']/data['RatingCounts']
cache.set(cache_id,data)
return (data,display,err)
def RatingTimeLine(self,request):
jsondata={}
jsondata['chartconfig']={}
jsondata['chartconfig']['title']="Average Movie Rating per Day"
jsondata['chartconfig']['names']=['AverageRating']
(data,display,err)=self.getdatacache(request)
jsondata['chartconfig']['errors']="<br/>".join(err)
jsondata['chartconfig']['subtitle']="<br/>".join(display)
jsondata['series']=data[['data','AverageRating']].values.tolist()
data=json.dumps(jsondata,cls = SeriesEncoder)
return {'data':data}
I have this model in my models.py:
class RatingModel(models.Model):
movie=models.ForeignKey(MovieModel)
user=models.ForeignKey(userModel)
rating=models.IntegerField()
date=models.DateField()
objects=models.Manager() #default manager
statManager=RatingManager() #new manager class
# FilterMapping={
#'movie':'movie__name', #django relational
# }
def __unicode__(self):
return "id: %d rating for movie is %s" %(self.id,self.movie.name) #relationships
class Meta:
app_label = 'movierating'
db_table = 'rating'
What could be the possible error in this line?
filterDict=request.session.get('RatingFilter',{})
In your third line you say r.session=() - that is, you're assigning an empty tuple to r.session. Your code later tries to call get() on this tuple, which isn't a supported operation.
I'm not sure what you're trying to do here. request.session is normally filled in by the session middleware. If you're trying to test your code programmatically, you might want to look into the Django testing framework, which supports sessions.

Cron job for Django File

I want to setup a Cron job to run a django file.
What I want to know is django-cron a good option for this? i.e. or are there any other apps that can be used?
If no, how to run a django file through command line ?
admin#ADMIN-PC ~/workspace/bolt (master)
$ python ./log/cron.py
Traceback (most recent call last):
File "./log/cron.py", line 3, in <module>
from account.models import UserProfile
ImportError: No module named account.models
I have set the following variable
admin#ADMIN-PC ~/workspace/bolt (master)
$ export DJANGO_SETTINGS_MODULE=settings
I keep getting these errors as the files that are being referenced have direct imports
from foo.models import *
Any help will be highly appreciated.
Custom Command
from django.core.management.base import BaseCommand, CommandError
import pdb
import datetime
from too.models import UserProfile
from foo.api import end_all_foo_conversations
class Command(BaseCommand):
# in minutes
def handle(self,*args,**options):
print datetime
The error I am getting while trying to run the command is as follows:-
'queryset': self.rel.to._default_manager.using(db).complex_fi
imit_choices_to),
AttributeError: 'str' object has no attribute '_default_manager'
I think you should write a custom management command and run it through manage.py.