RelatedObjectDoesNotExist-模型之间的关系错误?

时间:2020-10-26 03:37:18

标签: python django django-models django-rest-framework

我目前正在创建一个名为“医院管理系统”的应用程序,病人可以在这里任命医生(通过我尚未实施的系统)。当前,我遇到有关“ RelatedObjectDoesNotExist”的错误。这是完整的错误:

Environment:


Request Method: POST
Request URL: http://127.0.0.1:8000/hms_app/doctor_register/

Django Version: 3.1.2
Python Version: 3.8.5
Installed Applications:
['django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'hms_app']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware']



Traceback (most recent call last):
  File "C:\Users\acer\anaconda3\envs\myDjangoEnv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
    response = get_response(request)
  File "C:\Users\acer\anaconda3\envs\myDjangoEnv\lib\site-packages\django\core\handlers\base.py", line 179, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\Users\acer\Desktop\My_Django_Stuff\hospital_management_system\hms_app\views.py", line 60, in doctor_register
    doctor.doctor_profile.doctor_first_name = doctor_profile_form.cleaned_data.get('doctor_first_name')
  File "C:\Users\acer\anaconda3\envs\myDjangoEnv\lib\site-packages\django\db\models\fields\related_descriptors.py", line 421, in __get__
    raise self.RelatedObjectDoesNotExist(

Exception Type: RelatedObjectDoesNotExist at /hms_app/doctor_register/
Exception Value: User has no doctor_profile.

每次我尝试注册医生时都会出现此错误,但是当我尝试注册患者时不会发生这种错误

我怀疑这个错误与我的模型以及每个模型之间的关系有关。现在,我正在尝试使用Django的用户模型实现多个角色-具体来说,角色是医生和病人。到目前为止,这是我编写的代码:

models.py

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

# Create your models here.

class User(AbstractUser):
    is_patient = models.BooleanField(default=True)

SEX = [
    ('M', 'Male'),
    ('F', 'Female'),
]

class PatientProfile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE, null=True, related_name='patient_profile')
    patient_first_name = models.CharField(max_length=50, blank=False)
    patient_last_name = models.CharField(max_length=50, blank=False)
    patient_email = models.EmailField(max_length=50, blank=False)
    patient_profile_pic = models.ImageField(upload_to='patient_profile_pics', blank=True)
    patient_sex = models.CharField(max_length=50, blank=False, choices=SEX)
    def __str__(self):
        return self.patient_last_name

DEPARTMENT_CHOICES = [
    ('allied_medical_specialties', 'DEPARTMENT OF ALLIED MEDICAL SPECIALTIES'),
    ('cardiology', 'DEPARTMENT OF CARDIOLOGY'),
    ('cardiovascular_surgery_anesthesia', 'DEPARTMENT OF CARDIOVASCULAR SURGERY and ANESTHESIA'),
    ('education_training_research', 'DEPARTMENT OF EDUCATION, TRAINING and RESEARCH'),
    ('pediatric_cardiology', 'DEPARTMENT OF PEDIATRIC CARDIOLOGY'),
    ('ambulatory_emergency_care', 'DEPARTMENT OF AMBULATORY and EMERGENCY CARE'),
]

SPECIALTY_CHOICES = [
    ('allergy_immunology', 'Allergy and Immunology'),
    ('anesthesiology', 'Anesthesiology'),
    ('cardiology_adult', 'Cardiology Adult'),
    ('cardiology_pediatric', 'Cardiology Pediatric'),
    ('dental_medicine', 'Dental Medicine'),
    ('dermatology', 'Dermatology'),
    ('diabetology', 'Diabetology'),
    ('endocrinology', 'Endocrinology'),
    ('gastroenterology', 'Gastroenterology'),
    ('hematology', 'Hematology'),
    ('infectious_diseases', 'Infectious Diseases'),
    ('legal_medicine', 'Legal Medicine'),
    ('nephrology', 'Nephrology'),
    ('neurology', 'Neurology'),
    ('neuroradiology', 'Neuroradiology'),
    ('nuclear_medicine', 'Nuclear Medicine'),
    ('obstetrics_gynecology', 'Obstetrics and Gynecology'),
    ('oncology_medical', 'Oncology Medical'),
    ('opthalmology', 'Opthalmology'),
    ('pathology', 'Pathology'),
    ('pediatric', 'Pediatric'),
    ('pediatrics_adolescent_medicine', 'Pediatricts and Adolescent Medicine'),
    ('psychiatric_neurology', 'Psychiatric Neurology'),
    ('psychiatry', 'Psychiatry'),
    ('radiology', 'Radiology'),
    ('rehabilitation_medicine', 'Rehabilitation Medicine'),
    ('rheumatology', 'Rheumatology'),
    ('sleep_medicine', 'Sleep Medicine'),
    ('surgery', 'Surgery'),
    ('surgical_intensive_care', 'Surgical Intensive Care'),
    ('training', 'Training'),
]

