unbound method must be called with instance as first argument - django

I'm working with django and i'm getting this error: "unbound method create() must be called with SocialUrl instance as first argument (got nothing instead)". I've read several answers to the same problem here but i'm not sure they are doing the same thing wrong as i am.
Here is the Model containing the method i'm trying to call:
from django.db import models
class SocialUrl(models.Model):
code = models.CharField(max_length=30)
def create():
socialUrl = SocialUrl(code = generateCode())
socialUrl.save()
return socialUrl
def __unicode__(self):
return self.code
and here is the method trying to call SocialUrl.create():
from django.shortcuts import render
from django.template import RequestContext
from .general import generateCode
from .models import SocialUrl
def test(request):
socialUrl = SocialUrl.create()
#print(SocialUrl.objects.all())
return render(request, 'test.html', RequestContext(request, {"title": socialUrl.code}))
Here is the stacktrace:
Environment:
Request Method: GET
Request URL: http://127.0.0.1:8000/su/asdadsf
Django Version: 1.6.2
Python Version: 2.7.6
Installed Applications:
('django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'SocialUrl')
Installed Middleware:
('django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware')
Traceback:
File "C:\Users\Sverker\.virtualenvs\coomba\lib\site- packages\django\core\handlers\base.py" in get_response
114. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\Sverker\Dropbox\Coomba\SbrgCoomba\SocialUrl\views.py" in test
8. socialUrl = SocialUrl.create()
Exception Type: TypeError at /su/asdadsf
Exception Value: unbound method create() must be called with SocialUrl instance as first argument (got nothing instead)
Help would be appreciated :)

You need to instantiate the class before calling a method on the class. Change your view to:
from django.shortcuts import render
from django.template import RequestContext
from .general import generateCode
from .models import SocialUrl
def test(request):
socialUrl = SocialUrl()
socialUrl.create()
#print(SocialUrl.objects.all())
return render(request, 'test.html', RequestContext(request, {"title": socialUrl.code}))
Notice how you instantiate the object first (socialUrl = SocialUrl()) then you run create on the object you've instantiated. (socialUrl.create()).
However, I'm not sure your create method is going to work as you intend. What are you trying to accomplish with the create method?
EDIT to address comments:
I'm not familiar with Java static methods, but I think the standard way to what you want to do is as follows:
First, define your model as you've done. Note that I removed the create method.
from django.db import models
class SocialUrl(models.Model):
code = models.CharField(max_length=30)
def __unicode__(self):
return self.code
Then, in your views, instantiate a model and populate it with the attributes you want.
from django.shortcuts import render
from django.template import RequestContext
from .general import generateCode
from .models import SocialUrl
def test(request):
my_code = generateCode()
socialUrl = SocialUrl()
socialUrl.code = my_code # Setting code attribute to the result of your generateCode function
socialUrl.save() # Saves instance of SocialUrl to database.
return render(request, 'test.html', RequestContext(request, {"title": socialUrl.code}))

Related

Django - Render is not working in my project

