[英]get user profile in django
你好我是python和django的新手我需要一個獲取當前用戶配置文件的視圖我知道我應該使用來自User的get_profile但我不知道如何使用它。 我讀了django文件,它沒有幫助我。 這是我從doc中找到的:
from django.contrib.auth.models import User
profile=request.user.get_profile()
Django的文檔說明了這一切,特別是存儲有關用戶的其他信息的部分。 首先,您需要在models.py
某個位置定義模型,其中包含用戶附加信息的字段:
models.py
from django.contrib.auth.models import User
class UserProfile(models.Model):
# This field is required.
user = models.OneToOneField(User)
# Other fields here
accepted_eula = models.BooleanField()
favorite_animal = models.CharField(max_length=20, default="Dragons.")
然后,您需要通過在settings.py
設置AUTH_PROFILE_MODULE
來指示此模型( UserProfile
)是用戶配置文件:
settings.py
...
AUTH_PROFILE_MODULE = 'accounts.UserProfile'
...
您需要使用應用名稱替換accounts
。 最后,您希望在每次創建User
實例時通過注冊post_save
處理程序來創建配置文件,這樣每次創建用戶時Django也會創建他的配置文件:
models.py
from django.contrib.auth.models import User
class UserProfile(models.Model):
# This field is required.
user = models.OneToOneField(User)
# Other fields here
accepted_eula = models.BooleanField()
favorite_animal = models.CharField(max_length=20, default="Dragons.")
def create_user_profile(sender, instance, created, **kwargs):
if created:
UserProfile.objects.create(user=instance)
post_save.connect(create_user_profile, sender=User)
要在視圖中訪問當前用戶的配置文件,只需使用請求提供的User
實例,並在其上調用get_profile :
def your_view(request):
profile = request.user.get_profile()
...
# Your code
基本上django用戶模型將僅為字段提供訪問權限(firstname,lastname,email,password,is_staff,is_active,last_login)。
但是,如果我們要向此模型添加任何額外字段,請說我們需要為每個用戶添加一個名為dateofbirth的新列,然后我們需要在User模型中添加一個名為DOB的列。 但這是不可能的,因為我們無法編輯django用戶模型。
要實現這一點
1.我們可以有一個單獨的新表,其中包含電子郵件ID和DOB列,以便用戶模型中的列與新表中的列進行映射。 但是這將為每個數據庫請求創建一個新的數據庫實例。 如果你想找到客戶的DOB,
在第二種方法中,
不使用django用戶模型,而是使用您自己的自定義模型以及所需的所有字段。 但是,如果任何與安全性相關的更新或對django User模型進行的某些增強,我們就無法直接使用它。 我們需要在最后(無論我們使用自定義模型的地方)進行更多代碼更改。對於開發人員來說,識別代碼並進行更改會有點麻煩。
為了克服上述問題,django引入了django profile,它非常簡單,更靈活。 優點是
如何使用:
在settings.py中創建一個變量AUTH_PROFILE_MODULE = “appname.profiletable”
說,我們創建了一個新的表extrauser,它有DOB,emailid。 要查找客戶的DOB,請使用
a=User.objects.get(email='x@x.xom')
a.get_profile().DOB will give the dateofbirth value from extrauser table.
希望以上細節讓您清楚了解django個人資料。 如果有任何幫助,請告訴我。 我在我的項目中使用過django profile。
老問題,但我認為今天有人看到它可能會從中受益:
Django 1.5增加了 - 輕松 - 擴展用戶模型的能力。 這可能更好,因為你現在只有一個對象而不是兩個! 似乎更現代的方式。
您需要通過設置AUTH_PROFILE_MODULE = 'accounts.UserProfile'
(例如)來指定哪個類是您的“配置文件”
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.