unicode' object has no attribute 'get' in Django - django

I am trying to follow the [Django Tutorial 6][1] to do the user authenication. But i get stuck. I am getting this Attribute error: unicode' object has no attribute 'get'. The models,view and forms are provided below. Not sure where the error is... Need some help...
models.py
from django.db import models
from django.contrib.auth.models import User
class Drinker(models.Model):
user = models.OneToOneField(User)
birthday = models.DateField()
name = models.CharField(max_length=100)
def __unicode__(self):
return self.name
views.py
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
from django.template import RequestContext
from drinker.forms import RegistrationForm
from django.contrib.auth.models import User
from drinker.models import Drinker
def DrinkerRegistration(request):
if request.POST:
form =RegistrationForm(request.POST)
if form.is_valid():
user = User.objects.create_user(username=form.cleaned_data['username'],email=form.cleaned_data['email'])
password = form.cleaned_data['password']
user.save()
drinker=Drinker(user=user,name=form.cleaned_data['name'],birthday=form.cleaned_data['birthday'])
drinker.save()
return HttpResponseRedirect('/profile/')
else:
return render_to_response('register.html',{'form':form,},context_instance=RequestContext(request))
else:
form = RegistrationForm()
return render_to_response('register.html',{'form':form,},context_instance=RequestContext(request))
forms.py
from django import forms
from django.contrib.auth.models import User
from django.forms import ModelForm
from drinker.models import Drinker
class RegistrationForm(ModelForm):
username = forms.CharField(label=(u'User Name'))
email = forms.EmailField(label =(u'Email Address'))
password = forms.CharField(label =(u'Password'),widget=forms.PasswordInput(render_value=False))
password1 = forms.CharField(label =(u'Verify Password'),widget=forms.PasswordInput(render_value=False))
class Meta:
model = Drinker
exclude = ('user',)
def clean_username(self):
username = self.cleaned_data['username']
try:
User.objects.get(username=username)
except User.DoesNotExist:
return username
raise forms.ValidationError("That username is already taken. Please select another")
def clean(self):
password = self.cleaned_data['password']
password1= self.cleaned_data['password1']
if password and password1 and password != password1:
raise forms.ValidationError("The passwords did not match. Please try again")
return password
error:
Environment:
Request Method: POST
Django Version: 1.4
Python Version: 2.7.1
Installed Applications:
('django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.admin',
'django.contrib.admindocs',
'drinker')
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 "/Users/cnnlakshmen_2000/Projects/env/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
111. response = callback(request, *callback_args, **callback_kwargs)
File "/Users/cnnlakshmen_2000/Projects/Permissions/drinker/views.py" in DrinkerRegistration
12. if form.is_valid():
File "/Users/cnnlakshmen_2000/Projects/env/lib/python2.7/site-packages/django/forms/forms.py" in is_valid
124. return self.is_bound and not bool(self.errors)
File "/Users/cnnlakshmen_2000/Projects/env/lib/python2.7/site-packages/django/forms/forms.py" in _get_errors
115. self.full_clean()
File "/Users/cnnlakshmen_2000/Projects/env/lib/python2.7/site-packages/django/forms/forms.py" in full_clean
272. self._post_clean()
File "/Users/cnnlakshmen_2000/Projects/env/lib/python2.7/site-packages/django/forms/models.py" in _post_clean
311. exclude = self._get_validation_exclusions()
File "/Users/cnnlakshmen_2000/Projects/env/lib/python2.7/site-packages/django/forms/models.py" in _get_validation_exclusions
297. field_value = self.cleaned_data.get(field, None)
Exception Type: AttributeError at /register/
Exception Value: 'unicode' object has no attribute 'get'

You're returning password from the clean() method, rather than self.cleaned_data.

Related

'NoneType' object has no attribute '_meta'

