2016-10-15 3 views
0

Попробуйте создать AbstractBaseUser и пользовательский auth.Создать AbstractBaseUser

models.py

class Account(AbstractBaseUser): 
    account_id = models.AutoField(primary_key=True) 
    first_name = models.CharField(max_length=255) 
    last_name = models.CharField(max_length=255) 
    birthday_date = models.DateField(blank=True, null=True) 
    sex = models.TextField(blank=True, null=True) # This field type is a guess. 
    country = models.CharField(max_length=255, blank=True, null=True) 
    city = models.CharField(max_length=255, blank=True, null=True) 
    email = models.CharField(unique=True, max_length=320) 
    mobile_number = models.CharField(unique=True, max_length=45, blank=True, null=True) 
    registration_date = models.DateTimeField() 
    expired_date = models.DateField(blank=True, null=False) 
    account_type = models.TextField() # This field type is a guess. 

    objects = AccountManager 

    USERNAME_FIELD = 'email' 

    REQUIRED_FIELDS = ['first_name', 'last_name', 'registration_date', 'account_type'] 

    class Meta: 
     managed = False 
     db_table = 'account' 

AccountManager

class AccountManager(BaseUserManager): 
    def create_user(self, first_name, last_name, birthday_date, sex, country, city, email, 
        mobile_number, registration_date, expired_date, account_type, password): 

     fields = [first_name, last_name, birthday_date, sex, country, email, 
        mobile_number, registration_date, expired_date, account_type, password] 

     user = self.model(
      email=self.normalize_email(email), 
      first_name=first_name, 
      last_name=last_name, 
      birthday_date=birthday_date, 
      sex=sex, 
      country=country, 
      city=city, 
      mobile_number=mobile_number, 
      registration_date=registration_date, 
      expired_date=expired_date, 
      account_type=account_type, 
     ) 

     user.set_password(password) 
     user.save() 
     return user 

setting.py

INSTALLED_APPS = [ 
     'models', 
     ...] 
    AUTH_USER_MODEL = 'models.Account' 

    AUTHENTICATION_BACKENDS = ('models.backend.EmailOrPhoneBackend',) 

backend.py

class EmailOrPhoneBackend(object): 
    def authenticate(self, username=None, password=None, **kwargs): 
     try: 
      # Try to fetch the user by searching the username or email field 
      user = Account.objects.get(Q(mobile_number=username) | Q(email=username)) 
      if user.check_password(password): 
       return user 
     except Account.DoesNotExist: 
      # Run the default password hasher once to reduce the timing 
      # difference between an existing and a non-existing user (#20760). 
      Account().set_password(password) 

Стараюсь creatae нового пользователя путем анализа почтовых данных и сохранение его в БД:

def post(self, request, *args, **kwargs): 
    postDict = dict(request.POST) 

    account = Account(); 

    for element in postDict: 
     jsonPostDict = json.loads(element) 

     for value in jsonPostDict: 

      print('key is : ' + value) 
      print('value is : ' + jsonPostDict[value]) 

      if value == 'firstName': 
       account.first_name = jsonPostDict[value] 
       print('set first name') 
      if value == 'lastName': 
       account.last_name = jsonPostDict[value] 
       print('set last name') 
      if value == 'email': 
       account.email = jsonPostDict[value] 
       print('set email') 
      if value == 'password': 
       account.set_password(jsonPostDict[value]) 
       print('set password') 

    account.account_type = 'free' 
    account.save() 

    return HttpResponseRedirect("/admin", request, *args, **kwargs) 

Вход:

key is : firstName 
value is : a 
set first name 
key is : email 
value is : [email protected] 
set email 
key is : password 
value is : qwdsfgh23e 
set password 
key is : lastName 
value is : a 
set last name 
Internal Server Error: /signup 
Traceback (most recent call last): 
    File "/usr/local/lib/python3.4/dist-packages/django/db/backends/utils.py", line 64, in execute 
    return self.cursor.execute(sql, params) 
