2015-12-30 5 views
2

У меня есть пользовательская схема пользователя в Django для работы с ролями или типами пользователей, создавая приложение с именем userprofile, которое будет или будет настраивать мою пользовательскую модель.Переопределить метод save()

В моем settings.py я имею следующую конфигурацию:

INSTALLED_APPS = [ 
     ... 
    'userprofile', 
] 
#Custom model Users 
AUTH_USER_MODEL = 'userprofile.User' 

настроить свой класс User (USERPROFILE/models.py), которые наследуют от класса AbstractUser для добавления некоторых полей в моей модель пользователя из-за мои требования требовали меня.

Я также создать эти другие модели для ролей/пользователей профиля (MedicalProfile, PatientProfile, PhysiotherapistProfile) со своими собственными полями или атрибутами

Кроме того MedicalProfile, PatientProfile, PhysiotherapistProfile имеют OneToOneField отношения с моей пользовательской модели/класс User так:

from __future__ import unicode_literals 
from django.conf import settings 
from django.contrib.auth.models import AbstractUser 
from django.db import models 
from django.dispatch import receiver 
from django.db.models.signals import post_save 

class User(AbstractUser): 
    is_medical = models.BooleanField(default=False) 
    is_physiotherapist = models.BooleanField(default=False) 
    is_patient = models.BooleanField(default=False) 
    slug = models.SlugField(max_length=100, blank=True) 
    photo = models.ImageField(upload_to='avatars', null = True, blank = True) 

    # Overriding the save method 
    def save(self, *args, **kwargs): 
    if self.is_medical: 
     profile = MedicalProfile(user=self) 
     super(User, self).save(self, *args, **kwargs) 
     profile.save() 


    # We get the profiles user according with their type 
    def get_medical_profile(self): 
     medical_profile = None 
     if hasattr(self, 'medicalprofile'): 
      medical_profile=self.medicalprofile 
     return medical_profile 

    def get_patient_profile(self): 
     patient_profile = None 
     if hasattr(self, 'patientprofile'): 
      patient_profile = self.patientprofile 
     return patient_profile 

    def get_physiotherapist_profile(self): 
     physiotherapist_profile = None 
     if hasattr(self, 'physiotherapistprofile'): 
      physiotherapist_profile = self.physiotherapistprofile 
     return physiotherapist_profile 

    class Meta: 

     db_table = 'auth_user' 

class MedicalProfile(models.Model): 
    user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) 
    #active = models.BooleanField(default=True) 
    name = models.CharField(max_length=64) 


class PatientProfile(models.Model): 
    user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) 
    #active = models.BooleanField(default=True) 
    name = models.CharField(max_length=64) 


class PhysiotherapistProfile(models.Model): 
    user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) 
    #active = models.BooleanField(default=True) 
    name = models.CharField(max_length=64) 

Мой вопрос

Я хочу сфокусировать свой вопрос относительно процесса переопределения save() метод:

def save(self, *args, **kwargs): 
    if self.is_medical: 
     profile = MedicalProfile(user=self) 
     super(User, self).save(self, *args, **kwargs) 
     profile.save() 

Я хочу, каждый, что пользователь будет создан, автоматически будет создан свой профиль (MedicalProfile, PatientProfile, PhysiotherapistProfile) в соответствии, если их поле проверяется (is_medical, is_patient, is_physiotherapist)

В неудобно, что у меня есть с моим процессом коррекции заключается в следующем:

  • Когда я создаю пользователя через Джанго администратора, я получаю эту ошибку

enter image description here

я не знаю об этом, в отношении причины, по которым настроен пользователь ПК на None ...

Какие альтернативы я могу иметь для решения этой ситуации, и когда я создаю пользователь, их экземпляр профиля сохраняется (MedicalProfile, PhysiotherapistProfile, PatientProfile) в зависимости от атрибута checkbo/field (is_medical, is_physiotherapist, is_patient), который я выбираю?

Я приношу все свои извинения раньше, в случае, если мой вопрос не подходит или не связан с философией stackoverflow или расширением моего вопроса.

Причина, по которой это extense является то, что я хочу дать все детали для получения ответа

Любая ориентация буду признательна и будут оценены

+2

Почему на земле вы публикуете все эти скриншоты кода? Почему вы это сделали? Код - * текст *, разместите его как таковой. –

+0

Ok @ DanielRoseman у вас есть причина. Я изменил образ классов моделей для их соответствующего кода, отредактировав свой вопрос. Что касается других изображений, связанных с процессом отладки ... могу ли я оставить их в качестве изображений, из-за которых я хочу ссылаться на мой процесс отладки. Все нормально? – bgarcial

+0

Я думаю, что самый простой и лучший способ - переопределить метод сохранения в моей модели User. Я попробую https://docs.djangoproject.com/en/1.9/topics/db/models/#overriding-model-methods – bgarcial

