Django: NoReverseMatch Error production_id: None - django

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

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 - 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 Sitemap and Absolute URL

I have an issue setting up a sitemap with my models. I am getting the following error. Reverse for '5555155555' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: []. I think I have to pass a slug to the location but not 100% sure how I would accomplish this task.
#sitemap.py
from django.contrib.sitemaps import Sitemap
from django.contrib.flatpages.models import FlatPage
from django.urls import reverse
from phonenumbers.models import Phone
class PhoneSitemap(Sitemap):
changefreq = "always"
priority = 0.5
def items(self):
return Phone.objects.all()
def location(self, obj):
return reverse(obj)
def lastmode(self, obj):
return obj.created
class FlatpageSitemap(Sitemap):
changefreq = "always"
priority = 0.5
def items(self):
return FlatPage.objects.all()
#models.py
class Phone(models.Model):
phone_number = models.CharField(blank=False, max_length=15) # validators should be a list
name = models.CharField(max_length=50)
message = models.TextField()
caller = models.CharField(max_length=100, choices=CALLER_CHOICES, default="Unknown")
created = models.DateTimeField(auto_now_add=True)
slug = models.SlugField(max_length=250, unique=True)
def save(self, *args, **kwargs):
self.slug = slugify(self.phone_number)
super(Phone, self).save(*args, **kwargs)
def get_absolute_url(self):
return reverse('phonenumbers:phone_details', args=[self.slug])
def __str__(self):
return self.phone_number
#urls.py
from django.conf.urls import url, include
from django.contrib import admin
from django.contrib.flatpages import views
from django.contrib.sitemaps.views import sitemap
from .sitemap import PhoneSitemap, FlatpageSitemap
from info.views import home
sitemaps = {
'posts': PhoneSitemap,
'pages': FlatpageSitemap,
}
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^$', home, name="home"),
url(r'^privacy-policy/$', views.flatpage, {'url': '/privacy-policy/'}, name='privacy-policy'),
url(r'^terms-and-conditions/$', views.flatpage, {'url': '/terms-and-conditions/'}, name='terms-and-conditions'),
url(r'^sitemap\.xml$', sitemap, {'sitemaps': sitemaps}, name='django.contrib.sitemaps.views.sitemap'),
url(r'^whocalledme/', include('phonenumbers.urls', app_name="phonenumbers", namespace="phonenumbers")),
]
phonenumbers.urls
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^search/$', views.search_numbers, name="search_numbers"),
url(r'^number/(?P<slug>[-\w]+)/$', views.phone_detail, name="phone_detail"),
url(r'^add_number/$', views.add_number, name='add_number'),
Environment:
Request Method: GET
Request URL: http://127.0.0.1:8000/sitemap.xml
Django Version: 1.10.4
Python Version: 3.5.2
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.sites',
'django.contrib.flatpages',
'whitenoise.runserver_nostatic',
'crispy_forms',
'django.contrib.sitemaps',
'phonenumbers']
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 "/Users/Tommy/Desktop/django/info/lib/python3.5/site-packages/django/core/handlers/exception.py" in inner
39. response = get_response(request)
File "/Users/Tommy/Desktop/django/info/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response
187. response = self.process_exception_by_middleware(e, request)
File "/Users/Tommy/Desktop/django/info/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response
185. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Users/Tommy/Desktop/django/info/lib/python3.5/site-packages/django/contrib/sitemaps/views.py" in inner
16. response = func(request, *args, **kwargs)
File "/Users/Tommy/Desktop/django/info/lib/python3.5/site-packages/django/contrib/sitemaps/views.py" in sitemap
68. protocol=req_protocol))
File "/Users/Tommy/Desktop/django/info/lib/python3.5/site-packages/django/contrib/sitemaps/__init__.py" in get_urls
105. urls = self._urls(page, protocol, domain)
File "/Users/Tommy/Desktop/django/info/lib/python3.5/site-packages/django/contrib/sitemaps/__init__.py" in _urls
114. loc = "%s://%s%s" % (protocol, domain, self.__get('location', item))
File "/Users/Tommy/Desktop/django/info/lib/python3.5/site-packages/django/contrib/sitemaps/__init__.py" in __get
62. return attr(obj)
File "/Users/Tommy/Desktop/django/info/info/info/sitemap.py" in location
15. return obj.get_absolute_url()
File "/Users/Tommy/Desktop/django/info/info/phonenumbers/models.py" in get_absolute_url
25. return reverse('phonenumbers:phone_details', kwargs={'slug': self.slug})
File "/Users/Tommy/Desktop/django/info/lib/python3.5/site-packages/django/urls/base.py" in reverse
91. return force_text(iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs)))
File "/Users/Tommy/Desktop/django/info/lib/python3.5/site-packages/django/urls/resolvers.py" in _reverse_with_prefix
392. (lookup_view_s, args, kwargs, len(patterns), patterns)
Exception Type: NoReverseMatch at /sitemap.xml
Exception Value: Reverse for 'phone_details' with arguments '()' and keyword arguments '{'slug': '2159642387'}' not found. 0 pattern(s) tried: []
The name is phone_detail in urls.py and phone_details (with an "s") in get_absolute_url(). They should both be the same.

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!

