'NoneType' object has no attribute '_meta' - django

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.

Related

smtplib.SMTPConnectError: (421, b'Service not available') event after 2-step verification and used generated app password as the HOST_USER_PASSWORD

I am trying to incorporate email confirmation to user registration in my project. The user is supposed to get a confirmation link in their email before successful registration. To achieve this, I used django.core.mail.backends.smtp.EmailBackend as the email backend but I got the error below:
Internal Server Error: /account/register/
Traceback (most recent call last):
File "C:\Users\lenovo.virtualenvs\ecommerce4-MU6fbcf2\lib\site-packages\django\core\handlers\exception.py", line 55, in inner
response = get_response(request)
File "C:\Users\lenovo.virtualenvs\ecommerce4-MU6fbcf2\lib\site-packages\django\core\handlers\base.py", line 197, in get_response response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\lenovo\Desktop\ecommerce4\account\views.py", line 88, in account_register
user.email_user(subject=subject, message=message)
File "C:\Users\lenovo\Desktop\ecommerce4\account\models.py", line 59, in email_user
send_mail(
File "C:\Users\lenovo.virtualenvs\ecommerce4-MU6fbcf2\lib\site-packages\django\core\mail_init.py", line 87, in send_mail
return mail.send()
File "C:\Users\lenovo.virtualenvs\ecommerce4-MU6fbcf2\lib\site-packages\django\core\mail\message.py", line 298, in send
return self.get_connection(fail_silently).send_messages([self])
File "C:\Users\lenovo.virtualenvs\ecommerce4-MU6fbcf2\lib\site-packages\django\core\mail\backends\smtp.py", line 124, in send_messages
new_conn_created = self.open()
File "C:\Users\lenovo.virtualenvs\ecommerce4-MU6fbcf2\lib\site-packages\django\core\mail\backends\smtp.py", line 80, in open
self.connection = self.connection_class(
File "C:\Users\lenovo\AppData\Local\Programs\Python\Python310\lib\smtplib.py", line 258, in init
raise SMTPConnectError(code, msg)
smtplib.SMTPConnectError: (421, b'Service not available')
I allowed two step authentication to my gmail account and then created app password. I used the app password generated for my account as the HOST_USER_PASSWORD
Below is the code how I configured the the setings.py
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST='smtp.gmail.com'
EMAIL_HOST_USER='my gmail'
EMAIL_HOST_PASSWORD='the generated app password'
EMAIL_PORT=587
EMAIL_USE_TLS=True
Below is the model.py for user
import uuid
from django.conf import settings
from django.contrib.auth.models import (AbstractBaseUser, BaseUserManager,
PermissionsMixin)
from django.core.mail import send_mail
from django.db import models
from django.utils.translation import gettext_lazy as _
class Customer(AbstractBaseUser, PermissionsMixin):
email = models.EmailField(_('email address'), unique=True)
name = models.CharField(max_length=150)
mobile = models.CharField(max_length=20, blank=True)
is_active = models.BooleanField(default=False)
is_staff = models.BooleanField(default=False)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
objects = CustomAccountManager()
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['name']
class Meta:
verbose_name = "Accounts"
verbose_name_plural = "Accounts"
def email_user(self, subject, message):
send_mail(
subject,
message,
settings.EMAIL_HOST_USER,
[self.email],
fail_silently=False,
)
def __str__(self):
return self.name:
The view for user registration
from django.contrib import messages
from django.contrib.auth import login, logout
from django.contrib.auth.decorators import login_required
from django.contrib.sites.shortcuts import get_current_site
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import get_object_or_404, redirect, render
from django.template.loader import render_to_string
from django.urls import reverse
from django.utils.encoding import force_bytes, force_str
from django.utils.http import urlsafe_base64_decode, urlsafe_base64_encode
from orders.models import Order
from orders.views import user_orders
from store.models import Product
from .forms import RegistrationForm, UserAddressForm, UserEditForm
from .models import Address, Customer
from .tokens import account_activation_token
def account_register(request):
if request.user.is_authenticated:
return redirect("account:dashboard")
if request.method == "POST":
registerForm = RegistrationForm(request.POST)
if registerForm.is_valid():
user = registerForm.save(commit=False)
user.email = registerForm.cleaned_data["email"]
user.set_password(registerForm.cleaned_data["password"])
current_site = get_current_site(request)
subject = "Activate your Account"
message = render_to_string(
"account/registration/account_activation_email.html",
{
"user": user,
"domain": current_site.domain,
"uid": urlsafe_base64_encode(force_bytes(user.pk)),
"token": account_activation_token.make_token(user),
},
)
user.email_user(subject=subject, message=message)
user.is_active = False
user.save()
return render(request, "account/registration/register_email_confirm.html", {"form": registerForm})
else:
registerForm = RegistrationForm()
return render(request, "account/registration/register.html", {"form": registerForm})

Django Error while saving avatar : expected str, bytes or os.PathLike object, not NoneType

there is an error on cleaned_data['avatar'] (in forms.py) : expected str, bytes or os.PathLike object, not NoneType
this error appears when I sign in with an image for avatar.
I m using Django-allauth but not used to it.... So I add an avatar field which appears in sign_in form but I've the error when submitting.
this is my code: models.py
from django.db import models
from django.contrib.auth.models import AbstractUser
def get_path_name(instance, filename):
path = 'media/avatar/'
name = instance.user.id + "-" + instance.user.email
path = path + name
return path
# custom User model
class CustomUser(AbstractUser):
avatar = models.ImageField(upload_to= get_path_name, blank=True, null=True)
my form:
from django.contrib.auth import get_user_model
from django.contrib.auth.forms import UserCreationForm, UserChangeForm
from django.core.files.images import get_image_dimensions
from django import forms
class CustomUserCreationForm(UserCreationForm):
class Meta:
model = get_user_model()
fields = ('email', 'username', 'avatar')
def clean_avatar(self):
avatar = self.cleaned_data['avatar']
try:
w, h = get_image_dimensions(avatar)
# validate dimensions
max_width = max_height = 100
if w > max_width or h > max_height:
raise forms.ValidationError(
u'Please use an image that is '
'%s x %s pixels or smaller.' % (max_width, max_height))
# validate content type
main, sub = avatar.content_type.split('/')
if not (main == 'image' and sub in ['jpeg', 'pjpeg', 'gif', 'png']):
raise forms.ValidationError(u'Please use a JPEG, '
'GIF or PNG image.')
# validate file size
if len(avatar) > (20 * 1024):
raise forms.ValidationError(
u'Avatar file size may not exceed 20k.')
except AttributeError:
"""
Handles case when we are updating the user profile
and do not supply a new avatar
"""
pass
return avatar
class CustomUserChangeForm(UserChangeForm):
class Meta:
model = get_user_model()
fields = ('email', 'username', 'avatar')
my template:
{% extends '_base.html' %}
{% load crispy_forms_tags %}
{% block title %}
{% endblock title %}
{% block content %}
<h2>Sign Up</h2>
<form method="post">
{% csrf_token %}
{{ form|crispy }}
<button class="btn btn-success" type="submit">Sign Up</button>
</form>
{% endblock content %}
my settings:
AUTH_USER_MODEL = 'accounts.CustomUser'
I've check that migrations works as I can see field in database. But of course empty du to previous error.
I've another issue is that avatar field does not appears in /admin/change/user but I put the field in CustomUserChangeForm(UserChangeForm):
and this is my admin.py:
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth import get_user_model
from .forms import CustomUserCreationForm, CustomUserChangeForm
CustomUser = get_user_model()
class CustomUserAdmin(UserAdmin):
add_form = CustomUserCreationForm
form = CustomUserChangeForm
model = CustomUser
list_display = ['email', 'username', 'avatar']
admin.site.register(CustomUser, CustomUserAdmin)
error traceback:
Environment:
Request Method: POST
Request URL: http://127.0.0.1:8000/accounts/signup/
Django Version: 3.1.2
Python Version: 3.7.7
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'bootstrap4',
'crispy_forms',
'allauth',
'allauth.account',
'django.contrib.sites',
'accounts',
'home']
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 "/Users/hima/venv/lib/python3.7/site-packages/django/core/handlers/exception.py", line 47, in inner
response = get_response(request)
File "/hima/venv/lib/python3.7/site-packages/django/core/handlers/base.py", line 179, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Users//hima/venv/lib/python3.7/site-packages/django/views/generic/base.py", line 70, in view
return self.dispatch(request, *args, **kwargs)
File "/Users//hima/venv/lib/python3.7/site-packages/django/utils/decorators.py", line 43, in _wrapper
return bound_method(*args, **kwargs)
File "/Users//hima/venv/lib/python3.7/site-packages/django/views/decorators/debug.py", line 89, in sensitive_post_parameters_wrapper
return view(request, *args, **kwargs)
File "/Users//hima/venv/lib/python3.7/site-packages/allauth/account/views.py", line 215, in dispatch
return super(SignupView, self).dispatch(request, *args, **kwargs)
File "/Users//hima/venv/lib/python3.7/site-packages/allauth/account/views.py", line 81, in dispatch
**kwargs)
File "/Users//hima/venv/lib/python3.7/site-packages/allauth/account/views.py", line 193, in dispatch
**kwargs)
File "/Users//hima/venv/lib/python3.7/site-packages/django/views/generic/base.py", line 98, in dispatch
return handler(request, *args, **kwargs)
File "/Users//hima/venv/lib/python3.7/site-packages/allauth/account/views.py", line 103, in post
if form.is_valid():
File "/Users//hima/venv/lib/python3.7/site-packages/django/forms/forms.py", line 177, in is_valid
return self.is_bound and not self.errors
File "/Users//hima/venv/lib/python3.7/site-packages/django/forms/forms.py", line 172, in errors
self.full_clean()
File "/Users//hima/venv/lib/python3.7/site-packages/django/forms/forms.py", line 374, in full_clean
self._clean_fields()
File "/Users/hima/venv/lib/python3.7/site-packages/django/forms/forms.py", line 395, in _clean_fields
value = getattr(self, 'clean_%s' % name)()
File "/Users//hima/accounts/forms.py", line 15, in clean_avatar
w, h = get_image_dimensions(avatar)
File "/Users/hima/venv/lib/python3.7/site-packages/django/core/files/images.py", line 47, in get_image_dimensions
file = open(file_or_path, 'rb')
Exception Type: TypeError at /accounts/signup/
Exception Value: expected str, bytes or os.PathLike object, not NoneType

