Django Sitemap and Absolute URL - django

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.

Related

How to properly include + register viewset routers with Django 2.0 DRF 3.8

I'm developing a basic Django DRF API. I have been using class-based views with explicit URLs. Now I'm trying to use very vanilla DRF ViewSets + router (for auto URL generation).
Can anybody help point me in the right direction? I'm on DRF 3.8 and Django 2.0
Project urls.py:
from django.conf.urls import url, include
urlpatterns = [
url(r'^userprofile/', include('UserProfile.urls', namespace='UserProfile')),
]
App: UserProfile/urls.py:
from django.conf.urls import include
from django.urls import path
from rest_framework.routers import DefaultRouter
from UserProfile import views
app_name = 'UserProfile'
router = DefaultRouter()
router.register('humans', views.HumanViewSet,)
urlpatterns = [path('', include(router.urls))]
App: UserProfile/views.py
from rest_framework import viewsets
from UserProfile.models import Human
from UserProfile.serializers import HumanSerializer
class HumanViewSet(viewsets.ReadOnlyModelViewSet):
serializer_class = HumanSerializer
queryset = Human.objects.all()
I get an error:
__init__() missing 2 required positional arguments: 'app_name' and 'app_module'
Full traceback:
Including full traceback:
Environment:
Request Method: GET
Request URL: http://127.0.0.1:8000/userprofile/humans/
Django Version: 2.0.4
Python Version: 3.6.4
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'rest_framework.authtoken',
'rest_framework_simplejwt',
'django_extensions',
'django_pdb',
'django_use_email_as_username.apps.DjangoUseEmailAsUsernameConfig',
'custom_user.apps.CustomUserConfig',
'factory',
'UserProfile']
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 "/usr/local/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner
35. response = get_response(request)
File "/usr/local/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
128. response = self.process_exception_by_middleware(e, request)
File "/usr/local/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
126. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/usr/local/lib/python3.6/site-packages/django/views/decorators/csrf.py" in wrapped_view
54. return view_func(*args, **kwargs)
File "/usr/local/lib/python3.6/site-packages/rest_framework/viewsets.py" in view
103. return self.dispatch(request, *args, **kwargs)
File "/usr/local/lib/python3.6/site-packages/rest_framework/views.py" in dispatch
466. request = self.initialize_request(request, *args, **kwargs)
File "/usr/local/lib/python3.6/site-packages/rest_framework/viewsets.py" in initialize_request
125. request = super(ViewSetMixin, self).initialize_request(request, *args, **kwargs)
File "/usr/local/lib/python3.6/site-packages/rest_framework/views.py" in initialize_request
368. authenticators=self.get_authenticators(),
File "/usr/local/lib/python3.6/site-packages/rest_framework/views.py" in get_authenticators
262. return [auth() for auth in self.authentication_classes]
File "/usr/local/lib/python3.6/site-packages/rest_framework/views.py" in <listcomp>
262. return [auth() for auth in self.authentication_classes]
Exception Type: TypeError at /userprofile/humans/
Exception Value: __init__() missing 2 required positional arguments: 'app_name' and 'app_module'

Issue with Django 2.0 : 'WSGIRequest' object has no attribute 'session'

