Я пытаюсь использовать пользовательский объект пользователя с Django 1.6.5, и вот что происходит. Сначала немного моего кода.
def authenticate_user(request):
if request.method == 'GET':
log.debug('GET/authenticate_user called. Returning accounts/login.html to caller.')
args = {}
args.update(csrf(request))
return render(request, 'accounts/login.html', args)
if request.method == 'POST': # A POST means someone is submitting the login form. Let process it.
log.debug('POST/authenticate_user called. Beginning user authentication.')
username = request.POST.get('email', '') # Extract the username from the from or nothing.
password = request.POST.get('password', '') # Extract the password from the form or nothing.
log.debug('Checking the supplied credentials - username %s , password %s ', username, password)
user = authenticate(username=username, password=password) # Call auth.authenticate if the supplied credentials are correct it will
# return a user object. I check that next.
if user is not None: # If a user object was returned.
if user.is_active: # and that user is marked as active.
login(request, user) # then, log them in.
auth_logger.info('Login successful, Username - %s', user, extra={'hostname': hostname, 'sigid': 1, 'severity': 10})
args = {}
return render(request, 'accounts/loggedin.html', args)
else:
#This account is deactivated, no logging in allowed!
log.debug('Login unsuccessful. Account is deactivated. username - %s, password -%s', username, password)
auth_logger.info('Login unsuccessful!, user account is deactivated Username - %s', user, extra={'hostname': hostname, 'sigid': 3, 'severity': 25})
args = {}
return render(request, 'accounts/account_deactivated.html', args)
else:
log.debug('Login unsuccessful. Invalid username / password combination. username - %s, password -%s', username, password)
auth_logger.info('Login unsuccessful. Invalid username / password combination. Username - %s', user, extra={'hostname': hostname, 'sigid': 2, 'severity': 50})
return HttpResponseRedirect('/accounts/invalid_login')
Когда я попытаюсь войти в систему с логином (запрос, пользователь) #, тогда запишите их.
Я получаю ответ
TypeError at /accounts/authenticate_user
login() takes 1 positional argument but 2 were given
Request Method: POST
Request URL: http://localhost:8000/accounts/authenticate_user
Django Version: 1.6.5
Exception Type: TypeError
Exception Value:
login() takes 1 positional argument but 2 were given
Exception Location: /Users/craig/PycharmProjects/fttech/fttech/accounts/views.py in
authenticate_user, line 68
Python Executable: /Users/craig/.virtualenvs/fttech/bin/python
Python Version: 3.4.1
В моем чтении документации Django я, кажется, правильно ее использую:
Как зарегистрировать пользователя в
Если у вас есть аутентифицированный пользователь, которого вы хотите присоединить к текущему сеансу, это делается с помощью функции login().
авторизоваться()
To log a user in, from a view, use login(). It takes an HttpRequest object and a User object. login() saves the users ID in the session, using Djangos session framework.
from django.contrib.auth import authenticate, login
def my_view(request):
username = request.POST['username']
password = request.POST['password']
user = authenticate(username=username, password=password)
if user is not None:
if user.is_active:
login(request, user)
# Redirect to a success page.
else:
# Return a 'disabled account' error message
else:
# Return an 'invalid login' error message.
Я разрабатываю под Python 3.4.1 с Django 1.6.5 и этот выбор модулей:
Django==1.6.5
South==1.0
amqp==1.4.5
anyjson==0.3.3
astroid==1.1.1
billiard==3.3.0.18
celery==3.1.12
coverage==3.7.1
django-admin-bootstrapped==1.6.5
django-braces==1.4.0
django-celery==3.1.10
django-crispy-forms==1.4.0
django-custom-user==0.4
django-debug-toolbar==1.2.1
django-grappelli==2.5.3
django-model-utils==2.0.3
django-redis-sessions==0.4.0
django-tables2==0.15.0
djangorestframework==2.3.14
gnureadline==6.3.3
gunicorn==19.0.0
ipython==2.1.0
kombu==3.0.21
logilab-common==0.62.0
logutils==0.3.3
pytz==2014.4
redis==2.10.1
requests==2.3.0
six==1.7.3
sqlparse==0.1.11
twitter==1.14.3
Я использую модуль django-custom-user для получения объекта AbstractEmailUser, а затем создаю свой пользовательский объект следующим образом.
# Standard Lib Imports
from django.utils import timezone
import logging
# Core Django Imports
from django.db import models
from django.core.mail import send_mail
from django.utils.translation import ugettext_lazy as _
from django.conf import settings
from django.utils.http import urlquote
# Imports from my apps.
# Imports from other third party modules
from custom_user.models import AbstractEmailUser
class CustomUser(AbstractEmailUser):
""" Here is my model based on the django custom user application
"""
first_name = models.CharField('First Name', max_length=254, blank=True)
last_name = models.CharField('Last Name', max_length=254, blank=True)
shipping_address_1 = models.CharField('Shipping address line #1', max_length=64, blank=True)
shipping_address_2 = models.CharField('Shipping address line #1', max_length=64, blank=True)
shipping_address_3 = models.CharField('Shipping address line #1', max_length=64, blank=True)
shipping_city = models.CharField('Shipping city', max_length=32, blank=True)
shipping_state = models.CharField('Shipping state', max_length=2, blank=True)
shipping_zip = models.CharField('Shipping zip code', max_length=10, blank=True)
billing_address_1 = models.CharField('Billing address line #1', max_length=64, blank=True)
billing_address_2 = models.CharField('Billing address line #1', max_length=64, blank=True)
billing_address_3 = models.CharField('Billing address line #1', max_length=64, blank=True)
billing_city = models.CharField('Billing city', max_length=32, blank=True)
billing_state = models.CharField('Billing state', max_length=2, blank=True)
billing_zip = models.CharField('Billing zip code', max_length=10, blank=True)
receive_newsletter = models.BooleanField(_('receive newsletter'), default=False)
time_zone = models.CharField(_('time zone'), max_length=20, blank=True)
type_of_account = models.CharField('Type of Account', max_length=30, default='Alpha Access')
class_of_service = models.CharField('Type of Services', max_length=10, default='Alpha')
account_source = models.CharField('Account source', max_length=50, default='Friend of the family')
account_rebilling_interval = models.CharField(max_length=20, default='Nothing yet')
remaining_bundled_email_alert_credits = models.IntegerField('Remaining Email Alert Credits', max_length=4, default=100)
remaining_bundled_voice_alert_credits = models.IntegerField('Remaining Voice Alert Credits', max_length=4, default=100)
remaining_bundled_sms_alert_credits = models.IntegerField('Remaining SMS Alert Credits', max_length=4, default=100)
remaining_bundled_twitter_alert_credits = models.IntegerField('Remaining Twitter Alert Credits', max_length=4, default=100)
remaining_bundled_pushover_alert_credits = models.IntegerField('Remaining Pushover Alert Credits', max_length=4, default=100)
remaining_bundled_prowl_alert_credits = models.IntegerField('Remaining Prowl Alert Credits', max_length=4, default=100)
remaining_purchased_email_alert_credits = models.IntegerField('Remaining Purchased Alert Credits', default=0)
remaining_purchased_voice_alert_credits = models.IntegerField('Remaining Purchased Alert Credits', default=0)
remaining_purchased_sms_alert_credits = models.IntegerField('Remaining Purchased Alert Credits', default=0)
remaining_purchased_twitter_alert_credits = models.IntegerField('Remaining Purchased Alert Credits', default=0)
remaining_purchased_pushover_alert_credits = models.IntegerField('Remaining Purchased Alert Credits', default=0)
remaining_purchased_prowl_alert_credits = models.IntegerField('Remaining Purchased Alert Credits', default=0)
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['first_name', 'last_name',]
class Meta:
verbose_name =_('user')
verbose_name_plural = _('users')
def get_absolute_url(self):
return "/accounts/%s/" % urlquote(self.email)
def get_full_name(self):
full_name = '%s %s' % (self.first_name, self.last_name)
return full_name.strip()
def get_short_name(self):
return self.first_name
def email_user(self, subject, message, from_email=None):
send_mail(subject, message, from_email, [self.email])
По просьбе отслеживания и моего импорта:
# Standard Lib Imports
import logging
import platform
# Core Django Imports
from django.shortcuts import render
from django.http import HttpResponseRedirect
from django.contrib.auth import authenticate, login
from django.contrib.auth import get_user_model
from django.core.context_processors import csrf
from .forms import CustomUserCreationForm
# Imports from my apps.
from .models import CustomUser
# Imports from other third party modules
ВЫСЛЕЖИВАТЬ
Environment:
Request Method: POST
Request URL: http://localhost:8000/accounts/authenticate_user
Django Version: 1.6.5
Python Version: 3.4.1
Installed Applications:
('django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.admin',
'crispy_forms',
'custom_user',
'accounts',
'alarms',
'alert_targets',
'south',
'debug_toolbar')
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',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'debug_toolbar.middleware.DebugToolbarMiddleware')
Traceback:
File "/Users/craig/.virtualenvs/fttech/lib/python3.4/site-packages/django/core/handlers/base.py" in get_response
112. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Users/craig/PycharmProjects/fttech/fttech/accounts/views.py" in authenticate_user
68. login(request, user) # then, log them in.
Exception Type: TypeError at /accounts/authenticate_user
Exception Value: login() takes 1 positional argument but 2 were given