I am dealing with form like 1 week but couldn't solve my issue. Probably i overlook something that can be found easy by other eyes, but totally, i don't know what to do. I recognize problem by starting build form. I had to use render for form and it failed in every try. I am able to connect db and showing data in html pages but whenever i use render instead of render_to_response it is failing. And i had to use render for post request as i know. Not only for form, render is not working for all. Even for a simple: def home(request): context = {'foo': 'bar'} return render(request, 'main.html', context)
models.py
class ModuleNames(models.Model):
ModuleName = models.CharField(max_length = 50)
ModuleDesc = models.CharField(max_length = 256)
ModuleSort = models.SmallIntegerField()
isActive = models.BooleanField()
ModuleType = models.ForeignKey(ModuleTypes, on_delete=models.CASCADE, null = True)
slug = models.SlugField(('ModuleName'), max_length=50, blank=True)
class Meta:
app_label = 'zz'
def __unicode__(self):
return self.status
forms.py
from django import forms
from MyApp.models import ModuleNames
class ModuleForm(forms.ModelForm):
moduleName = forms.CharField(label='Module Name', max_length=50)
ModuleDesc = forms.CharField(max_length = 256)
ModuleSort = forms.IntegerField()
isActive = forms.BooleanField()
ModuleType = forms.IntegerField()
class Meta:
model = ModuleNames
fields =('moduleName','ModuleDesc','ModuleSort','isActive','ModuleType')
view.py
from django.views.generic import TemplateView
from django.shortcuts import render,render_to_response, redirect
from django.template import RequestContext
import json
from django.core.serializers.json import Serializer
from django.http import HttpResponse, Http404, HttpResponseRedirect
from urllib.parse import urlparse
from django.urls import resolve
from django.db import connection
from collections import namedtuple
from django.db.models import F
from django.views.decorators.cache import cache_page
from django.views.decorators.csrf import csrf_protect
from MyApp.models import ModuleNames
from MyApp.forms import ModuleForm
def AddNewModule(request):
template_name = 'addnewmodule.html'
if request.method == 'GET':
form = ModuleForm()
posts = ModuleNames.objects.all()
args = {'form': form, 'posts': posts }
return render(request, template_name, args) #This part is showing data when i use render_to_response. But after clicking Save button on html page, it will give below first error.
if request.method == 'POST':
form = ModuleForm(request.POST)
if form.is_valid():
form.pop('csrfmiddlewaretoken', None)
post = form.save(commit=False)
post.save()
text = form.cleaned_data['post']
form = ModuleForm()
args = {'form': form, 'text': text}
return render(request, template_name, args)
Error that i have when using render_to_response
Forbidden (403)
CSRF verification failed. Request aborted.
Help
Reason given for failure:
CSRF token missing or incorrect.
Error when i use render for any function
Environment:
Request Method: GET
Request URL: http://127.0.0.1:8000/addnewmodule
Django Version: 2.1.3
Python Version: 3.7.1
Installed Applications:
['MyApp',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware']
Traceback:
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/handlers/exception.py" in inner
34.response = get_response(request)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/handlers/base.py" in _get_response
126.response = self.process_exception_by_middleware(e, request)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/handlers/base.py" in _get_response
124.response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Users/Cem/Documents/Projects/Python/Web/FirstApp/MyApp/views.py" in addnewmodule
132.return render(request, template_name, args)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/shortcuts.py" in render
36.content = loader.render_to_string(template_name, context, request, using=using)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/template/loader.py" in render_to_string
62.return template.render(context, request)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/template/backends/django.py" in render
61.return self.template.render(context)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/template/base.py" in render
169.with context.bind_template(self):
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/contextlib.py" in __enter__
112.return next(self.gen)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/template/context.py" in bind_template
246.updates.update(processor(self.request))
Exception Type: TypeError at /addnewmodule
Exception Value: 'module' object is not callable
Read about CSRF tokens in django, it's used for site protection/
You are missing the the csrf_token in your addnewmodule.html form, so,
you can get back to addnewmodule.html form and add the {% csrf_token %}just below the tag form action="" method="POST" like this
<form action="" method="POST">
{% csrf_token %}

Django exception middleware: TypeError: object() takes no parameters

I'm using Django 1.10 and trying to catch all exceptions with exception middleware.
The code below causes an internal server error:
mw_instance = middleware(handler)
TypeError: object() takes no parameters
views.py
from django.http import HttpResponse
def my_view(request):
x = 1/0 # cause an exception
return HttpResponse("ok")
settings.py
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'myproject.middleware.ExceptionMiddleware',
]
middleware.py
from django.http import HttpResponse
class ExceptionMiddleware(object):
def process_exception(self, request, exception):
return HttpResponse("in exception")
I have seen these object() takes no parameters in django 1.10 and other questions talking about middleware versus middleware_classes, but I'm not sure how that applies to this case, or what I'd actually need to change to fix the issue.
Since you are using the new MIDDLEWARE settings, your Middleware class must accept a get_response argument: https://docs.djangoproject.com/en/1.10/topics/http/middleware/#writing-your-own-middleware
You could write your class like this:
from django.http import HttpResponse
class ExceptionMiddleware(object):
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
return self.get_response(request)
def process_exception(self, request, exception):
return HttpResponse("in exception")
You could also use the MiddlewareMixin to make your Middleware compatible with pre-1.10 and post-1.10 Django versions: https://docs.djangoproject.com/en/1.10/topics/http/middleware/#upgrading-pre-django-1-10-style-middleware
from django.http import HttpResponse
from django.utils.deprecation import MiddlewareMixin
class ExceptionMiddleware(MiddlewareMixin):
def process_exception(self, request, exception):
return HttpResponse("in exception")
in the newer version of Django, the middleware should be written like this
import datetime
from django.core.cache import cache
from django.conf import settings
from django.utils.deprecation import MiddlewareMixin
class ActiveUserMiddleware(MiddlewareMixin):
def process_request(self, request):
current_user = request.user
if request.user.is_authenticated:
now = datetime.datetime.now()
cache.set('seen_%s' % (current_user.username), now,
settings.USER_LASTSEEN_TIMEOUT)

