· 7 years ago · Sep 27, 2018, 09:50 AM
1AttributeError: Manager isn't available; 'auth.User' has been swapped for 'accounts.UserProfile'
2
3from django.contrib.auth import get_user_model
4User = get_user_model()
5
6django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet.
7
8> import os import datetime from django.conf import settings
9>
10>
11> # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR =
12> os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
13>
14>
15> # Quick-start development settings - unsuitable for production
16> # See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/
17>
18> # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'ruho^096p16m=vg!sn(&o46-qwe#y(zf^bee&!wujo-4h@%hgl'
19>
20> # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True
21>
22> ALLOWED_HOSTS = ['*']
23>
24>
25> # Application definition INSTALLED_APPS = [
26> 'rest_framework', # Django rest framework 套件
27> 'rest_framework.authtoken',
28> 'grappelli', # grappelli admin 版é¢å¥—ä»¶
29> 'django.contrib.admin',
30> 'django.contrib.auth',
31> 'django.contrib.contenttypes',
32> 'django.contrib.sessions',
33> 'django.contrib.messages',
34> 'django.contrib.staticfiles',
35> 'django.contrib.sites',
36> 'rest_auth',
37> 'rest_auth.registration',
38> 'debug_toolbar', # django debug 工具列
39> 'django_extensions', # django 擴展套件,æä¾›ä¸€äº›cli指令
40> 'import_export', # å¯å¾ž admin 匯出資料 (ç›®å‰å› 版本關係,所以無法使用)
41> 'django_filters', # 優化從model query 資料效能
42> 'allauth', # django allauth 套件
43> 'allauth.account', # django allauth 套件
44> 'allauth.socialaccount', # django allauth 套件
45> 'allauth.socialaccount.providers.facebook', # django allauth 套件,è¨å®šä½¿ç”¨FB登入用
46> # 'rest_framework_docs', # å¯è¼¸å‡ºAPI文件 (ç›®å‰å› 版本關係,所以無法使用)
47> 'books', # 書ç±APP
48> 'accounts',# 使用者帳號APP ]
49>
50> from django.contrib.auth import get_user_model User = get_user_model()
51>
52> AUTH_USER_MODEL = 'accounts.UserProfile'
53>
54> MIDDLEWARE = [
55> 'django.middleware.security.SecurityMiddleware',
56> 'django.contrib.sessions.middleware.SessionMiddleware',
57> 'django.middleware.common.CommonMiddleware',
58> 'django.middleware.csrf.CsrfViewMiddleware',
59> 'django.contrib.auth.middleware.AuthenticationMiddleware',
60> 'django.contrib.messages.middleware.MessageMiddleware',
61> 'django.middleware.clickjacking.XFrameOptionsMiddleware',
62> 'debug_toolbar.middleware.DebugToolbarMiddleware', ]
63>
64> INTERNAL_IPS = ('127.0.0.1',)
65>
66> # é…ç½®django_rest_framework REST_FRAMEWORK = {
67> # Use Django's standard `django.contrib.auth` permissions,
68> # or allow read-only access for unauthenticated users.
69> 'DEFAULT_AUTHENTICATION_CLASSES': (
70> 'rest_framework_jwt.authentication.JSONWebTokenAuthentication',
71> 'rest_framework.authentication.SessionAuthentication',
72> 'rest_framework.authentication.BasicAuthentication',
73> ),
74> 'DEFAULT_PERMISSION_CLASSES': [
75> 'rest_framework.permissions.IsAuthenticated',
76> ] }
77>
78> # é…ç½®JQueryå’ŒSHOW_TOOLBAR_​​CALLBACK DEBUG_TOOLBAR_CONFIG = {
79> 'JQUERY_URL': 'https://ajax.googleapis.com/ajax/libs/dojo/1.13.0/dojo/dojo.js',
80> 'SHOW_TOOLBAR_​​CALLBACK': lambda request: DEBUG, }
81 ....
82
83from django.db import models
84from django.conf import settings
85from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin
86from books.models import Bookinfo
87from datetime import datetime, timedelta
88import jwt
89
90from django.contrib.auth import get_user_model
91User = get_user_model()
92
93
94# 建立usermanager定義使用者和高級使用者instance作為數據查詢的管ç†å™¨
95class UserManager(BaseUserManager):
96
97 # 建立一般使用者
98 def create_user(self, username, email, password=None):
99
100 # åˆ¤æ–·ä½¿ç”¨è€…æ˜¯å¦æœ‰è¼¸å…¥ä½¿ç”¨è€…å稱和email
101 if username is None:
102 raise TypeError('請填入使用者å稱')
103 if email is None:
104 raise TypeError('è«‹å¡«å…¥Email')
105
106 user = self.model(
107 username=username,
108 email=self.normalize_email(email)
109 )
110 user.set_password(password)
111 user.save()
112
113 return user
114
115 # 建立高級使用者
116 def create_superuser(self, username, email, password):
117
118 if password is None:
119 raise TypeError('Superusers must have a password')
120
121 # 直接使用建立一般使用者方法
122 user = self.create_user(username, email, password)
123 user.is_superuser = True
124 user.is_staff = True
125 user.save()
126
127 return user
128
129# 定義使用者資料表
130class UserProfile(AbstractBaseUser, PermissionsMixin):
131
132 class Meta:
133 db_table = 'userprofile'
134
135 # 定義使用者需填入資料
136 username = models.CharField(max_length=255, db_index=True, unique=True, verbose_name='用戶å')
137 user_image = models.ImageField(upload_to='img', verbose_name='用戶圖片')
138 email = models.EmailField(db_index=True, unique=True, verbose_name='é›»å郵件')
139 birthday = models.DateField(verbose_name='生日')
140 GENDER_CHOICES = (
141 ('Male', 'ç”·'),
142 ('Female', '女')
143 )
144 gender = models.CharField(
145 max_length=5, choices=GENDER_CHOICES, verbose_name='性別')
146 location = models.CharField(max_length=255, blank=True, verbose_name='地å€')
147 about = models.TextField(blank=True, verbose_name='關於我')
148
149 # 確èªä½¿ç”¨è€…是å¦é‚„有å†ä½¿ç”¨å¹³å°
150 is_active = models.BooleanField(default=True)
151 # 確èªä½¿ç”¨è€…是å¦ç‚ºç®¡ç†è€…
152 is_staff = models.BooleanField(default=False)
153
154 # 創建時間
155 create_at = models.DateTimeField(auto_now_add=True)
156 # 更新資料時間
157 update_at = models.DateTimeField(auto_now=True)
158
159 # 外éµ:將評論和書櫃關è¯èµ·ä¾†
160 com = models.OneToOneField(
161 'Comments', null=True, blank=True, on_delete=models.CASCADE, verbose_name='è©•è«–ID')
162 bookshelf = models.OneToOneField(
163 'bookshelf', null=True, blank=True, on_delete=models.CASCADE, verbose_name='書櫃ID')
164
165 # The `USERNAME_FIELD` property tells us which field we will use to log in.
166 # In this case we want it to be the email field.
167 USERNAME_FIELD = 'email'
168 REQUIRED_FIELDS = ['username']
169
170 # Tells Django that the UserManager class defined above should manage
171 # objects of this type.
172 objects = UserManager()
173
174 def __str__(self):
175 """
176 Returns a string representation of this `User`.
177
178 This string is used when a `User` is printed in the console.
179 """
180 return self.email
181
182 @property
183 def token(self):
184 """
185 Allows us to get a user's token by calling `user.token` instead of
186 `user.generate_jwt_token().
187
188 The `@property` decorator above makes this possible. `token` is called
189 a "dynamic property".
190 """
191 return self._generate_jwt_token()
192
193 def get_full_name(self):
194 """
195 This method is required by Django for things like handling emails.
196 Typically this would be the user's first and last name. Since we do
197 not store the user's real name, we return their username instead.
198 """
199 return self.username
200
201 def get_short_name(self):
202 """
203 This method is required by Django for things like handling emails.
204 Typically, this would be the user's first name. Since we do not store
205 the user's real name, we return their username instead.
206 """
207 return self.username
208
209 def _generate_jwt_token(self):
210 """
211 Generates a JSON Web Token that stores this user's ID and has an expiry
212 date set to 60 days into the future.
213 """
214 dt = datetime.now() + timedelta(days=60)
215
216 token = jwt.encode({
217 'id': self.pk,
218 'exp': int(dt.strftime('%s'))
219 }, settings.SECRET_KEY, algorithm='HS256')
220
221 return token.decode('utf-8') ....
222
223from django import forms
224from django.contrib.auth.forms import UserCreationForm, UserChangeForm
225from .models import UserProfile
226
227from django.contrib.auth import get_user_model
228User = get_user_model()
229
230class UserProfileForm(UserCreationForm):
231 class Meta:
232 model = UserProfile
233 fields = (
234 'username', 'user_image', 'email', 'gender',
235 'birthday', 'location', 'about'
236 )
237
238
239class UserProfileChangeForm(UserChangeForm):
240 class Meta:
241 model = UserProfile
242 fields = UserChangeForm.Meta.fields
243
244from django.contrib import admin
245from django.contrib.auth.admin import UserAdmin
246from .models import Comments, Bookshelf, UserProfile
247from import_export.admin import ImportExportModelAdmin
248from .forms import UserCreationForm, UserChangeForm
249
250from django.contrib.auth import get_user_model
251User = get_user_model()
252
253class UserProfileAdmin(UserAdmin):
254 add_form = UserCreationForm
255 form = UserChangeForm
256 model = UserProfile
257 list_display = ('_id', 'user_name', 'e-mail', 'gender',
258 'birthday', 'location', 'created_at')
259 search_fields = ['user_name', 'gender']
260
261class CommentsAdmin(ImportExportModelAdmin):
262 list_display = ('_id', 'rating', 'read_status', 'created_time')
263 search_fields = ['rating']
264
265class BookshelfAdmin(ImportExportModelAdmin):
266 list_display = ('_id', 'created_time')
267 # search_fields = ['gender']
268
269
270admin.site.register(UserProfile, UserProfileAdmin)
271admin.site.register(Comments, CommentsAdmin)
272admin.site.register(Bookshelf, BookshelfAdmin)