class DoctorProfile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE, null=True, related_name='doctor_profile')
    doctor_first_name = models.CharField(max_length=50, blank=False, default="")
    doctor_last_name = models.CharField(max_length=50, blank=False, default="")
    doctor_email = models.EmailField(max_length=50, blank=False, default="")
    doctor_profile_pic = models.ImageField(upload_to='doctor_profile_pics', blank=True)
    doctor_sex = models.CharField(max_length=50, blank=False, choices=SEX)
    department = models.CharField(max_length=50, blank=False, choices=DEPARTMENT_CHOICES)
    specialty = models.CharField(max_length=50, blank=False, choices=SPECIALTY_CHOICES)
    def __str__(self):
        return self.doctor_last_name

@receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
    print('****', created)
    if instance.is_patient:
        PatientProfile.objects.get_or_create(user=instance)
    else:
        DoctorProfile.objects.get_or_create(user=instance)

@receiver(post_save, sender=User)
def save_user_profile(sender, instance, **kwargs):
    print('_-----')
    if instance.is_patient:
        instance.patient_profile.save()
    else:
        DoctorProfile.objects.get_or_create(user=instance)

forms.py

from django import forms
from django.contrib.auth.models import User
from hms_app.models import User, PatientProfile, DoctorProfile

class UserForm(forms.ModelForm):
    password = forms.CharField(widget=forms.PasswordInput())
    class Meta:
        model = User
        fields = ('username', 'password')

class PatientProfileForm(forms.ModelForm):
    class Meta:
        model = PatientProfile
        fields = ('patient_first_name', 'patient_last_name', 'patient_email', 'patient_sex', 'patient_profile_pic')

class DoctorProfileForm(forms.ModelForm):
    class Meta:
        model = DoctorProfile
        fields = ('doctor_first_name', 'doctor_last_name', 'doctor_email', 'doctor_sex', 'department', 'specialty', 'doctor_profile_pic')

views.py

from django.http import request
from django.shortcuts import render
from hms_app.forms import UserForm, PatientProfileForm, DoctorProfileForm
from hms_app.models import User, PatientProfile, DoctorProfile
from django.contrib.auth import authenticate, login, logout as django_logout
from django.http import HttpResponseRedirect, HttpResponse
from django.urls import reverse
from django.contrib.auth.decorators import login_required
# Create your views here.
def index(request):
    return render(request, 'hms_app/index.html')

@login_required
def logout(request):
    django_logout(request)
    return HttpResponseRedirect(reverse('index'))

def patient_register(request):
    registered = False

    if request.method == "POST":
        user_form = UserForm(data=request.POST)
        patient_profile_form = PatientProfileForm(data=request.POST)

        if user_form.is_valid() and patient_profile_form.is_valid():
            patient = user_form.save()
            patient.set_password(patient.password)
            patient.save()

            patient.patient_profile.patient_first_name = patient_profile_form.cleaned_data.get('patient_first_name')
            patient.patient_profile.patient_last_name = patient_profile_form.cleaned_data.get('patient_last_name')
            patient.patient_profile.patient_email = patient_profile_form.cleaned_data.get('patient_email')    
            patient.patient_profile.patient_sex = patient_profile_form.cleaned_data.get('patient_sex')
            if 'patient_profile_pic' in request.FILES:
                patient.patient_profile.patient_profile_pic = request.FILES['patient_profile_pic']
            patient.patient_profile.save()
            registered = True

        else:
            print(user_form.errors, patient_profile_form.errors)
    else:
        user_form = UserForm()
        patient_profile_form = PatientProfileForm()
    return render(request, 'hms_app/patient_registration.html', {'user_form':user_form, 'patient_profile_form':patient_profile_form, 'registered':registered})

