django name render is not defined - django

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!

Related

unable to send argument value from one view to another view in Django

In my login view function, i wanted to know if the user is redirected here after being stopped from accessing a Page
This is basically a Q & A website where user is redirected to login page if he click on write Answer link without signing In
Here is views.py of main app
from django.shortcuts import render
from django.http import request, HttpResponseRedirect, HttpResponse
# import the models
from .models import Question, Answer, Comment
# import paginator for pagination
from django.core.paginator import Paginator
# import forms
from .forms import Write_Answer_form, CommentForm
# import user
from django.contrib.auth.models import User
# import timezone for update function
from django.utils import timezone
# reverse for efficient url redirecting
from django.urls import reverse
from django.shortcuts import redirect
# Create your views here.
# i have deleted some views functions as they seems irrelavant here
def writeAns(request,questionID):
# check if the user is authenticated
if request.user.is_authenticated:
# get the Question from ID
RequestedQuestion= Question.objects.get(id= questionID)
# check if there is a post request from template
if request.method == 'POST':
# get all the form data with post request into a variable
fom= Write_Answer_form(request.POST)
if fom.is_valid():
get_save_form_data(RequestedQuestion, request, fom)
# make a string url to pass as a arguments
url= '/detail/'+ str(questionID)
return HttpResponseRedirect(url)
else:
# send blank form to template
fom= Write_Answer_form()
data= {'form':fom}
return render(request, 'writeAns.html', data)
# if user is not authenticated
else:
return redirect('login_page',args=["True"])
views.py of authentiCation app ( i want to send redirected value to login_page function )
from django.shortcuts import render
from django.http import request,HttpResponseRedirect
# for user creation & login form
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth import authenticate, login, logout
# for user related Queries
from django.contrib.auth.models import User
from django.urls import reverse
from django.shortcuts import redirect
# imports for test purpose
from django.http import HttpResponse
# Create your views here.
# register page
def register_Page(request):
if request.method == 'POST':
form= UserCreationForm(request.POST)
if form.is_valid():
form.save()
username= request.POST['username']
password= request.POST['password1']
user= authenticate(request,username=username,password=password)
login(request,user)
return HttpResponseRedirect('/')
else:
return HttpResponse('Either the user name is not available or you may have filled the form incorrectly')
else:
form = UserCreationForm()
context= {'form':form}
return render(request,'authentication/register_Page.html',context)
# login page
def login_page(request,redirected=None):
if request.method == 'POST':
username= request.POST['username']
password= request.POST['password']
# returns user if credentials are valid
user= authenticate(request, username=username, password= password)
# check if user var contains the user
if user is not None:
login(request, user)
return redirect(reverse('Home_page'))
else:
return HttpResponse('Invalid credentials')
# check if the user is redirected
if redirected == "True":
data= {'warning':"please login first"}
return render(request,'authentication/login.html',data)
else:
return render(request,'authentication/login.html')
# logout Page
def log_out(request):
logout(request)
return HttpResponseRedirect(reverse('login_page'))
urls.py of authentiCation
from django.urls import path
from authentiCation import views
urlpatterns = [
path('register/',views.register_Page,name='register_Page'),
path('login/',views.login_page,name='login_page'),
path('logout/',views.log_out,name='logout_page'),
]
And here is the Traceback
Environment:
Request Method: GET
Request URL: http://127.0.0.1:8000/writeAns/5
Django Version: 3.2
Python Version: 3.7.3
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'App_wfi_Community',
'django.contrib.humanize',
'askQuestion',
'authentiCation']
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 (most recent call last):
File "/home/saurav/Documents/programming_Projects/WFI-Community/venv/lib/python3.7/site-packages/django/core/handlers/exception.py", line 47, in inner
response = get_response(request)
File "/home/saurav/Documents/programming_Projects/WFI-Community/venv/lib/python3.7/site-packages/django/core/handlers/base.py", line 181, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/saurav/Documents/programming_Projects/WFI-Community/App_wfi_Community/views.py", line 114, in writeAns
return redirect('login_page',args=["True"])
File "/home/saurav/Documents/programming_Projects/WFI-Community/venv/lib/python3.7/site-packages/django/shortcuts.py", line 41, in redirect
return redirect_class(resolve_url(to, *args, **kwargs))
File "/home/saurav/Documents/programming_Projects/WFI-Community/venv/lib/python3.7/site-packages/django/shortcuts.py", line 130, in resolve_url
return reverse(to, args=args, kwargs=kwargs)
File "/home/saurav/Documents/programming_Projects/WFI-Community/venv/lib/python3.7/site-packages/django/urls/base.py", line 86, in reverse
return resolver._reverse_with_prefix(view, prefix, *args, **kwargs)
File "/home/saurav/Documents/programming_Projects/WFI-Community/venv/lib/python3.7/site-packages/django/urls/resolvers.py", line 694, in _reverse_with_prefix
raise NoReverseMatch(msg)
Exception Type: NoReverseMatch at /writeAns/5
Exception Value: Reverse for 'login_page' with keyword arguments '{'args': ['True']}' not found. 1 pattern(s) tried: ['login/$']
The error is
NoReverseMatch at /writeAns/5
Reverse for 'login_page' with keyword arguments '{'args': ['True']}' not found. 1 pattern(s) tried: ['login/$']
For some reason people think the shortcut function redirect would send their user to some other view while passing data to it. This is not true.
According to the documentation the redirect function:
Returns an
HttpResponseRedirect
to the appropriate 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: reverse()
will be used to reverse-resolve the name.
An absolute or relative 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.
What is HttpResponseRedirect? Well it is simply a response with a HTTP 302 status code and a url in the Location header indicating that their requested resource has been temporarily moved to the URL given by the Location header.
Well what if we want to have some data for the user and redirect them somewhere? There are various methods to do that:
Use a GET parameter:
from django.urls import reverse
# While redirecting
return redirect("{}?{}".format(reverse("login_page"), "data=True"))
# At receiving view:
data = request.GET.get("data", False) == "True"
Store something in the session [Django docs] for the user:
# While redirecting
request.session['data'] = "True"
return redirect('login_page')
# At receiving view
data = request.session.get('data') == 'True'

