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.
Related
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
I'm failing to authenticate my user upon the registration. I've found out the solution for one time link token authentication, was tampering with ModelBackend you can see the basic solution here, I'll paste up my implementation because I'm using CBV for the view.
Custom ModelBackend:
from django.contrib.auth.backends import ModelBackend
import logging
from business_accounts.models.my_user import MyUser
logger = logging.getLogger(__name__)
class UrlTokenBackend(ModelBackend):
"""
Custom login backend that will accept token allow click url login
"""
def authenticate(self, request, token=None):
try:
user = MyUser.objects.get(token=token)
except MyUser.DoesNotExist:
logger.warning('My user=%s does not exist', user)
return None
if not user.is_active:
return None
def get_user(self, user_id):
try:
return MyUser.objects.get(pk=user_id)
except MyUser.DoesNotExist:
logger.warning('User with this id=%s does not exists', user_id)
return None
The authentication middleware is registered here
AUTHENTICATION_BACKENDS = (
'business_accounts.backends.UrlTokenBackend',
# Needed to login by username in Django admin, regardless of `allauth`
'django.contrib.auth.backends.ModelBackend',
# `allauth` specific authentication methods, such as login by e-mail
'allauth.account.auth_backends.AuthenticationBackend',
)
Custom view is:
from django.contrib.auth import authenticate, login
from django.shortcuts import redirect
from django.views.generic import View
class UrlGatewayLogin(View):
def get(self, request):
token = request.GET.get('token')
user = authenticate(token=token)
login(request, user)
return redirect('dashboard')
and the url is
url(r'^auth/login/', UrlGatewayLogin.as_view(), name='auth-login')
Now I'll construct a url for the login, like so, http:/localhost:8000/auth/login/?token=12323344 so the whole process will just login the user over this link and redirect him to the dashboard.
The login is showing me this error:
Environment:
Request Method: GET
Request URL: http://localhost:8888/auth/login/?token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE1MjYzNjE5MTksInVzZXJfaWQiOjcwLCJlbWFpbCI6ImFkbWluQGFkbWluLmFpIiwidXNlcm5hbWUiOiJhZG1pbkBhZG1pbi5haSIsIm9yaWdfaWF0IjoxNTI2MzU4OTE5fQ.qyR5SYZ1uO0reVSRjcFdXGGhgfKhdu1eU277UAGU5l8
Django Version: 1.8.5
Python Version: 3.4.2
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.sites',
'allauth',
'allauth.account',
'allauth.socialaccount',
'allauth.socialaccount.providers.facebook',
'allauth.socialaccount.providers.twitter',
'allauth.socialaccount.providers.foursquare',
'allauth.socialaccount.providers.google',
'rest_framework',
'rest_framework_swagger',
'django_filters',
'corsheaders',
'gunicorn',
'googleads',
'django_nose',
'webpack_loader',
'common',
'business_accounts',
'search',
'platforms_search',
'locations',
'reviews',
'socialmedia',
'inbox',
'stats',
'usermanagement',
'connect',
'dashboard',
'freetrial',
'billing',
'demo',
'social_tickets',
'external',
'test_account']
Installed Middleware:
('django.contrib.sessions.middleware.SessionMiddleware',
'corsheaders.middleware.CorsMiddleware',
'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',
'django.middleware.common.CommonMiddleware')
Traceback:
File "/srv/bspotted.net/venv/lib/python3.4/site-packages/django/core/handlers/base.py" in get_response
132. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/srv/bspotted.net/venv/lib/python3.4/site-packages/django/views/generic/base.py" in view
71. return self.dispatch(request, *args, **kwargs)
File "/srv/bspotted.net/venv/lib/python3.4/site-packages/django/views/generic/base.py" in dispatch
89. return handler(request, *args, **kwargs)
File "/srv/bspotted.net/app/business_accounts/views/url_gateway_login.py" in get
10. login(request, user)
File "/srv/bspotted.net/venv/lib/python3.4/site-packages/django/contrib/auth/__init__.py" in login
111. request.session[SESSION_KEY] = user._meta.pk.value_to_string(user)
File "/srv/bspotted.net/venv/lib/python3.4/site-packages/django/utils/functional.py" in inner
226. return func(self._wrapped, *args)
Exception Type: AttributeError at /auth/login/
Exception Value: 'AnonymousUser' object has no attribute '_meta'
So can someone explain why is this happening and how can I overcome this, thank you.
authenticate() should return user object:
class UrlTokenBackend(ModelBackend):
"""
Custom login backend that will accept token allow click url login
"""
def authenticate(self, request, token=None):
try:
user = MyUser.objects.get(token=token)
except MyUser.DoesNotExist:
logger.warning('My user=%s does not exist', user)
return None
if not user.is_active:
return None
return user
Working on a project for school I know how to do this in flask but learning django. I am trying to make sure that a valid email is entered before it post. If I do not do the if else statement the form goes though but wont validate it. I have the following and the only part not working is the one part with comments but I included the whole views.py incase you see something at top that could be wrong.
views.py
from django.shortcuts import render, redirect
from .models import User
import re
EMAIL_REGEX = re.compile(r'^[a-zA-Z0-9.+_-]+#[a-zA-Z0-9._-]+\.[a-zA-Z]+$')
# Create your views here.
def index(request):
return render(request, "emailvalidation/index.html" )
def create(request):
if request.method == 'POST': #here down
if len(request.form['email']) < 1:
add_message("Invalid Email Address!") #if i take out the if else the form does work
elif not EMAIL_REGEX.match(request.form['email']): #the validation.
add_message("Invalid Email Address!")
else:
User.objects.create(email = request.POST['email'] ) #to here
context ={
"email": User.objects.all(),
}
return render(request, 'emailvalidation/success.html' ,context)
the traceback error
Environment:
Request Method: POST
Request URL: http://localhost:8000/user
Django Version: 1.10.6
Python Version: 2.7.10
Installed Applications:
['apps.emailvalidation',
'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:\Users\dbhol\Desktop\DojoAssignments\Python\myenvirnoments\djangoENv\lib\site-packages\django\core\handlers\exception.py" in inner
42. response = get_response(request)
File "C:\Users\dbhol\Desktop\DojoAssignments\Python\myenvirnoments\djangoENv\lib\site-packages\django\core\handlers\base.py" in _get_response
187. response = self.process_exception_by_middleware(e, request)
File "C:\Users\dbhol\Desktop\DojoAssignments\Python\myenvirnoments\djangoENv\lib\site-packages\django\core\handlers\base.py" in _get_response
185. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\dbhol\Desktop\DojoAssignments\Python\myenvirnoments\django2\emailval\emailval\apps\emailvalidation\views.py" in create
15. if len(request.form['email']) < 1:
Exception Type: AttributeError at /user
Exception Value: 'WSGIRequest' object has no attribute 'form'
request does not have a form attribute. Since you already have if request.method == "POST" - you can safely do the following:
change
request.form['email']
with
request.POST['email']
Ideally, you should be using django forms for handing the validations etc. Django forms have better validation logic, regex validators, etc..
This issue is rather strange. Here's a stack trace:
Environment:
Request Method: GET
Request URL: http://localhost/en/dashboard
Django Version: 1.9.6
Python Version: 2.7.12
Installed Applications:
('django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.admin',
'django_mongoengine',
'django_mongoengine.mongo_auth',
'django_mongoengine.mongo_admin.sites',
'django_mongoengine.mongo_admin',
'django_adyen',
'spiral_api',
'rest_framework',
'rest_framework_mongoengine',
'spiral_admin',
'rest_framework_docs')
Installed Middleware:
('django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.locale.LocaleMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'spiral_api.middlewares.BehalfUserMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'spiral_api.middlewares.AuthHeaderMiddleware')
Traceback:
File "/usr/local/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
235. response = middleware_method(request, response)
File "/code/django_app/spiral_api/middlewares.py" in process_response
11. def process_response(self, request, response):
File "/usr/local/lib/python2.7/site-packages/django/utils/functional.py" in inner
204. self._setup()
File "/usr/local/lib/python2.7/site-packages/django/utils/functional.py" in _setup
351. self._wrapped = self._setupfunc()
File "/code/django_app/spiral_api/middlewares.py" in get_user
18. user = get_user_middleware(request)
Exception Type: TypeError at /en/dashboard
Exception Value: unbound method is_authenticated() must be called with AbstractBaseUser instance as first argument (got nothing instead)
Here's a middleware:
from functools import partial
from django.contrib.auth.middleware import get_user as get_user_middleware
from django.contrib.auth.models import AbstractBaseUser
from django.utils.functional import SimpleLazyObject
from spiral_api.models import SpiralUserProfile
class AuthHeaderMiddleware(object):
def process_response(self, request, response):
response['is_login'] = int(request.user.is_active) if hasattr(request, 'user') else 0
return response
class BehalfUserMiddleware(object):
def get_user(self, request):
user = get_user_middleware(request)
if user.is_authenticated():
profile = SpiralUserProfile.objects.get(user=user)
return profile.behalf or user
else:
return user
def process_request(self, request):
assert hasattr(request, 'session'), (
"The Django authentication middleware requires session middleware "
"to be installed. Edit your MIDDLEWARE_CLASSES setting to insert "
"'django.contrib.sessions.middleware.SessionMiddleware' before "
"'django.contrib.auth.middleware.AuthenticationMiddleware'."
)
request.user = SimpleLazyObject(partial(self.get_user, request))
request.behalf = SimpleLazyObject(lambda: get_user_middleware(request))
Sadly project is not mine. From exception you see it points to get_user_middleware() function. I've tried to add print in there, also as sys.exit(), nothing works.. it seems to be it doesn't even come to that function. Here's how middleware setup looks in Settings:
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.locale.LocaleMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
# 'django.contrib.auth.middleware.AuthenticationMiddleware',
'spiral_api.middlewares.BehalfUserMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'spiral_api.middlewares.AuthHeaderMiddleware'
)
Also a model SpiralUserProfile has a field behalf which is reference to model User. I'm completely puzzled why exception shows error in a place where interpreter doesn't even come to? How to solve this issue?
Versions of requirements.txt:
nose==1.3.7
pinocchio==0.4.2
django_nose==1.4.4
bjoern==1.4.3
amqp==1.4.9
anyjson==0.3.3
apiclient==1.0.3
billiard==3.3.0.23
blinker==1.4
build==1.0.2
celery==3.1.23
Django==1.9.6
django-bootstrap3==7.0.1
django-crispy-forms==1.6.0
django-fanout==1.1.1
django-filter==0.13.0
git+https://github.com/MongoEngine/django-mongoengine
django-redis==4.4.3
django-rest-framework-mongoengine==3.3.0
djangorestframework==3.3.3
drfdocs==0.0.9
EasyProcess==0.2.2
fanout==1.2.0
git+http://github.com/google/google-api-python-client/
gunicorn==19.3.0
httplib2==0.9.2
kombu==3.0.35
mongodbforms==0.3
mongoengine==0.10.6
nltk==3.2.1
oauth2==1.9.0.post1
oauth2client==2.1.0
oauthlib==1.1.2
Pillow==3.2.0
psycopg2==2.6
pubcontrol==2.2.7
pyasn1==0.1.9
pyasn1-modules==0.0.8
PyInvoice==0.1.7
PyJWT==1.4.0
pymongo==3.2.2
python-openid==2.2.5
pytz==2016.4
PyVirtualDisplay==0.2
qrcode==5.3
qrplatba==0.3.4
redis==2.10.5
reportlab==3.3.0
requests==2.10.0
requests-oauthlib==0.6.1
rsa==3.4.2
selenium==2.53.2
simplejson==3.8.2
six==1.10.0
uritemplate==0.6
urllib3==1.15.1
xvfbwrapper==0.2.8
zope.dottedname==4.1.0
pyPdf
I am not sure how this ever worked, but I can see why you'd get that error. In django-mongoengine/mongo_auth/models.py I see this:
class BaseUser(object):
is_anonymous = AbstractBaseUser.is_anonymous
is_authenticated = AbstractBaseUser.is_authenticated
class User(BaseUser, document.Document):
...
which seems to be the source of the error.
You can make it work by modifying that library so that the User class implements those methods directly:
class User(document.Document):
...
def is_anonymous(self):
"""
Always returns False. This is a way of comparing User objects to
anonymous users.
"""
return False
def is_authenticated(self):
"""
Always return True. This is a way to tell if the user has been
authenticated in templates.
"""
return True
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.