def doctor_register(request):
    registered = False

    if request.method == "POST":
        user_form = UserForm(data=request.POST)
        doctor_profile_form = DoctorProfileForm(data=request.POST)

        if user_form.is_valid() and doctor_profile_form.is_valid():
            doctor = user_form.save()
            doctor.set_password(doctor.password)
            doctor.save()

            doctor.doctor_profile.doctor_first_name = doctor_profile_form.cleaned_data.get('doctor_first_name')
            doctor.doctor_profile.doctor_last_name = doctor_profile_form.cleaned_data.get('doctor_last_name')
            doctor.doctor_profile.doctor_email = doctor_profile_form.cleaned_data.get('doctor_email')    
            doctor.doctor_profile.doctor_sex = doctor_profile_form.cleaned_data.get('doctor_sex')
            doctor.doctor_profile.department = doctor_profile_form.cleaned_data.get('department')
            doctor.doctor_profile.specialty = doctor_profile_form.cleaned_data.get('specialty')
            if 'doctor_profile_pic' in request.FILES:
                doctor.doctor_profile.doctor_profile_pic = request.FILES['doctor_profile_pic']
            doctor.doctor_profile.save()
            registered = True

        else:
            print(user_form.errors, doctor_profile_form.errors)
    else:
        user_form = UserForm()
        doctor_profile_form = DoctorProfileForm()
    return render(request, 'hms_app/doctor_registration.html', {'user_form':user_form, 'doctor_profile_form':doctor_profile_form, 'registered':registered})


def patient_login(request):

    if request.method == 'POST':
        patient_username = request.POST.get('patient_username')
        patient_password = request.POST.get('patient_password')
        patient = authenticate(username=patient_username, password=patient_password)

        if patient:
            if patient.is_active:
                login(request, patient)
                return HttpResponseRedirect(reverse('index'))

            else:
                return HttpResponse('Your account is not active.')
        else:
            print("Someone tried to login and failed.")
            print("Patient Username: {} and Patient Password {}".format(patient_username, patient_password))
            return HttpResponse("Invalid login details. Please try again.")
    else:
        return render(request, 'hms_app/patient_login.html', {})

def doctor_login(request):

    if request.method == 'POST':
        doctor_username = request.POST.get('doctor_username')
        doctor_password = request.POST.get('doctor_password')
        doctor = authenticate(username=doctor_username, password=doctor_password)

        if doctor:
            if doctor.is_active:
                login(request, doctor)
                return HttpResponseRedirect(reverse('index'))

            else:
                return HttpResponse('Your account is not active.')
        else:
            print("Someone tried to login and failed.")
            print("Doctor Username: {} and Doctor Password {}".format(doctor_username, doctor_password))
            return HttpResponse("Invalid login details. Please try again.")
    else:
        return render(request, 'hms_app/doctor_login.html', {})

这是 settings.py ,以防万一

"""
Django settings for hospital_management_system project.

Generated by 'django-admin startproject' using Django 3.1.2.

For more information on this file, see
https://docs.djangoproject.com/en/3.1/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.1/ref/settings/
"""

from pathlib import Path

# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
TEMPLATE_DIR = (Path(BASE_DIR, 'templates'))
STATIC_DIR = (Path(BASE_DIR, 'static'))
MEDIA_DIR = (Path(BASE_DIR, 'media'))


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/

ALLOWED_HOSTS = []


# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'hms_app',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'hospital_management_system.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [TEMPLATE_DIR,],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'hospital_management_system.wsgi.application'


# Database
# https://docs.djangoproject.com/en/3.1/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'OPTIONS': {
            'sql_mode': 'traditional',
            'init_command': "SET sql_mode = 'STRICT_TRANS_TABLES'",
        },
        'NAME': 'hms_sample',
        'HOST': '127.0.0.1',
        'PORT': '3306',
        'USER': 'root',
        'PASSWORD': '',
    }
}


# Password validation
# https://docs.djangoproject.com/en/3.1/ref/settings/#auth-password-validators

PASSWORD_HASHERS = [
    'django.contrib.auth.hashers.PBKDF2PasswordHasher',
    'django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher',
    'django.contrib.auth.hashers.Argon2PasswordHasher',
    'django.contrib.auth.hashers.BCryptSHA256PasswordHasher',
]

AUTH_USER_MODEL = "hms_app.User"

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
        'OPTIONS': {'min_length':8}
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]


# Internationalization
# https://docs.djangoproject.com/en/3.1/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.1/howto/static-files/

STATIC_URL = '/static/'
STATICFILES_DIRS = [STATIC_DIR,]

MEDIA_ROOT = MEDIA_DIR
MEDIA_URL = '/media/'

LOGIN_URL = 'hms_app/patient_login'

我一直到处都在寻找解决方案,但是我似乎找不到一个。预先感谢!

0 个答案:

没有答案
相关问题