Manager isn't available; 'auth.User' has been swapped for 'members.CustomUser'

i have problem with my code when i want signup error appear Manager isn't available; 'auth.User' has been swapped for 'members.CustomUser' , i try solotion of other questions same like Manager isn't available; 'auth.User' has been swapped for 'members.CustomUser' but all of them asking to replace User = User = get_user_model() but i am not use any User in my code or i dont know where i used that.im new in django , python , js and etc so if my question is silly forgivme .
for more information :1) i used Django Signup Tutorial for create signup method . first that was working well but after i expand my homework project i get error .2)in others app ("products" and "search") no where im not import User and even i dont use CustomUser too bez not need to work with User in this apps.just memebers work with User and CustomUser.
model.py :
from django.contrib.auth.models import AbstractUser
class CustomUser(AbstractUser):
def __str__(self):
return self.email
class Meta:
verbose_name = "member"
verbose_name_plural = "members"
setting.py:
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'card.apps.CardConfig',
'members.apps.MembersConfig',
'search.apps.SearchConfig',
'products.apps.ProductsConfig',
'rest_framework',
]
AUTH_USER_MODEL = 'members.CustomUser'
admin.py:
from django.contrib import admin
from django.contrib.auth import get_user_model
from django.contrib.auth.admin import UserAdmin
from .forms import CustomUserCreationForm, CustomUserChangeForm
from .models import CustomUser
class CustomUserAdmin(UserAdmin):
add_form = CustomUserCreationForm
form = CustomUserChangeForm
model = CustomUser
list_display = ['email', 'username']
admin.site.register(CustomUser, CustomUserAdmin)
form.py:
# users/forms.py
from django.contrib.auth.forms import UserCreationForm, UserChangeForm
from .models import CustomUser
class CustomUserCreationForm(UserCreationForm):
class Meta(UserCreationForm):
model = CustomUser
fields = ('username', 'email')
class CustomUserChangeForm(UserChangeForm):
class Meta:
model = CustomUser
fields = ('username', 'email')
error:
27/Feb/2019 12:36:01] "GET /signup/ HTTP/1.1" 200 5293
Internal Server Error: /signup/
Traceback (most recent call last):
File "C:\shopping\venv\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
response = get_response(request)
File "C:\shopping\venv\lib\site-packages\django\core\handlers\base.py", line 126, in _get_response
response = self.process_exception_by_middleware(e, request)
File "C:\shopping\venv\lib\site-packages\django\core\handlers\base.py", line 124, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\shopping\venv\lib\site-packages\django\views\generic\base.py", line 68, in view
return self.dispatch(request, *args, **kwargs)
File "C:\shopping\venv\lib\site-packages\django\views\generic\base.py", line 88, in dispatch
return handler(request, *args, **kwargs)
File "C:\shopping\venv\lib\site-packages\django\views\generic\edit.py", line 172, in post
return super().post(request, *args, **kwargs)
File "C:\shopping\venv\lib\site-packages\django\views\generic\edit.py", line 141, in post
if form.is_valid():
File "C:\shopping\venv\lib\site-packages\django\forms\forms.py", line 185, in is_valid
return self.is_bound and not self.errors
File "C:\shopping\venv\lib\site-packages\django\forms\forms.py", line 180, in errors
self.full_clean()
File "C:\shopping\venv\lib\site-packages\django\forms\forms.py", line 383, in full_clean
self._post_clean()
File "C:\shopping\venv\lib\site-packages\django\contrib\auth\forms.py", line 107, in _post_clean
super()._post_clean()
File "C:\shopping\venv\lib\site-packages\django\forms\models.py", line 403, in _post_clean
self.instance.full_clean(exclude=exclude, validate_unique=False)
File "C:\shopping\venv\lib\site-packages\django\db\models\base.py", line 1137, in full_clean
self.clean()
File "C:\shopping\venv\lib\site-packages\django\contrib\auth\models.py", line 338, in clean
self.email = self.__class__.objects.normalize_email(self.email)
File "C:\shopping\venv\lib\site-packages\django\db\models\manager.py", line 188, in __get__
cls._meta.swapped,
AttributeError: Manager isn't available; 'auth.User' has been swapped for 'members.CustomUser'
[27/Feb/2019 12:36:04] "POST /signup/ HTTP/1.1" 500 113770
Modify views.py
from django.contrib.auth.forms import UserCreationForm
from django.urls import reverse_lazy
from django.views import generic
class SignUp(generic.CreateView):
form_class = UserCreationForm
success_url = reverse_lazy('login')
template_name = 'signup.html'
to
from .forms import CustomUserCreationForm
from django.urls import reverse_lazy
from django.views import generic
class SignUp(generic.CreateView):
form_class = CustomUserCreationForm
success_url = reverse_lazy('login')
template_name = 'signup.html'
In your forms.py make changes as:
from django.contrib.auth import get_user_model
class CustomUserChangeForm(UserChangeForm):
class Meta:
model = get_user_model()
fields = ('username', 'email')
class CustomUserCreationForm(UserCreationForm):
class Meta:
model = get_user_model()
fields = ('username', 'email')
Also add this script in your members/init.py file:
default_app_config = 'members.apps.MembersConfig'

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

unicode' object has no attribute 'get' in 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.