ответ

2

Вам нужно сделать что-то в вашем методе сохранения, если пользователь не является медицинским; вам все равно нужно сохранить объект.

Фиксированный реализация будет:

def save(self, *args, **kwargs): 
    user = super(User, self).save(self, *args, **kwargs) 
    if self.is_medical: 
     MedicalProfile(user=self).save() 
0

Мой class User расположен в userprofile/models.py является переопределение метода сохранения, остался так:

class User(AbstractUser): 
    is_medical = models.BooleanField(default=False) 
    is_physiotherapist = models.BooleanField(default=False) 
    is_patient = models.BooleanField(default=False) 
    slug = models.SlugField(max_length=100, blank=True) 
    photo = models.ImageField(upload_to='avatars', null = True, blank = True) 

    def save(self, *args, **kwargs): 
     user = super(User, self).save(*args, **kwargs) 

     # Creating and user with medical, patient and physiotherapist profiles 
     if self.is_medical and not MedicalProfile.objects.filter(user=self).exists()\ 
       and self.is_patient and not PatientProfile.objects.filter(user=self).exists()\ 
       and self.is_physiotherapist and not PhysiotherapistProfile.objects.filter(user=self).exists(): 

      medical_profile=MedicalProfile(user=self).save() 
      patient_profile=PatientProfile(user=self).save() 
      physiotherapist_profile=PhysiotherapistProfile(user=self).save() 
      #profile.save() 

     # Creating and user with medical and patient profiles 
     elif self.is_medical and not MedicalProfile.objects.filter(user=self).exists()\ 
      and self.is_patient and not PatientProfile.objects.filter(user=self).exists(): 

      medical_profile=MedicalProfile(user=self).save() 
      patient_profile=PatientProfile(user=self).save() 

     # Creating and user with medical and physiotherapist profiles 
     elif self.is_medical and not MedicalProfile.objects.filter(user=self).exists()\ 
      and self.is_physiotherapist and not PhysiotherapistProfile.objects.filter(user=self).exists(): 

      medical_profile=MedicalProfile(user=self).save() 
      physiotherapist_profile=PhysiotherapistProfile(user=self).save() 

     # Creating and user with physiotherapist and patient profiles 
     elif self.is_physiotherapist and not PhysiotherapistProfile.objects.filter(user=self).exists()\ 
      and self.is_patient and not PatientProfile.objects.filter(user=self).exists(): 

      physiotherapist_profile = PhysiotherapistProfile(user=self).save() 
      patient_profile = PatientProfile(user=self).save() 

     # Creating and user with medical profile 
     elif self.is_medical and not MedicalProfile.objects.filter(user=self).exists(): 
      profile = MedicalProfile(user=self) 
      profile.save() 

     # Creating and user with patient profile 
     elif self.is_patient and not PatientProfile.objects.filter(user=self).exists(): 
      profile = PatientProfile(user=self) 
      profile.save() 

     # Creating and user with physiotherapist profiles 
     elif self.is_physiotherapist and not PhysiotherapistProfile.objects.filter(user=self).exists(): 
      profile = PhysiotherapistProfile(user=self) 
      profile.save() 



    # We get the profiles user according with their type 
    def get_medical_profile(self): 
     medical_profile = None 
     if hasattr(self, 'medicalprofile'): 
      medical_profile=self.medicalprofile 
     return medical_profile 

    def get_patient_profile(self): 
     patient_profile = None 
     if hasattr(self, 'patientprofile'): 
      patient_profile = self.patientprofile 
     return patient_profile 

    def get_physiotherapist_profile(self): 
     physiotherapist_profile = None 
     if hasattr(self, 'physiotherapistprofile'): 
      physiotherapist_profile = self.physiotherapistprofile 
     return physiotherapist_profile 

    # We redefine the attributes (create db_table attribute) in class Meta to say to Django 
    # that users will save in the same table that the Django default user model 
    # https://github.com/django/django/blob/master/django/contrib/auth/models.py#L343 
    class Meta: 

     db_table = 'auth_user' 

class MedicalProfile(models.Model): 
    user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) 
    #active = models.BooleanField(default=True) 
    name = models.CharField(max_length=64) 


class PatientProfile(models.Model): 
    user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) 
    #active = models.BooleanField(default=True) 
    name = models.CharField(max_length=64) 


class PhysiotherapistProfile(models.Model): 
    user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) 
    #active = models.BooleanField(default=True) 
    name = models.CharField(max_length=64) 

# Enter the username as slug field 
@receiver(post_save, sender = settings.AUTH_USER_MODEL) 
def post_save_user(sender, instance, **kwargs): 
    slug = slugify(instance.username) 
    User.objects.filter(pk=instance.pk).update(slug=slug) 

сохранения() метод, позвольте мне сохранить пользователей со всеми возможные комбинации профилей.

Но есть ли лучший способ сделать это?

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