2017-04-10 118 views
0

這聽起來像一百萬個其他類似的問題,但已經被問到,但我忍受。Django自定義用戶

我是新來的Django,但不是Python。我在YouTube上跟着newboston的教程,所以我對框架的工作原理有了一個大概的瞭解。作爲一個學習鍛鍊,我想創建一個「社交網絡」類型的網站,用戶可以在一個配置文件註冊,填寫以下字段:

-Profile pic (file) 
-Bio + personal info 
-List with add functionality, meaning the user can press a "+" and add new things to the list. The final, full length list is what I want to store. 
-Random file upload field. 

如何去擴展底座用戶類?我寧願從頭開始學習,但如果有好的指導,歡迎使用all-auth的想法。

與其將問題視爲重複,不如將指向我的初學者的最佳指南,以便與官方的Django文檔不同?

其他線程的鏈接也可以。網上有很多關於這方面的信息,有幾頁使用框架的一部分而沒有任何解釋。

+0

https://simpleisbetterthancomplex.com/tutorial/2016/07/22/how-to-extend-django-user-model.html –

+0

我會從[官方文檔]開始(https://docs.djangoproject .COM/EN /開發/主題/認證/定製/#延長-的現有用戶模型)。由於您只想添加額外的字段並且不會更改認證行爲,所以最好的辦法是使用「配置文件方法」。 – Selcuk

回答

0

Django所有Auth文檔都不錯。您可以擴展您的用戶配置文件是這樣的:

models.py

class StudentProfile(models.Model): 
    userId = models.OneToOneField(User, on_delete=models.CASCADE, related_name='student_profile') 
    user_dp = models.ImageField(upload_to = upload_location, null = True, blank=True, width_field="width_field", height_field="height_field") 
    height_field = models.IntegerField(default=0, null=True, blank=True) 
    width_field = models.IntegerField(default=0, null=True, blank=True) 
    first_name = models.CharField(max_length=120, blank=True) 
    last_name = models.CharField(max_length=120, blank=True) 
    gender_choices = (
     ('Unspecified', 'Unspecified'), 
     ('Male', 'Male'), 
     ('Female', 'Female'), 
     ('Other', 'Other'), 
    ) 

    gender = models.CharField(max_length=20, choices=gender_choices, default='Unspecified') 
    college_name = models.CharField(max_length=500, blank=True) 
    date_of_birth = models.DateField(blank=True, null=True) 
    graduation_year = models.IntegerField(blank=True, null=True) 
    description = models.TextField(blank = True, null=True) 
    created_on = models.DateTimeField(auto_now=False, auto_now_add=True) 
    updated_on = models.DateTimeField(auto_now=True, auto_now_add=False) 
    onboarded = models.BooleanField(default=False) 
    address = models.ForeignKey(Address, blank=True, null=True) 

    def __str__(self): 
     return self.first_name + self.last_name 

這是使用用戶(Django的內置AUTH)作爲onetoone場學生簡介。我一直在我的項目中使用它。如果你想要社交登錄,建議使用所有身份驗證。您可以使用預保存信號/在用戶註冊時擴展默認註冊以創建用戶配置文件。像這樣:

class SocialAccountAdapter(DefaultSocialAccountAdapter): 
    def save_user(self, request, sociallogin, form=None): 
     user = super(SocialAccountAdapter, self).save_user(request, sociallogin, form) 
     changes = 0 
     try: 
      profile = StudentProfile.objects.get(userId=user).first() 
     except StudentProfile.DoesNotExist: 
      profile = StudentProfile() 
      profile.userId = user 
      profile.save() 

     if not profile.user_dp: 
      url = sociallogin.account.get_avatar_url() 
      avatar = download_file_from_url(url) 
      if avatar: 
       profile.user_dp = avatar 
       changes = 1 


     if changes == 1: 
      profile.save() 

     return user 

    def pre_social_login(self, request, sociallogin): 
     """ 
     Invoked just after a user successfully authenticates via a 
     social provider, but before the login is actually processed 
     (and before the pre_social_login signal is emitted). 

     We're trying to solve different use cases: 
     - social account already exists, just go on 
     - social account has no email or email is unknown, just go on 
     - social account's email exists, link social account to existing user 
     """ 

     print (sociallogin.account.extra_data) 
     # Ignore existing social accounts, just do this stuff for new ones 
     if sociallogin.is_existing: 
      return 

     # some social logins don't have an email address, e.g. facebook accounts 
     # with mobile numbers only, but allauth takes care of this case so just 
     # ignore it 
     if 'email' not in sociallogin.account.extra_data: 
      if 'emailAddress' not in sociallogin.account.extra_data: 
       return 
      else: 
       # Note: __iexact is used to ignore cases 
       try: 
        email = sociallogin.account.extra_data['emailAddress'].lower() 
        user = User.objects.get(email=email) 

       # if it does not, let allauth take care of this new social account 
       except User.DoesNotExist: 
        sp = StudentProfile() 
        return 

       # if it does, connect this new social login to the existing user 
       sociallogin.connect(request, user) 


     # check if given email address already exists. 
     # Note: __iexact is used to ignore cases 
     else : 
      try: 
       email = sociallogin.account.extra_data['email'].lower() 

       user = User.objects.get(email=email) 

      # if it does not, let allauth take care of this new social account 
      except User.DoesNotExist: 
       sp = StudentProfile() 
       return 

      # if it does, connect this new social login to the existing user 
      sociallogin.connect(request, user) 

希望這會有所幫助。

0

您的問題不在於擴展用戶。我想你無法弄清楚如何在DataBase上管理它。

所以,我對這個解決方案是: -

- Profile pic (file) 
- Bio + personal info 

對於上述兩個創建
所需的Fileds(資料相片(文件),生物+個人信息等單獨CustomUser模型。)ForgienKey(用戶)

- List with add functionality, meaning the user can press a "+" and 
add new things to the list. The final, full length list is what I want to store. 

爲此,創建一個帶有必需字段的新Model UserSaveListModel。 在每個+添加按鈕上點擊保存這個用戶的新對象。

- Random file upload field. 

創建新模型UPLOADEDFILES模型。在每次上傳文件時都會爲此創建一個新的obj。

如果您認爲將來會分離模塊而不僅僅是功能,您還可以爲每個應用創建分離應用。

+0

你有沒有指向我可以遵循的類似代碼示例的鏈接?沒有一個初學者的指導是很困難的。 – jonnyd42