Django rest framework ```TypeError: type object argument after ** must be a mapping, not int``` being thrown

I have a SMSMessages model that will contain all the sms sent.I'm trying access via the django-rest-framework ListCreateAPIView class, but I keep on hitting error when I try to do an OPTION request on the api via Insomnia, TypeError at /smsmessages/
type object argument after ** must be a mapping, not int.
I searched on SO and found similar errors but they were caused b/c of a filter() argument, which doesn't apply to this.
I'm using django 2.2.5, python 3.6.8, django-rest-framework 3.10.3 and a mysqlclient 1.4.4.
this is the model of SMSMessages
from django.db import models
from django.contrib.auth.models import AbstractUser
from rest_framework.authtoken.models import Token
class SMSMessages(models.Model):
sms_number_to = models.CharField(max_length=14)
sms_content = models.CharField(max_length=160)
sending_user = models.ForeignKey("SMSUser", on_delete=models.PROTECT, related_name="user_that_sent", limit_choices_to=1)
sent_date = models.DateTimeField(auto_now=True)
delivery_status = models.BooleanField(default=False)
class Meta:
verbose_name_plural = "SMSMessages"
def __str__(self):
return self.sending_user
and this is this the urls.py file:
from django.urls import path
from rest_framework.authtoken import views
from rest_framework.routers import DefaultRouter
from notification.apiviews import SMSendView, SMSMessagesView
app_name = "notification"
router = DefaultRouter()
urlpatterns = [
path("smsmessages/", SMSMessagesView.as_view(), name="sms_messages"),
]
so the way I access it is by sending an OPTION request to http://localhost:8000/smsmessages/.
This the SMSMessagesview class that is used for the api view:
from rest_framework import generics, status, viewsets, permissions
from rest_framework.response import Response
from rest_framework.views import APIView
from django.shortcuts import get_object_or_404, get_list_or_404
from django.contrib.auth import authenticate
from commons.models import SMSMessages
from commons.serializers import SMSMessagesSerializer
class SMSMessagesView(generics.ListCreateAPIView):
"""
This class is responsible for generating, and returning, the view for all created objects of the SMSMessages model.
It sub-classes the ListCreateAPIView class from the generics module.
"""
queryset = SMSMessages.objects.all()
if not queryset:
Response(data={"{0} not found".format(queryset)}, status=404, content_type="application/json")
serializer_class = SMSMessagesSerializer
and this is the error:
TypeError at /notification/smsmessages/
type object argument after ** must be a mapping, not int
Request Method: OPTIONS
Request URL: http://localhost:8055/notification/smsmessages/
Django Version: 2.2.5
Python Executable: /home/gadd/vscodeworkspace/sms.et/api.sms.et/api_env/bin/python
Python Version: 3.6.8
Python Path: ['/home/gadd/vscodeworkspace/sms.et/api.sms.et', '/home/gadd/vscodeworkspace/sms.et/api.sms.et/api_env/lib/python36.zip', '/home/gadd/vscodeworkspace/sms.et/api.sms.et/api_env/lib/python3.6', '/home/gadd/vscodeworkspace/sms.et/api.sms.et/api_env/lib/python3.6/lib-dynload', '/usr/lib/python3.6', '/home/gadd/vscodeworkspace/sms.et/api.sms.et/api_env/lib/python3.6/site-packages']
Server time: Sat, 5 Oct 2019 16:19:59 +0000
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'rest_framework_swagger',
'rest_framework.authtoken',
'commons',
'notification']
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 "/home/gadd/vscodeworkspace/sms.et/api.sms.et/api_env/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner
34. response = get_response(request)
File "/home/gadd/vscodeworkspace/sms.et/api.sms.et/api_env/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
115. response = self.process_exception_by_middleware(e, request)
File "/home/gadd/vscodeworkspace/sms.et/api.sms.et/api_env/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
113. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/gadd/vscodeworkspace/sms.et/api.sms.et/api_env/lib/python3.6/site-packages/django/views/decorators/csrf.py" in wrapped_view
54. return view_func(*args, **kwargs)
File "/home/gadd/vscodeworkspace/sms.et/api.sms.et/api_env/lib/python3.6/site-packages/django/views/generic/base.py" in view
71. return self.dispatch(request, *args, **kwargs)
File "/home/gadd/vscodeworkspace/sms.et/api.sms.et/api_env/lib/python3.6/site-packages/rest_framework/views.py" in dispatch
505. response = self.handle_exception(exc)
File "/home/gadd/vscodeworkspace/sms.et/api.sms.et/api_env/lib/python3.6/site-packages/rest_framework/views.py" in handle_exception
465. self.raise_uncaught_exception(exc)
File "/home/gadd/vscodeworkspace/sms.et/api.sms.et/api_env/lib/python3.6/site-packages/rest_framework/views.py" in raise_uncaught_exception
476. raise exc
File "/home/gadd/vscodeworkspace/sms.et/api.sms.et/api_env/lib/python3.6/site-packages/rest_framework/views.py" in dispatch
502. response = handler(request, *args, **kwargs)
File "/home/gadd/vscodeworkspace/sms.et/api.sms.et/api_env/lib/python3.6/site-packages/rest_framework/views.py" in options
516. data = self.metadata_class().determine_metadata(request, self)
File "/home/gadd/vscodeworkspace/sms.et/api.sms.et/api_env/lib/python3.6/site-packages/rest_framework/metadata.py" in determine_metadata
68. actions = self.determine_actions(request, view)
File "/home/gadd/vscodeworkspace/sms.et/api.sms.et/api_env/lib/python3.6/site-packages/rest_framework/metadata.py" in determine_actions
94. actions[method] = self.get_serializer_info(serializer)
File "/home/gadd/vscodeworkspace/sms.et/api.sms.et/api_env/lib/python3.6/site-packages/rest_framework/metadata.py" in get_serializer_info
111. for field_name, field in serializer.fields.items()
File "/home/gadd/vscodeworkspace/sms.et/api.sms.et/api_env/lib/python3.6/site-packages/django/utils/functional.py" in __get__
80. res = instance.__dict__[self.name] = self.func(instance)
File "/home/gadd/vscodeworkspace/sms.et/api.sms.et/api_env/lib/python3.6/site-packages/rest_framework/serializers.py" in fields
360. for key, value in self.get_fields().items():
File "/home/gadd/vscodeworkspace/sms.et/api.sms.et/api_env/lib/python3.6/site-packages/rest_framework/serializers.py" in get_fields
1047. source, info, model, depth
File "/home/gadd/vscodeworkspace/sms.et/api.sms.et/api_env/lib/python3.6/site-packages/rest_framework/serializers.py" in build_field
1182. return self.build_relational_field(field_name, relation_info)
File "/home/gadd/vscodeworkspace/sms.et/api.sms.et/api_env/lib/python3.6/site-packages/rest_framework/serializers.py" in build_relational_field
1257. field_kwargs = get_relation_kwargs(field_name, relation_info)
File "/home/gadd/vscodeworkspace/sms.et/api.sms.et/api_env/lib/python3.6/site-packages/rest_framework/utils/field_mapping.py" in get_relation_kwargs
255. limit_choices_to = models.Q(**limit_choices_to)
Exception Type: TypeError at /notification/smsmessages/
Exception Value: type object argument after ** must be a mapping, not int
This is the serializer class used:
from rest_framework import serializers
from rest_framework.authtoken.models import Token
from commons.models import SMSUser, SMSPrice, Type, SMSMessages
class SMSMessagesSerializer(serializers.ModelSerializer):
"""
A class for serializing the SMSMessages model's data. It sub-classes the
ModelSerializer class from serializer's module.
"""
class Meta:
model = SMSMessages
fields = '__all__'
This same error is raised when I try to add an SMSMessages object to the db via the admin interface. Can anybody help?
From the documentation for ForeignKey.limit_choices_to, it...
sets a limit to the available choices for this field when this field is rendered using a ModelForm or the admin (by default, all objects in the queryset are available to choose). Either a dictionary, a Q object, or a callable returning a dictionary or Q object can be used.
...but in the model, you set an integer limit_choices_to=1 which is none of these things.
Did you perhaps intend to use something like limit_choices_to={'id': 1} to limit choices to SMS users with that ID?
That's just because you use limit_choices_to with wrong data format which defined by Django.
Either a dictionary, a Q object, or a callable returning a dictionary or Q object can be used.
So this caused the error:
sending_user = models.ForeignKey("SMSUser", on_delete=models.PROTECT, related_name="user_that_sent", limit_choices_to=1 # HERE)
So you might need to be clear what you want to do here to config the right filter so that Django Admin will will filter data when you select sending_user for your model. Like if you want to allow to select is_superuser only for sending_user on admin page then you can go with this:
limit_choices_to={
'is_superuser': True,
}

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" />

unbound method must be called with instance as first argument

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}))