I am trying to build register api. Here i am stuck with the problem and hoping you guys will address my mistake and will lead me to right way. Anyway thanks in advance. Hoping for your soon response. Thank you .
serializers.py
from django.contrib.auth.models import User
from rest_framework import serializers
class UserSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = User
fields = ('id', 'username', 'email', 'password')
extra_kwargs = {'password': {'write_only': True}}
def create(self, validated_data):
""" Create and return a new user"""
user = User.objects.create_user(**validated_data)
return user
models.py
from django.db import models
from django.contrib.auth.base_user import AbstractBaseUser
from django.contrib.auth.models import PermissionsMixin
from django.contrib.auth.models import BaseUserManager
from django.contrib.auth import get_user_model
class UserRegisterManager(BaseUserManager):
""" Helps django work with our custom user model """
def createUser(self, email, name, password=None):
""" Creates a new user profile object """
if not email:
raise ValueError("User must have an email address.")
email = self.normalize_email(email)
user = self.model(email=email, name=name)
user.set_password(password) # set_password helps to convert str into hash
user.save(using=self._db)
return user
def create_superuser(self, email, name, password):
""" Creates and saves a new superuser with given details. """
user = self.create_user(email, name, password)
user.is_superuser = True
user.is_staff = True
user.save(using=self._db)
return user
class UserRegister(AbstractBaseUser, PermissionsMixin):
""" Represents a 'user register' inside our system """
email = models.EmailField(max_length=255, unique=True)
name = models.CharField(max_length=255)
is_active = models.BooleanField(default=True) # user is currently active or not
is_staff = models.BooleanField(default=False)
objects = UserRegisterManager()
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['name']
def get_full_name(self):
""" Used to get user fullname """
return self.name
def get_short_name(self):
""" Used to get user short name """
return self.name
def __str__(self):
""" Django uses this when it need to convert the object to a string """
return self.email
this is my model
views.py
from django.contrib.auth.models import User
from rest_framework import viewsets
from rest_framework.authentication import TokenAuthentication
from .serializers import UserSerializer
from . import permissions
from django.contrib.auth import get_user_model
User = get_user_model()
class UserViewSet(viewsets.ModelViewSet):
""" API endpoint that allows users to be viewed or edited. """
serializer_class = UserSerializer
queryset = User.objects.all()
# authentication_classes = (TokenAuthentication,)
# permission_classes = (permissions.UpdateProfile,)
setting.py
AUTH_USER_MODEL = 'register.UserRegister'
this helps to switch to costume user.
admin.py
from django.contrib import admin
from .models import UserRegister
admin.site.register(UserRegister)
And this is how i register my model
Error
This is error
Environment:
Request Method: GET
Request URL: http://127.0.0.1:8000/api/register/
Django Version: 2.1.5
Python Version: 3.7.1
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',
'register',
'corsheaders']
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',
'corsheaders.middleware.CorsMiddleware',
'django.middleware.common.CommonMiddleware']
Traceback:
File "C:\Users\Pashupati Pariyar\Desktop\Django + Angular\Backend\api\lib\site-packages\django\core\handlers\exception.py" in inner
34. response = get_response(request)
File "C:\Users\Pashupati Pariyar\Desktop\Django + Angular\Backend\api\lib\site-packages\django\core\handlers\base.py" in _get_response
156. response = self.process_exception_by_middleware(e, request)
File "C:\Users\Pashupati Pariyar\Desktop\Django + Angular\Backend\api\lib\site-packages\django\core\handlers\base.py" in _get_response
154. response = response.render()
File "C:\Users\Pashupati Pariyar\Desktop\Django + Angular\Backend\api\lib\site-packages\django\template\response.py" in render
106. self.content = self.rendered_content
File "C:\Users\Pashupati Pariyar\Desktop\Django + Angular\Backend\api\lib\site-packages\rest_framework\response.py" in rendered_content
72. ret = renderer.render(self.data, accepted_media_type, context)
File "C:\Users\Pashupati Pariyar\Desktop\Django + Angular\Backend\api\lib\site-packages\rest_framework\renderers.py" in render
733. context = self.get_context(data, accepted_media_type, renderer_context)
File "C:\Users\Pashupati Pariyar\Desktop\Django + Angular\Backend\api\lib\site-packages\rest_framework\renderers.py" in get_context
663. raw_data_post_form = self.get_raw_data_form(data, view, 'POST', request)
File "C:\Users\Pashupati Pariyar\Desktop\Django + Angular\Backend\api\lib\site-packages\rest_framework\renderers.py" in get_raw_data_form
574. data = serializer.data.copy()
File "C:\Users\Pashupati Pariyar\Desktop\Django + Angular\Backend\api\lib\site-packages\rest_framework\serializers.py" in data
563. ret = super(Serializer, self).data
File "C:\Users\Pashupati Pariyar\Desktop\Django + Angular\Backend\api\lib\site-packages\rest_framework\serializers.py" in data
266. self._data = self.get_initial()
File "C:\Users\Pashupati Pariyar\Desktop\Django + Angular\Backend\api\lib\site-packages\rest_framework\serializers.py" in get_initial
413. for field in self.fields.values()
File "C:\Users\Pashupati Pariyar\Desktop\Django + Angular\Backend\api\lib\site-packages\rest_framework\serializers.py" in fields
363. for key, value in self.get_fields().items():
File "C:\Users\Pashupati Pariyar\Desktop\Django + Angular\Backend\api\lib\site-packages\rest_framework\serializers.py" in get_fields
1024. info = model_meta.get_field_info(model)
File "C:\Users\Pashupati Pariyar\Desktop\Django + Angular\Backend\api\lib\site-packages\rest_framework\utils\model_meta.py" in get_field_info
39. forward_relations = _get_forward_relationships(opts)
File "C:\Users\Pashupati Pariyar\Desktop\Django + Angular\Backend\api\lib\site-packages\rest_framework\utils\model_meta.py" in _get_forward_relationships
96. not field.remote_field.through._meta.auto_created
Exception Type: AttributeError at /api/register/
Exception Value: 'NoneType' object has no attribute '_meta'
from django.contrib.auth import get_user_model
User = get_user_model()
Always use that to access the user model instead of this
from django.contrib.auth.models import User
to account for custom user models.

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 - TypeError at /admin/login/ has_module_perms() takes 2 positional arguments but 3 were given

