2013-09-24 77 views
5

Tôi đã cố gắng hàng giờ để đăng nhập vào bảng quản trị django bằng superuser thành công nhưng không thể có quyền kết hợp tên người dùng/pw đúng.Không thể đăng nhập vào django admin sau khi tạo người dùng siêu với mô hình người dùng tùy chỉnh

Tôi muốn người dùng chỉ sử dụng email của họ làm tên người dùng của họ. Tôi cũng đã làm hết sức mình để tái tạo ví dụ trong tài liệu Django here. Tôi đã xóa di chuyển, sycndb và mọi thứ hoạt động ngoại trừ việc đăng nhập vào bảng quản trị.

đang liên quan: Từ models.py:

from django.db import models 
from django.forms import ModelForm 
from django.contrib.auth.models import BaseUserManager, AbstractBaseUser 

class UserManager(BaseUserManager): 
    def create_user(self, email, password=None): 
     """ 
     Creates and saves a User with the given email 
     """ 
     if not email: 
      raise ValueError('Users must have an email address') 

     user = self.model(
      email=UserManager.normalize_email(email), 
     ) 
     user.set_password(password) 
     user.save(using=self._db) 
     return user 

    def create_superuser(self, email, password): 
     """ 
     Creates and saves a superuser with the given email, date of 
     birth and password. 
     """ 
     user = self.create_user(email, 
      password=password 
     ) 

     user.is_admin = True 
     user.is_staff = True 
     user.is_superuser = True 
     user.save(using=self._db) 
     return user 



class User(AbstractBaseUser): 
    objects = UserManager() 
    date_added = models.DateField(auto_now=False, auto_now_add=True) 
    email = models.EmailField(unique=True, db_index=True) 
    USERNAME_FIELD = 'email' 
    REQUIRED_FIELDS = [] 

    def __unicode__(self): 
     return self.email 

    is_active = models.BooleanField(default=True) 
    is_admin = models.BooleanField(default=False) 

    def get_full_name(self): 
    # The user is identified by their email address 
     return self.email 

    def get_short_name(self): 
    # The user is identified by their email address 
     return self.email 

    # On Python 3: def __str__(self): 
    def __unicode__(self): 
     return self.email 

    def has_perm(self, perm, obj=None): 

    # Simplest possible answer: Yes, always 
     return True 

    def has_module_perms(self, app_label): 

    # Simplest possible answer: Yes, always 
     return True 

    def is_staff(self): 

    # Simplest possible answer: All admins are staff 
     return self.is_admin 

Từ admin.py:

from django.contrib import admin 
from app.models import Relationship, Event, User 
from django import forms 
from django.contrib import admin 
from django.contrib.auth.models import Group 
from django.contrib.auth.admin import UserAdmin 
from django.contrib.auth.forms import ReadOnlyPasswordHashField 


class UserCreationForm(forms.ModelForm): 
    """A form for creating new users. Includes all the required 
    fields, plus a repeated password.""" 

    password1 = forms.CharField(label='Password', widget=forms.PasswordInput) 
    password2 = forms.CharField(label='Password confirmation', widget=forms.PasswordInput) 

    class Meta: 
     model = User 
     fields = ('email',) 

    def clean_password2(self): 
     # Check that the two password entries match 
     password1 = self.cleaned_data.get("password1") 
     password2 = self.cleaned_data.get("password2") 
     if password1 and password2 and password1 != password2: 
      raise forms.ValidationError("Passwords don't match") 
     return password2 

    def save(self, commit=True): 
     user = super(UserCreationForm, self).save(commit=False) 
     user.set_password(self.cleaned_data["password1"]) 
     if commit: 
      user.save() 
     return user 


class UserChangeForm(forms.ModelForm): 
    password = ReadOnlyPasswordHashField() 

    class Meta: 
     model = User 

    def clean_password(self): 
     return self.initial["password"] 





class UserAdmin(UserAdmin): 
    # The forms to add and change user instances 
    form = UserChangeForm 
    add_form = UserCreationForm 


    list_display = ('email', 'is_admin') 
    list_filter = ('is_admin',) 
    fieldsets = (
     (None, {'fields': ('email', 'password')}), 
     ('Permissions', {'fields': ('is_admin',)}), 
    ) 

    add_fieldsets = (
     (None, { 
      'classes': ('wide',), 
      'fields': ('email', 'password1', 'password2')} 
     ), 
    ) 
    search_fields = ('email',) 
    ordering = ('email',) 
    filter_horizontal =() 

admin.site.register(User, UserAdmin) 
admin.site.unregister(Group) 