adding new registered users to the database and their login system in django

i have created a form in which the user enters data and that data is saved onto the database.but the form is not s![enter image description here][1]aving the data is there any wrong in the coding?please help..
my code is here:-
1) views.py
-----------------------------------------------------------
from django.http import HttpResponse
#from django.shortcuts import render_to_response
from django.template import RequestContext, loader
from forms import SignupForm
def signup(request):
if request.method == 'POST':
form = SignupForm(request.POST)
if form.is_valid():
form.cleaned_data('username')
form.cleaned_data('email')
form.cleaned_data('password1')
form.save()
return HttpResponse('/login/') #havent did the login method yet...
else:
t = loader.get_template('signup.html')
cform = SignupForm()
c = RequestContext (request, {'form' : cform,})
return HttpResponse(t.render(c))
#def login(request):
# newform = SignupForm()
#if newform.is_valid():
2) forms.py-
from django.contrib.auth.models import User
from django import forms
class SignupForm(forms.Form):
username = forms.CharField(max_length=255, label="Username")
email = forms.CharField(max_length=255, label="E-Mail Address")
password1 = forms.CharField(max_length=255, label="Password", widget=forms.PasswordInput)
password2 = forms.CharField(max_length=255, label="Repeat Password", widget=forms.PasswordInput)
def clean_username(self):
try:
User.objects.get(username=self.cleaned_data['username'])
except User.DoesNotExist:
return self.cleaned_data['username']
raise forms.ValidationError("This username is already in use.Please choose another.")
def clean(self):
if 'password1' in self.cleaned_data and 'password2' in self.cleaned_data:
if self.cleaned_data['password1'] != self.cleaned_data['password2']:
raise forms.ValidationError("You must type the same password each time")
return self.cleaned_data
def save(self):
new_user = User.objects.create_user(username=self.cleaned_data['username'], email=self.cleaned_data['email'], password=self.cleaned_data['password1'])
return new_user
3)urls.py:-
from django.conf.urls import patterns, include, url
from django.contrib import admin
#from salary import settings
#from salarylive.views import signup
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
#url(r'^$', 'salary.views.home', name='home'),
#url(r'^salary/', include('salary.foo.urls')),
# Uncomment the admin/doc line below to enable admin documentation:
# url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
# Uncomment the next line to enable the admin:
url(r'^admin/', include(admin.site.urls)),
url(r'^signup/$', 'salarylive.views.signup'),
#url(r'^login/$', 'salarylive.views.login'),
)
error traceback :-
error traceback :- Environment:
Request Method: POST
Request URL: http://localhost:8000/signup/
Django Version: 1.4.3
Python Version: 2.7.0
Installed Applications:
('django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.admin',
'salarylive')
Installed Middleware:
('django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware')
Traceback:
File "c:\Python27\lib\site-packages\django\core\handlers\base.py" in get_response
111. response = callback(request, *callback_args, **callback_kwargs)
File "e:\Software Installations\Aptana Workspace\salary\salarylive\views.py" in signup
10. form.cleaned_data('username')
Exception Type: TypeError at /signup/
Exception Value: 'dict' object is not callable
You have some indentation errors. The first return HttpResponse should be indented one additional level, so that it only happens if the form is valid. The second return HttpResponse and the line above it should be indented one less level, so that it catches the fall-through from the if statement.
The way you have it, the code always redirects, even if the form is not valid and the data is not saved. With those changes, the second return will re-render the form with errors when it is not valid.