I get an error when I login http://127.0.0.1:8000/admin.
I don't know where the error occurred.
This is the error message:
Environment:
Request Method: GET
Request URL: http://127.0.0.1:8000/admin/login/?next=/admin/
Django Version: 2.0.5
Python Version: 3.6.2
Installed Applications:
['users',
'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 "/home/c/Softwares/anaconda3/envs/medic/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner
35. response = get_response(request)
File "/home/c/Softwares/anaconda3/envs/medic/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
128. response = self.process_exception_by_middleware(e, request)
File "/home/c/Softwares/anaconda3/envs/medic/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
126. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/c/Softwares/anaconda3/envs/medic/lib/python3.6/site-packages/django/views/decorators/cache.py" in _wrapped_view_func
44. response = view_func(request, *args, **kwargs)
File "/home/c/Softwares/anaconda3/envs/medic/lib/python3.6/site-packages/django/contrib/admin/sites.py" in login
382. self.each_context(request),
File "/home/c/Softwares/anaconda3/envs/medic/lib/python3.6/site-packages/django/contrib/admin/sites.py" in each_context
302. 'available_apps': self.get_app_list(request),
File "/home/c/Softwares/anaconda3/envs/medic/lib/python3.6/site-packages/django/contrib/admin/sites.py" in get_app_list
470. app_dict = self._build_app_dict(request)
File "/home/c/Softwares/anaconda3/envs/medic/lib/python3.6/site-packages/django/contrib/admin/sites.py" in _build_app_dict
418. has_module_perms = model_admin.has_module_permission(request)
File "/home/c/Softwares/anaconda3/envs/medic/lib/python3.6/site-packages/django/contrib/admin/options.py" in has_module_permission
506. return request.user.has_module_perms(self.opts.app_label)
File "/home/c/Softwares/anaconda3/envs/medic/lib/python3.6/site-packages/django/contrib/auth/models.py" in has_module_perms
422. return _user_has_module_perms(self, module)
File "/home/c/Softwares/anaconda3/envs/medic/lib/python3.6/site-packages/django/contrib/auth/models.py" in _user_has_module_perms
196. if backend.has_module_perms(user, app_label):
Exception Type: TypeError at /admin/login/
Exception Value: has_module_perms() takes 2 positional arguments but 3 were given
users/views.py:
from django.shortcuts import render, redirect
from .forms import RegisterForm
# Create your views here.
def index(request):
return render(request, 'index.html')
def register(request):
redirect_to = request.POST.get('next', request.GET.get('next', ''))
if request.method == 'POST':
form = RegisterForm(request.POST)
if form.is_valid():
form.save()
if redirect_to:
return redirect(redirect_to)
else:
return redirect('/')
else:
form = RegisterForm()
return render(request, 'users/register.html', context={'form': form, 'next': redirect_to})
this is a user login registration authentication code, and only have user app.
in the traceback seem the error didn't occured in my code, so i don't know where it is wrong.
user/models.py:
from django.db import models
from django.contrib.auth.models import AbstractUser
# Create your models here.
class User(AbstractUser):
email = models.EmailField(verbose_name='email',
unique=True, error_messages={'unique': 'Email is already occupied'})
class Meta(AbstractUser.Meta):
pass
If use an AbstractBaseUser add arguments, or try overwriting the function, can use this:
def has_module_perms(self, *args): # or add
# ....
return True

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

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.