I upgraded my Django version from 1.11.5 to 2.0 and I'm trying to solve different deprecated element.
However, even if my CSS/bootstrap style sheet doesn't work, I don't overcome to log into my Django software. I have this issue :
'WSGIRequest' object has no attribute 'session'
This is the entire Traceback :
Environment:
Request Method: POST
Request URL: http://127.0.0.1:8000/Authentification/Login/
Django Version: 2.0
Python Version: 3.6.2
Installed Applications:
['Institution',
'django.conf.urls',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'bootstrapform',
'django_countries',
'chartit',
'Configurations',
'Home',
'Authentication',
'Identity',
'rest_framework',
'Fiscal',
'bootstrap4']
Installed Middleware:
[]
Traceback:
File "/Users/valentinjungbluth/Desktop/DatasystemsCORE3.6/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner
35. response = get_response(request)
File "/Users/valentinjungbluth/Desktop/DatasystemsCORE3.6/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
128. response = self.process_exception_by_middleware(e, request)
File "/Users/valentinjungbluth/Desktop/DatasystemsCORE3.6/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
126. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Users/valentinjungbluth/Desktop/DatasystemsCORE3.6/lib/python3.6/site-packages/django/views/decorators/csrf.py" in wrapped_view
54. return view_func(*args, **kwargs)
File "/Users/valentinjungbluth/Desktop/Django/DatasystemsCORE/DatasystemsCore/DatasystemsCORE/Authentication/views.py" in Login
26. login(request, user)
File "/Users/valentinjungbluth/Desktop/DatasystemsCORE3.6/lib/python3.6/site-packages/django/contrib/auth/__init__.py" in login
130. if SESSION_KEY in request.session:
Exception Type: AttributeError at /Authentification/Login/
Exception Value: 'WSGIRequest' object has no attribute 'session'
In my Authentification app :
# views.py file
#-*- coding: utf-8 -*-
from django.contrib.auth import authenticate, login, logout
from .forms import ConnexionForm
from django.shortcuts import render, reverse, get_object_or_404, redirect
from django.http import HttpResponseRedirect, HttpResponse
from .models import LoggedUsers
from API_GED import Logger
import datetime
from django.views.decorators.csrf import csrf_exempt,csrf_protect
#csrf_exempt
def Login(request):
error = False
if request.method == "POST":
form = ConnexionForm(request.POST)
if form.is_valid():
username = form.cleaned_data["username"]
password = form.cleaned_data["password"]
user = authenticate(username=username, password=password) # Nous vérifions si les données sont correctes
if user: # Si l'objet renvoyé n'est pas None
login(request, user)
response = redirect('Homepage')
return response
else: # sinon une erreur sera affichée
error = True
else:
form = ConnexionForm()
return render(request, 'Authentication_Homepage.html', locals())
def Logout(request):
logout(request)
return redirect(reverse('Choice'))
def ConnectedUsers(request) :
logged_users = LoggedUsers.objects.all()
print (logged_users)
logged_users_number = LoggedUsers.objects.all().count()
context = {
"logged_users":logged_users,
"logged_users_number":logged_users_number,
}
return render(request, "Authentication_LoggedUsers.html", context)
An my models.py file :
from django.db import models
from django.contrib.auth.models import User
from django.contrib.auth.signals import user_logged_in, user_logged_out
# class UserProfile(models.Model):
# user = models.OneToOneField(User)
# avatar = models.ImageField(upload_to='/images/')
class LoggedUsers(models.Model):
user = models.ForeignKey(User, primary_key=True, on_delete=models.CASCADE)
def __str__(self):
return '{}{}{}'.format(self.user.first_name + " ", self.user.last_name + " (", self.user.username + ")")
def login_user(sender, request, user, **kwargs):
LoggedUsers(user=user).save()
def logout_user(sender, request, user, **kwargs):
try:
u = LoggedUsers.objects.get(user=user)
u.delete()
except LoggedUsers.DoesNotExist:
pass
user_logged_in.connect(login_user)
user_logged_out.connect(logout_user)
In my settings.py file, I have MIDDLEWARE_CLASSES :
MIDDLEWARE_CLASSES = [
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.locale.LocaleMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.middleware.gzip.GZipMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django.middleware.security.SecurityMiddleware',
'DatasystemsCORE.middleware.OnlineNowMiddleware',
]
Any idea ?
EDIT :
I wrote MIDDLEWARE like this :
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',
]
It seems to work !
So the MIDDLEWARE_CLASSES changed to MIDDLEWARE https://docs.djangoproject.com/en/2.0/topics/http/middleware/#activating-middleware
MIDDLEWARE_CLASSES has been deprecated since Django 1.10 and was removed completely in version 2.0. That means you have no middleware at all.
You should use the MIDDLEWARE setting instead; note, that uses new-style middleware, you might need to upgrade your custom middleware class.