Django: NoReverseMatch Error production_id: None

Having an issue where I would fill out the form and when I click to save the input, it would show the info submitted into the query but my production_id value would return as None.
Here is the error:
Environment:
Request Method: POST
Request URL: http://192.168.33.10:8000/podfunnel/episodeinfo/
Django Version: 1.9
Python Version: 2.7.6
Installed Applications:
('producer',
'django.contrib.admin',
'django.contrib.sites',
'registration',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'storages',
'django_extensions',
'randomslugfield',
'adminsortable2',
'crispy_forms')
Installed Middleware:
('django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django.middleware.security.SecurityMiddleware')
Traceback:
File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py" in get_response
149. response = self.process_exception_by_middleware(e, request)
File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py" in get_response
147. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/views/generic/base.py" in view
68. return self.dispatch(request, *args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/contrib/auth/mixins.py" in dispatch
56. return super(LoginRequiredMixin, self).dispatch(request, *args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/views/generic/base.py" in dispatch
88. return handler(request, *args, **kwargs)
File "/home/vagrant/fullcast_project/producer/views/pod_funnel.py" in post
601. return HttpResponseRedirect(reverse('podfunnel:episodeimagefiles', kwargs={'production_id':production_id}))
File "/usr/local/lib/python2.7/dist-packages/django/core/urlresolvers.py" in reverse
600. return force_text(iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs)))
File "/usr/local/lib/python2.7/dist-packages/django/core/urlresolvers.py" in _reverse_with_prefix
508. (lookup_view_s, args, kwargs, len(patterns), patterns))
Exception Type: NoReverseMatch at /podfunnel/episodeinfo/
Exception Value: Reverse for 'episodeimagefiles' with arguments '()' and keyword arguments '{'production_id': None}' not found. 1 pattern(s) tried: [u'podfunnel/episodeimagefiles/(?P<production_id>[0-9]+)/$']
Here is my pod_funnel.py view:
from django.http import HttpResponseRedirect, Http404, HttpResponseForbidden
from django.shortcuts import render, get_object_or_404
from django.views.generic import View, RedirectView, TemplateView
from django.contrib.auth.decorators import login_required
from django.contrib.auth.mixins import LoginRequiredMixin
from .forms.client_setup import ClientSetupForm
from .forms.podcast_setup import PodcastSetupForm
from .forms.episode_info import EpisodeInfoForm
from .forms.image_files import EpisodeImageFilesForm
from .forms.wordpress_info import EpisodeWordpressInfoForm
from .forms.chapter_marks import EpisodeChapterMarksForm
from .forms.show_links import ShowLinksForm
from .forms.tweetables import TweetablesForm
from .forms.clicktotweet import ClickToTweetForm
from .forms.schedule import ScheduleForm
from .forms.wordpress_account import WordpressAccountForm
from .forms.wordpress_account_setup import WordpressAccountSetupForm
from .forms.wordpress_account_sortable import WordpressAccountSortableForm
from .forms.soundcloud_account import SoundcloudAccountForm
from .forms.twitter_account import TwitterAccountForm
from producer.helpers import get_podfunnel_client_and_podcast_for_user
from producer.helpers.soundcloud_api import SoundcloudAPI
from producer.helpers.twitter import TwitterAPI
from django.conf import settings
from producer.models import Client, Production, ChapterMark, ProductionLink, ProductionTweet, Podcast, WordpressConfig, Credentials, WordPressSortableSection, \
TwitterConfig, SoundcloudConfig
from django.core.urlresolvers import reverse
from producer.tasks.auphonic import update_or_create_preset_for_podcast
class EpisodeInfoView(LoginRequiredMixin, View):
form_class = EpisodeInfoForm
template_name = 'pod_funnel/forms_episode_info.html'
def get(self, request, *args, **kwargs):
initial_values = {}
user = request.user
# Lets get client and podcast for the user already. if not existent raise 404
client, podcast = get_podfunnel_client_and_podcast_for_user(user)
if client is None or podcast is None:
raise Http404
# See if a production_id is passed on the kwargs, if so, retrieve and fill current data.
# if not just provide empty form since will be new.
production_id = kwargs.get('production_id', None)
if production_id:
production = get_object_or_404(Production, id=production_id)
# Ensure this production belongs to this user, if not Unauthorized, 403
if production.podcast_id != podcast.id:
return HttpResponseForbidden()
initial_values['production_id'] = production.id
initial_values['episode_number'] = production.episode_number
initial_values['episode_title'] = production.episode_title
initial_values['episode_guest_first_name'] = production.episode_guest_first_name
initial_values['episode_guest_last_name'] = production.episode_guest_last_name
initial_values['episode_guest_twitter_name'] = production.episode_guest_twitter_name
initial_values['episode_summary'] = production.episode_summary
form = self.form_class(initial=initial_values)
return render(request, self.template_name, {'form': form})
def post(self, request, *args, **kwargs):
form = self.form_class(request.POST)
client, podcast = get_podfunnel_client_and_podcast_for_user(request.user)
if form.is_valid():
# lets get the data
production_id = form.cleaned_data.get('production_id')
episode_number = form.cleaned_data.get('episode_number')
episode_title = form.cleaned_data.get('episode_title')
episode_guest_first_name = form.cleaned_data.get('episode_guest_first_name')
episode_guest_last_name = form.cleaned_data.get('episode_guest_last_name')
episode_guest_twitter_name = form.cleaned_data.get('episode_guest_twitter_name')
episode_summary = form.cleaned_data.get('episode_summary')
#if a production existed, we update, if not we create
if production_id is not None:
production = Production.objects.get(id=production_id)
else:
production = Production(podcast=podcast)
production.episode_number = episode_number
production.episode_title = episode_title
production.episode_guest_first_name = episode_guest_first_name
production.episode_guest_last_name = episode_guest_last_name
production.episode_guest_twitter_name = episode_guest_twitter_name
production.episode_summary = episode_summary
production.save()
return HttpResponseRedirect(reverse('podfunnel:episodeimagefiles', kwargs={'production_id':production_id}))
return render(request, self.template_name, {'form': form})
episode_info.py form:
from django import forms
class EpisodeInfoForm(forms.Form):
production_id = forms.IntegerField(widget=forms.Field.hidden_widget, required=False)
episode_number = forms.IntegerField(widget=forms.NumberInput, required=True)
episode_title = forms.CharField(max_length=255, required=True)
episode_guest_first_name = forms.CharField(max_length=128)
episode_guest_last_name = forms.CharField(max_length=128)
episode_guest_twitter_name = forms.CharField(max_length=64)
episode_summary = forms.CharField(widget=forms.Textarea)
And url.py:
from django.conf.urls import url
from django.views.generic import TemplateView
import producer.views.pod_funnel as views
urlpatterns = [
url(r'^dashboard/', views.dashboard, name="dashboard"),
url(r'^clientsetup/', views.ClientSetupView.as_view(), name="clientsetup"),
url(r'^podcastsetup/', views.PodcastSetupView.as_view(), name="podcastsetup"),
url(r'^episodeinfo/$', views.EpisodeInfoView.as_view(), name="episodeinfo"),
url(r'^episodeinfo/(?P<production_id>[0-9]+)/$', views.EpisodeInfoView.as_view(), name="episodeinfo_edit"),
url(r'^episodeimagefiles/(?P<production_id>[0-9]+)/$', views.EpisodeImageFilesView.as_view(), name="episodeimagefiles"),
Any suggestion would be appreciated.
It looks like production_id can be None in your view, in which case you can't use it when you call reverse. It would be better to use production.id instead. You have just saved the production in your view, so production.id will be set.
return HttpResponseRedirect(reverse('podfunnel:episodeimagefiles', kwargs={'production_id':production.id}))
Note that you can simplify this line by using the redirect shortcut. Add the import,
from django.shortcuts import redirect
then change the line to
return redirect('podfunnel:episodeimagefiles', production_id=production.id)
You can't always redirect to episodeimagefiles if you didn't provide appropriate initial value for production_id:
# See if a production_id is passed on the kwargs, if so, retrieve and fill current data.
# if not just provide empty form since will be new.
production_id = kwargs.get('production_id', None) <-- here you set production_id variable to None if no `production_id` in kwargs
Look at your exception:
Exception Value: Reverse for 'episodeimagefiles' with arguments '()' and keyword arguments '{'production_id': None}' not found. 1 pattern(s) tried: [u'podfunnel/episodeimagefiles/(?P<production_id>[0-9]+)/$']
It means you passed None value for production_id variable, but episodeimagefiles pattern required some int value to resolve url, so it raises NoReverseMatch exception.
Your form is valid in EpisodeInfoView.post because you set required=False for production_id attribute in your form:
class EpisodeInfoForm(forms.Form):
production_id = forms.IntegerField(widget=forms.Field.hidden_widget, required=False)
I guess, if you debug your generated form before submit it, you can see something like <input type="hidden" name="production_id" value="None" />

django name render is not defined

I have an error when I try to import render in my program and I fear it is because it is not supported in django 1.9.
I am using python 3.4 and django 1.9.
When I try to run my server, I have the error:
ImportError: cannot import name render`.
Here is my code:
blog/views:
from datetime import datetime
from django.shortcuts import render
def date_actuelle(request):
return render(request, 'blog/date.html', {'date': datetime.now()})
def addition(request, nombre1, nombre2):
total = int(nombre1) + int(nombre2)
# Retourne nombre1, nombre2 et la somme des deux au tpl
return render(request, 'blog/addition.html', locals())
blog/urls:
from django.conf.urls import url, patterns
from . import views
urlpatterns = [
# url(r'^accueil/$', views.home),
# url(r'^article/(?P<id_article>\d+)$', views.view_article),
# url(r'^article/(?P<year>\d{4})/(?P<month>\d{2})$', views.list_articles),
# url(r'^redirection$', views.view_redirection),
url(r'^date/$', views.date_actuelle),
url(r'^addition/(?P<nombre1>\d+)/(?P<nombre2>\d+)/$', views.addition),
]
creps_bretonnes.urls:
from django.conf.urls import patterns, include, url
from django.contrib import admin
from blog import views
urlpatterns = [
url(r'^blog/', include('blog.urls')),
]
I have also tried from django.shortcuts import *, then the server is launched but when I try to access the page it says NameError: name 'render' is not defined.
Would you have an idea?
What is written on the server when I run it:
cmd values when trying to run the server with from django.shortcuts import render
traceback when using from django.shortcuts import * and trying to access localhost:8000/blog/date
Environment:
Request Method: GET
Request URL: http://localhost:8000/blog/date/
Django Version: 1.9.7
Python Version: 3.4.4
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware']
Traceback:
File "C:\Python34\lib\site-packages\django\core\handlers\base.py" in get_response
149. response = self.process_exception_by_middleware(e, request)
File "C:\Python34\lib\site-packages\django\core\handlers\base.py" in get_response
147. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\sperney\Documents\Travail\creps_bretonnes\blog\views.py" in date_actuelle
37. return render(request, 'blog/date.html', {'date': datetime.now()})
Exception Type: NameError at /blog/date/
Exception Value: name 'render' is not defined
here it is:
"""
This module collects helper functions and classes that "span" multiple levels
of MVC. In other words, these functions/classes introduce controlled coupling
for convenience's sake.
"""
from django.template import loader
from django.http import HttpResponse, Http404
from django.http import HttpResponseRedirect, HttpResponsePermanentRedirect
from django.db.models.manager import Manager
from django.db.models.query import QuerySet
from django.core import urlresolvers
def render_to_response(*args, **kwargs):
"""
Returns a HttpResponse whose content is filled with the result of calling
django.template.loader.render_to_string() with the passed arguments.
"""
httpresponse_kwargs = {'mimetype': kwargs.pop('mimetype', None)}
return HttpResponse(loader.render_to_string(*args, **kwargs), **httpresponse_kwargs)
def redirect(to, *args, **kwargs):
"""
Returns an HttpResponseRedirect to the apropriate URL for the arguments
passed.
The arguments could be:
* A model: the model's `get_absolute_url()` function will be called.
* A view name, possibly with arguments: `urlresolvers.reverse()` will
be used to reverse-resolve the name.
* A URL, which will be used as-is for the redirect location.
By default issues a temporary redirect; pass permanent=True to issue a
permanent redirect
"""
if kwargs.pop('permanent', False):
redirect_class = HttpResponsePermanentRedirect
else:
redirect_class = HttpResponseRedirect
# If it's a model, use get_absolute_url()
if hasattr(to, 'get_absolute_url'):
return redirect_class(to.get_absolute_url())
# Next try a reverse URL resolution.
try:
return redirect_class(urlresolvers.reverse(to, args=args, kwargs=kwargs))
except urlresolvers.NoReverseMatch:
# If this is a callable, re-raise.
if callable(to):
raise
# If this doesn't "feel" like a URL, re-raise.
if '/' not in to and '.' not in to:
raise
# Finally, fall back and assume it's a URL
return redirect_class(to)
def _get_queryset(klass):
"""
Returns a QuerySet from a Model, Manager, or QuerySet. Created to make
get_object_or_404 and get_list_or_404 more DRY.
"""
if isinstance(klass, QuerySet):
return klass
elif isinstance(klass, Manager):
manager = klass
else:
manager = klass._default_manager
return manager.all()
def get_object_or_404(klass, *args, **kwargs):
"""
Uses get() to return an object, or raises a Http404 exception if the object
does not exist.
klass may be a Model, Manager, or QuerySet object. All other passed
arguments and keyword arguments are used in the get() query.
Note: Like with get(), an MultipleObjectsReturned will be raised if more than one
object is found.
"""
queryset = _get_queryset(klass)
try:
return queryset.get(*args, **kwargs)
except queryset.model.DoesNotExist:
raise Http404('No %s matches the given query.' % queryset.model._meta.object_name)
def get_list_or_404(klass, *args, **kwargs):
"""
Uses filter() to return a list of objects, or raise a Http404 exception if
the list is empty.
klass may be a Model, Manager, or QuerySet object. All other passed
arguments and keyword arguments are used in the filter() query.
"""
queryset = _get_queryset(klass)
obj_list = list(queryset.filter(*args, **kwargs))
if not obj_list:
raise Http404('No %s matches the given query.' % queryset.model._meta.object_name)
return obj_list
Thanks a lot
Finaly I have deployed a virtual env (ubuntu) using virtual box.
I had absolutely no issues on the ubuntu env to deploy it and follow the steps with the exact same code as above!
Thanks for your help anyway!

Django import error: No module named models

I keep receiving the error Could not import movies.views. Error was: No module named models
Here is my traceback:
Environment:
Request Method: GET
Request URL: http://localhost:8000/movies/awesome-movie/
Django Version: 1.3.1
Python Version: 2.7.3
Installed Applications:
['django.contrib.auth',
'username_patch',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.admin',
'django.contrib.flatpages',
'south',
'tagging',
'tagging_autocomplete',
'accounts',
'movies',
'tracking',
'djcelery',
'pagination']
Installed Middleware:
('django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.middleware.locale.LocaleMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.contrib.flatpages.middleware.FlatpageFallbackMiddleware',
'pagination.middleware.PaginationMiddleware')
Traceback:
File "/Users/jeff/Code/filmlibrary/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
101. request.path_info)
File "/Users/jeff/Code/filmlibrary/lib/python2.7/site-packages/django/core/urlresolvers.py" in resolve
252. sub_match = pattern.resolve(new_path)
File "/Users/jeff/Code/filmlibrary/lib/python2.7/site-packages/django/core/urlresolvers.py" in resolve
252. sub_match = pattern.resolve(new_path)
File "/Users/jeff/Code/filmlibrary/lib/python2.7/site-packages/django/core/urlresolvers.py" in resolve
158. return ResolverMatch(self.callback, args, kwargs, self.name)
File "/Users/jeff/Code/filmlibrary/lib/python2.7/site-packages/django/core/urlresolvers.py" in _get_callback
167. raise ViewDoesNotExist("Could not import %s. Error was: %s" % (mod_name, str(e)))
Exception Type: ViewDoesNotExist at /movies/awesome-movie/
Exception Value: Could not import movies.views. Error was: No module named models
I am not sure why I have this error. My code is as follows...
I have an django app called tracking and another called movies. I have a python file called tracking.py in the tracking app it consists of the following code:
filmlibrary/tracking/tracking.py
from movies.models import Movie
from tracking.models import MovieView
import os
import base64
def tracking_id(request):
try:
return request.session['tracking_id']
except KeyError:
request.session['tracking_id'] = base64.b64encode(os.urandom(36))
return request.session['tracking_id']
def log_movie_view(request, movie):
t_id = tracking_id(request)
try:
v = MovieView.objects.get(tracking_id=t_id, movie=movie)
v.save()
except MovieView.DoesNotExist:
v = MovieView()
v.movie = movie
v.ip_address = request.META.get('REMOTE_ADDR')
v.tracking_id = t_id
v.user = None
if request.user.is_authenticated():
v.user = request.user
v.save()
The above is pretty basic stuff. My views.py in my movies app uses the tracking.py file here:
filmlibrary/movies/views.py
#login_required
def movie_details(request, slug, template_name="movies/movie_detail.html"):
movie = get_object_or_404(Movie, slug=slug)
movie.tracking_id = tracking.tracking_id(request)
movie.save()
tracking.log_movie_view(request, movie)
context = RequestContext(request, {'movie': movie })
if movie:
try:
screener = movie.moviemedia_set.get(movie_type='screener')
.... continued
UPDATE:
Here are the contents of filmlibrary/tracking/models.py
from django.db import models
from django.contrib.auth.models import User
from movies.models import Movie
class PageView(models.Model):
class Meta:
abstract = True
date = models.DateTimeField(auto_now=True)
ip_address = models.IPAddressField()
user = models.ForeignKey(User, null=True)
tracking_id = models.CharField(max_length=50, default='')
class MovieView(PageView):
movie = models.ForeignKey(Movie)
The error appears to come from the import line from tracking.models import MovieView in the tracking.py file and I am not sure why. As soon as I comment out that line the error goes away but then of course I'll have new errors about MovieView not existing as expected. I don't see anything wrong with that import line in tracking.py.
Does anyone have any suggestions as to why I receive that error and how I can resolve this?
Can you try
from models import MovieView
instead of
from tracking.models import MovieView
The reason being both models.py and tracking.py are in the same app folder "tracking", you don't need to write tracking.models, this will make Django think that you have a folder named models inside the tracking directory.
Though this is a good solution in some cases, this error can also be caused by app name conflicts with built in apps.
I know that our team has encountered this error and it was because of the actual app name. This is also important to note, because you won't be able to pull in models to other apps if that is the case.
#You cannot use this format out of scope
from models import Test
#You can use this both in and out of scope in Django
from myapp.models import Test
If the second example isn't working in your Django project you may be using a conflicting app name. Good examples of unusable built in apps include (but are not limited to) "tests", and "admin".
I would caution against a bandaid fix and investigate your app name closely.