liên quan settings.py mã:

MIDDLEWARE_CLASSES = (
    'django.middleware.common.CommonMiddleware', 
    'django.contrib.sessions.middleware.SessionMiddleware', 
    'django.middleware.csrf.CsrfViewMiddleware', 
    'django.contrib.auth.middleware.AuthenticationMiddleware', 
    'django.contrib.messages.middleware.MessageMiddleware', 
    'django.contrib.auth.middleware.RemoteUserMiddleware', 
    # Uncomment the next line for simple clickjacking protection: 
    # 'django.middleware.clickjacking.XFrameOptionsMiddleware', 
) 

ROOT_URLCONF = 'relrem.urls' 

# Python dotted path to the WSGI application used by Django's runserver. 
WSGI_APPLICATION = 'relrem.wsgi.application' 

TEMPLATE_DIRS = (
    # Put strings here, like "/home/html/django_templates" or "C:/www/django/templates". 
    # Always use forward slashes, even on Windows. 
    # Don't forget to use absolute paths, not relative paths. 
) 

INSTALLED_APPS = (
    'django.contrib.auth', 
    'django.contrib.contenttypes', 
    'django.contrib.sessions', 
    'django.contrib.sites', 
    'django.contrib.messages', 
    'django.contrib.staticfiles', 
    'django.contrib.admin', 
    'app', 
    'south', 

    # Uncomment the next line to enable admin documentation: 
    # 'django.contrib.admindocs', 
) 

AUTH_USER_MODEL = 'app.User' 

AUTHENTICATION_BACKENDS = (
    'django.contrib.auth.backends.RemoteUserBackend', 
) 

Mẫu đầu ra thiết bị đầu cuối từ việc tạo ra một superuser và xem nó trong một bảng:

Email: [email protected] 
Password: 
Password (again): 
Superuser created successfully. 

[ 
{ 
"pk": 1, 
"model": "app.user", 
"fields": { 
    "is_active": true, 
    "last_login": "2013-09-24T02:09:44.996Z", 
    "is_admin": true, 
    "date_added": "2013-09-23", 
    "password": "", 
    "email": "[email protected]" 
} 
} 
] 

Tôi nghĩ rằng nó phải liên quan đến cách lưu mật khẩu và trả lại mật khẩu, vì tôi có nhận được thông báo "Vui lòng nhập đúng email và mật khẩu cho tài khoản của nhân viên . Lưu ý rằng cả hai trường có thể phân biệt chữ hoa chữ thường. "Tôi đã thử xóa tất cả các mã liên quan đến băm và làm sạch nó, nhưng thực sự vẫn trả về một băm trong sử dụng bảng.

tôi hy vọng tôi làm sai điều gì rõ ràng, cảm ơn trước cho bất cứ ai có thời gian để xem xét thông qua toàn bộ câu hỏi này.

Trả lời

9

mã này là tốt. vấn đề là bạn đang sử dụng RemoteUserBackend độc quyền, thay vì default backend:

AUTHENTICATION_BACKENDS = (
    'django.contrib.auth.backends.RemoteUserBackend', 
) 

tôi chưa bao giờ sử dụng nó bản thân mình, nhưng from the docs rõ ràng là nó sẽ chỉ kiểm tra tiêu đề REMOTE_USER trong các yêu cầu của bạn, do đó làm cho nỗ lực đăng nhập mật khẩu của bạn không liên quan.

Bạn có thể thêm ModelBackend mặc định như một dự phòng, nếu bạn wan't để có cả hai sẵn:

AUTHENTICATION_BACKENDS = (
     'django.contrib.auth.backends.RemoteUserBackend', 
     'django.contrib.auth.backends.ModelBackend', 
) 

hoặc thoát khỏi RemoteUserBackend alltogether và có ứng dụng của bạn xác nhận một cách mặc định.

Hy vọng điều này sẽ hữu ích.

+0

Cảm ơn bạn đã dành thời gian xem xét, tiếc là vẫn gặp sự cố tương tự. Tôi đã xóa dòng AUTHENTICATION_BACKEND và mọi thứ liên quan đến RemoteUser và tôi vẫn không thể đăng nhập. – berserkia

+0

@berserkia bạn có thêm 'django.contrib.auth.backends.ModelBackend' vào AUTHENTICATION_BACKENDS của mình không? Bạn có thể cập nhật câu hỏi của mình để hiển thị settings.py hiện tại của mình không? – kirbuchi

+0

Điều đó, nhờ @kirbuchi. – berserkia

Các vấn đề liên quan