Created Object in Python Shell, not recognized when queried

Currently creating a Django site for some work I'm doing. Here are the relevant code blocks:
portal/device_categories/models.py
from django.db import models
# Create your models here.
class Type(models.Model):
device_category = models.CharField(max_length=20)
def __str__(self):
return self.device_category
class Device(models.Model):
category = models.ForeignKey(Type, on_delete=models.CASCADE)
tms_code = models.CharField(max_length=5)
device_name = models.CharField(max_length=30)
device_count = models.CharField(max_length=3)
def __str__(self):
return "Device:" + self.device_name
portal/device_categories/urls.py
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^(?P<device_type>[A-Za-z]+)/$', views.deviceList, name='deviceList'),
]
portal/device_categories/views.py
from django.shortcuts import render
from django.http import HttpResponse
from .models import Type, Device
from django.template import loader
# Create your views here.
def index(request):
return HttpResponse("This is the Device Categories Page")
def deviceList(request, device_type):
all_devices = Device.objects.get(category__device_category=device_type)
template = loader.get_template('device_categories/index.html')
context = {
'all_devices': all_devices,
}
return render(request, template, context)
I have created numerous Device Objects using the:
python manage.py shell
methodology, some example categories are: fans, switches, modules. All the categories have also been set up as their own Type Class. Now I have 5 objects that I assigned a category of fans, but when I try to go to url:
127.0.0.1:8000/device_categories/fans/
I am getting error:
Environment:
Request Method: GET
Request URL: http://127.0.0.1:8000/device_categories/fans/
Django Version: 1.11.4
Python Version: 3.6.0
Installed Applications:
['network_resources.apps.NetworkResourcesConfig',
'device_categories.apps.DeviceCategoriesConfig',
'device_inventory.apps.DeviceInventoryConfig',
'on_call.apps.OnCallConfig',
'contact_info.apps.ContactInfoConfig',
'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 "C:\Program Files (x86)\Python36-32\lib\site-packages\django-1.11.4-py3.6.egg\django\core\handlers\exception.py" in inner
41. response = get_response(request)
File "C:\Program Files (x86)\Python36-32\lib\site-packages\django-1.11.4-py3.6.egg\django\core\handlers\base.py" in _get_response
187. response = self.process_exception_by_middleware(e, request)
File "C:\Program Files (x86)\Python36-32\lib\site-packages\django-1.11.4-py3.6.egg\django\core\handlers\base.py" in _get_response
185. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\users\wskidmor\Django\nocportal\device_categories\views.py" in deviceList
11. all_devices = Device.objects.get(category__device_category=device_type)
File "C:\Program Files (x86)\Python36-32\lib\site-packages\django-1.11.4-py3.6.egg\django\db\models\manager.py" in manager_method
85. return getattr(self.get_queryset(), name)(*args, **kwargs)
File "C:\Program Files (x86)\Python36-32\lib\site-packages\django-1.11.4-py3.6.egg\django\db\models\query.py" in get
380. self.model._meta.object_name
Exception Type: DoesNotExist at /device_categories/fans/
Exception Value: Device matching query does not exist.
I have verified that the objects exist when I go into the shell so I'm not sure what I'm doing wrong. I have found similar questions posted on here but I have tried those solutions and they unfortunately didn't apply. Thank you for your help
Change this line in your views:
all_devices = Device.objects.get(category__device_category=device_type)
To:
all_devices = Device.objects.filter(category__device_category=device_type)

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

Custom password_reset_form returning: unhashable type: 'dict'

I am trying to override the form for password_reset_form but it keep resulting in following error:
unhashable type: 'dict'
I interpret this error as password_reset_form does not exist for some reason?
My urls.py:
from rest_framework.routers import DefaultRouter
from django.conf.urls import patterns, url, include
from web import views
from web.forms import MyLoginForm, MyPasswordResetForm
urlpatterns = patterns('',
#url(r'^', views.IndexView.as_view(), name='index'),
url(r'^accounts/login/$', 'django.contrib.auth.views.login', {'authentication_form': MyLoginForm}),
url(r'^accounts/logout/$', 'django.contrib.auth.views.logout', name='logout'),
url(r'^accounts/password/reset/$',
'django.contrib.auth.views.password_reset',
{'password_reset_form': MyPasswordResetForm},
{'post_reset_redirect' : '/user/password/reset/done/'}),
(r'^accounts/password/reset/done/$',
'django.contrib.auth.views.password_reset_done'),
(r'^accounts/password/reset/(?P<uidb36>[0-9A-Za-z]+)-(?P<token>.+)/$',
'django.contrib.auth.views.password_reset_confirm',
{'post_reset_redirect' : '/user/password/done/'}),
(r'^accounts/password/done/$',
'django.contrib.auth.views.password_reset_complete'),
)
My forms.py:
from django import forms
from django.forms import ModelForm
from django.contrib.auth.models import User
from django.contrib.auth.forms import AuthenticationForm, PasswordResetForm
class MyLoginForm(AuthenticationForm):
username = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control','placeholder':'Brugernavn'}))
password = forms.CharField(widget=forms.PasswordInput(attrs={'class':'form-control','placeholder':'Password'}))
class MyPasswordResetForm(PasswordResetForm):
username = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control','placeholder':'Brugernavn'}))
Full stacktrace:
Environment:
Request Method: GET
Request URL: http://127.0.0.1:8000/accounts/password/reset/
Django Version: 1.6.1
Python Version: 2.7.5
Installed Applications:
('django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'web',
'api',
'django.contrib.admin',
'rest_framework.authtoken',
'corsheaders',
'django.contrib.auth')
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',
'corsheaders.middleware.CorsMiddleware')
Traceback:
File "/Library/Python/2.7/site-packages/django/core/handlers/base.py" in get_response
114. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Library/Python/2.7/site-packages/django/utils/decorators.py" in _wrapped_view
99. response = view_func(request, *args, **kwargs)
File "/Library/Python/2.7/site-packages/django/contrib/auth/views.py" in password_reset
142. post_reset_redirect = reverse('password_reset_done')
File "/Library/Python/2.7/site-packages/django/core/urlresolvers.py" in reverse
509. return iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs))
File "/Library/Python/2.7/site-packages/django/core/urlresolvers.py" in _reverse_with_prefix
387. possibilities = self.reverse_dict.getlist(lookup_view)
File "/Library/Python/2.7/site-packages/django/core/urlresolvers.py" in reverse_dict
296. self._populate()
File "/Library/Python/2.7/site-packages/django/core/urlresolvers.py" in _populate
273. for name in pattern.reverse_dict:
File "/Library/Python/2.7/site-packages/django/core/urlresolvers.py" in reverse_dict
296. self._populate()
File "/Library/Python/2.7/site-packages/django/core/urlresolvers.py" in _populate
287. lookups.appendlist(pattern.name, (bits, p_pattern, pattern.default_args))
File "/Library/Python/2.7/site-packages/django/utils/datastructures.py" in appendlist
383. self.setlistdefault(key).append(value)
File "/Library/Python/2.7/site-packages/django/utils/datastructures.py" in setlistdefault
373. if key not in self:
Exception Type: TypeError at /accounts/password/reset/
Exception Value: unhashable type: 'dict'
Your arguments for url isn't right. Should be one dictionary
url(r'^accounts/password/reset/$',
'django.contrib.auth.views.password_reset',
{'password_reset_form': MyPasswordResetForm,
'post_reset_redirect': '/user/password/reset/done/'}),