psycopg2.ProgrammingError: ERROR: row "password" in table "account" does not exist 
LINE 1: INSERT INTO "account" ("password", "last_login", "first_name... 
          ^


The above exception was the direct cause of the following exception: 

Traceback (most recent call last): 
    File "/usr/local/lib/python3.4/dist-packages/django/core/handlers/exception.py", line 39, in inner 
    response = get_response(request) 
    File "/usr/local/lib/python3.4/dist-packages/django/core/handlers/base.py", line 187, in _get_response 
    response = self.process_exception_by_middleware(e, request) 
    File "/usr/local/lib/python3.4/dist-packages/django/core/handlers/base.py", line 185, in _get_response 
    response = wrapped_callback(request, *callback_args, **callback_kwargs) 
    File "/usr/local/lib/python3.4/dist-packages/django/views/generic/base.py", line 68, in view 
    return self.dispatch(request, *args, **kwargs) 
    File "/usr/local/lib/python3.4/dist-packages/django/views/generic/base.py", line 88, in dispatch 
    return handler(request, *args, **kwargs) 
    File "/usr/finstatement/project/account_management/views.py", line 44, in post 
    account.save() 
    File "/usr/local/lib/python3.4/dist-packages/django/contrib/auth/base_user.py", line 80, in save 
    super(AbstractBaseUser, self).save(*args, **kwargs) 
    File "/usr/local/lib/python3.4/dist-packages/django/db/models/base.py", line 796, in save 
    force_update=force_update, update_fields=update_fields) 
    File "/usr/local/lib/python3.4/dist-packages/django/db/models/base.py", line 824, in save_base 
    updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields) 
    File "/usr/local/lib/python3.4/dist-packages/django/db/models/base.py", line 908, in _save_table 
    result = self._do_insert(cls._base_manager, using, fields, update_pk, raw) 
    File "/usr/local/lib/python3.4/dist-packages/django/db/models/base.py", line 947, in _do_insert 
    using=using, raw=raw) 
    File "/usr/local/lib/python3.4/dist-packages/django/db/models/manager.py", line 85, in manager_method 
    return getattr(self.get_queryset(), name)(*args, **kwargs) 
    File "/usr/local/lib/python3.4/dist-packages/django/db/models/query.py", line 1045, in _insert 
    return query.get_compiler(using=using).execute_sql(return_id) 
    File "/usr/local/lib/python3.4/dist-packages/django/db/models/sql/compiler.py", line 1054, in execute_sql 
    cursor.execute(sql, params) 
    File "/usr/local/lib/python3.4/dist-packages/django/db/backends/utils.py", line 79, in execute 
    return super(CursorDebugWrapper, self).execute(sql, params) 
    File "/usr/local/lib/python3.4/dist-packages/django/db/backends/utils.py", line 64, in execute 
    return self.cursor.execute(sql, params) 
    File "/usr/local/lib/python3.4/dist-packages/django/db/utils.py", line 94, in __exit__ 
    six.reraise(dj_exc_type, dj_exc_value, traceback) 
    File "/usr/local/lib/python3.4/dist-packages/django/utils/six.py", line 685, in reraise 
    raise value.with_traceback(tb) 
    File "/usr/local/lib/python3.4/dist-packages/django/db/backends/utils.py", line 64, in execute 
    return self.cursor.execute(sql, params) 
django.db.utils.ProgrammingError: ОШИБКА: row "password" in table "account" does not exist 
LINE 1: INSERT INTO "account" ("password", "last_login", "first_name... 
          ^

[15/Oct/2016 08:40:22] "POST /signup HTTP/1.1" 500 147276 

Я должен добавить пароль строку в моей базе данных, или я делаю некоторые ошибки в настройке auth или backend?

ответ

0

Посмотрите на вас Account модель. Не существует поля password. Вы должны добавить это поле и сохранить данные там.

Смежные вопросы