когда я регистрирую нового пользователя, я хочу сохранить в другую группу, каждый пользователь которой назначен определенной модели с использованием сигналов django post_save - PullRequest
0 голосов
/ 20 апреля 2020

У меня есть две модели, поданные в файл signal.py с двумя сигналами post_save, каждая из которых ссылается на две разные модели с общим отправителем. Пользователь, когда я создаю пользователя, например, доктора, я обнаружил, что пользователь сохраняется с обоими группы, эти группы - врач и пациент, я хочу ситуации, когда, если я создаю пользователя, пользователю, который связан с моделью (отношение «Один к одному»), назначается только одна группа из двух, т.е. пользователь, которому назначены пациент и врач, я также хочу, чтобы сведения о создании сохранялись в соответствующей модели, я получаю только имя пользователя user.user, сохраненное в конкретной модели. У меня также есть проблемы с обновлением страницы моего профиля пациента, но страница профиля доктора обновляется, пациент не, пожалуйста, что я делаю неправильно, был бы признателен за ваши входные данные, это мои сигналы.py

from django.db.models.signals import post_save
from .models import *
from django.contrib.auth.models import User
from django.contrib.auth.models import Group


def create_profile(sender, instance, created, **kwargs):
    if created:
        group = Group.objects.get(name='doctor')
        instance.groups.add(group)
        Doctor.objects.create(
            user=instance,
            name=instance.username,
            )
        print("Profile Created For Doctor")


post_save.connect(create_profile, sender=User)


def create_patient_profile(sender, instance, created, **kwargs)

    if created:
        group_patient = Group.objects.get(name='patient'):

        instance.groups.add(group_patient)

        Patient.objects.create(
            user_p=instance,
            name=instance.username,
            )
        print("Profile Created For Patient")


post_save.connect(create_patient_profile, sender=User)

Это мой файл models.py

from django.db import models
from multiselectfield import MultiSelectField
from django.contrib.auth.models import User

# Create your models here.


class Doctor(models.Model):
    GENDER_ChOICE = (
        ('Choose Your Option', 'Choose Your Option'),
        ('male', 'male'),
        ('female', 'female'),
    )
    user = models.OneToOneField(User, null=True, blank=True, on_delete=models.CASCADE)
    name = models.CharField(max_length=200, null=True)
    phone = models.CharField(max_length=200, null=True)
    email = models.EmailField(max_length=200, null=True)
    address = models.CharField(max_length=2045, null=True)
    gender = models.CharField(max_length=200, null=True, blank=False, default='choose', choices=GENDER_ChOICE)
    date = models.DateTimeField(auto_now_add=True, null=True)
    profile_pic = models.ImageField(null=True, default="avatar-1577909_960_720.png", blank=True)
    date_of_birth = models.DateField(max_length=200, null=True)

    def __str__(self):
        return self.name


class Patient(models.Model):
    GENDER_ChOICE = (
        ('Choose Your Option', 'Choose Your Option'),
        ('male', 'male'),
        ('female', 'female'),
    )
    SURGERY = (
        ('appendectomy', 'appendectomy'),
        ('cholecystectomy', 'cholecystectomy'),
        (' coronary artery bypass', 'coronary artery bypass'),
        ('hypertension', 'hypertension'),
        ('carotid endarterectomy', 'carotid endarterectomy')
    )
    ChOICE1 = (
        ('ebola', 'ebola'),
        ('malaria', 'malaria'),
        ('asthma', 'asthma'),
        ('hypertension', 'hypertension'),
    )

    REVIEW = (
        ('fever', 'fever'),
        ('cough', 'cough'),
        ('vomiting', 'vomiting'),
        ('difficulty breathing', 'difficulty breathing'),
        ('chestpain', 'chestpain'),
    )
    DRUGUSE = (
        ('none', 'none'),
        ('yes', 'yes'),
    )
    IMMUNIZE = (
        ('tetanus', 'tetanus'),
        ('pneumonia', 'pneumonia'),
        ('flu shot', 'flu shot'),
        ('Hep b', 'Hep b'),
    )
    ALCOHOL = (
        ('none', 'none'),
        ('occasionally', 'occasionally'),
        ('frequently', 'frequently'),
    )
    STATUS = (
        ('Choose Your Option', 'Choose Your Option'),
        ('pending', 'pending'),
        ('complete', 'complete'),
    )

    user_p = models.OneToOneField(User, null=True, on_delete=models.CASCADE)
    profile_pic = models.ImageField(null=True, default="avatar-1577909_960_720.png", blank=True)
    name = models.CharField(max_length=200, null=True)
    phone = models.CharField(max_length=200, null=True)
    email = models.EmailField(max_length=200, null=True)
    address = models.CharField(max_length=2045, null=True)
    gender = models.CharField(max_length=200, null=True, blank=False, default='choose', choices=GENDER_ChOICE)
    date = models.DateTimeField(auto_now_add=True, null=True)
    date_of_birth = models.DateTimeField(max_length=200, null=True)
    current_medical_condition = MultiSelectField(null=True, choices=ChOICE1)
    surgeries = MultiSelectField(null=True, choices=SURGERY
                                 , max_length=200)
    druguse = MultiSelectField(null=True, choices=DRUGUSE)
    system_review = MultiSelectField(null=True, choices=REVIEW, max_length=200)
    immunization = MultiSelectField(null=True, choices=IMMUNIZE, max_length=200)
    alcohol_use = MultiSelectField(null=True, choices=ALCOHOL, max_length=200)
    other_complaint = models.CharField(max_length=20045, null=True, blank=True)
    appointment_status = models.CharField(max_length=200, null=True, choices=STATUS)
    doctor = models.ForeignKey(Doctor, null=True, on_delete=models.SET_NULL)

    def __str__(self):
        return self.name

Это мой файл views.py

from django.shortcuts import render, redirect
from django.http import HttpResponse
from django.contrib import messages
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required

from .decorators import *
from .models import *
from .forms import *
from .filters import *
from django.contrib.auth.models import Group
# Create your views here.

@unauthenticated_user
def signup_doctor(request):

    form = CreateDoctorForm()

    if request.method == 'POST':
        form = CreateDoctorForm(request.POST)
        if form.is_valid():
            user = form.save()
            username = form.cleaned_data.get('username')

            messages.success(request, 'Account has been created for ' + username)
            return redirect('login')

    context = {'form': form}
    return render(request, 'accounts/signup_med.html', context)


@unauthenticated_user
def home(request):
    return render(request, 'accounts/index.html')

@unauthenticated_user
def about(request):
    return render(request, 'accounts/about.html')

@unauthenticated_user
def loginPage(request):

    if request.method == 'POST':
        username = request.POST.get('username')
        password = request.POST.get('password')

        user = authenticate(request, username=username, password=password)

        if user is not None:
            login(request, user)
            return redirect('doc_dashboard')
        else:
            messages.info(request, 'Username or Password is Incorrect')

    return render(request, 'accounts/login.html')


@unauthenticated_user_patient
def loginPagePatient(request):

    if request.method == 'POST':
        username = request.POST.get('username')
        password = request.POST.get('password')

        user = authenticate(request, username=username, password=password)

        if user is not None:
            login(request, user)
            return redirect('user_dashboard')
        else:
            messages.info(request, 'Username or Password is Incorrect')

    return render(request, 'accounts/login_patient.html')


def logoutUser(request):
    logout(request)
    return redirect('login')


def logoutUserPatient(request):
    logout(request)
    return redirect('login_patient')

@unauthenticated_user
@unauthenticated_user_patient
def casechart(request):
    patients = Patient.objects.all()
    context = {'patients': patients}
    return render(request, 'accounts/casechart.html', context)


@unauthenticated_user_patient
def bookappoint(request):
    form = CreatePatientForm()

    if request.method == 'POST':
        form = CreatePatientForm(request.POST)
        if form.is_valid():
            user = form.save()
            username = form.cleaned_data.get('username')

            messages.success(request, 'Account has been created for ' + username)
            return redirect('login_patient')

    context = {'form': form}
    return render(request, 'accounts/bookappointment.html', context)


@login_required(login_url='login')
@doctor_only
def doc_dashboard (request):

    patient_no = request.user.doctor.patient_set.all().count()
    print(request.user)

    context = {'patient_no': patient_no}

    return render(request, 'accounts/doc_dashboard.html', context)


def user_dashboard (request):

    return render(request, 'accounts/user_dashboard.html')

@login_required(login_url='login')
@allowed_users(allowed_roles=['doctor'])
def patient(request, pk):
    patient = Patient.objects.get(id=pk)
    context = {'patient': patient}

    return render(request, 'accounts/patient.html', context)

@login_required(login_url='login')
@allowed_users(allowed_roles=['doctor'])
def patient_list(request):
    patientlist = Patient.objects.all()
    myFilter = PatientFilter(request.GET, queryset=patientlist)
    patientlist = myFilter.qs

    context = {'patientlist': patientlist, 'myFilter': myFilter}

    return render(request, 'accounts/patient_list.html', context)

@login_required(login_url='login')
@allowed_users(allowed_roles=['doctor'])
def doctor(request):
    doctor = request.user.doctor
    form = DoctorForm(instance=doctor)

    if request.method == "POST":
        form = DoctorForm(request.POST, request.FILES, instance=doctor)
        if form.is_valid():
            form.save()

    context = {'form': form}

    return render(request, 'accounts/doctor.html', context)


@login_required(login_url='login_patient')
@allowed_users(allowed_roles=['patient'])
def profile(request):
    patient = request.user.patient
    form = PatientForm(instance=patient)

    if request.method == "POST":
        form = PatientForm(request.POST, request.FILES, instance=patient)
        if form.is_valid():
            form.save()

    context = {'form': form}

    return render(request, 'accounts/patient_profile.html', context)

Это мой файл decorators.py

from django.http import HttpResponse
from django.shortcuts import redirect


def unauthenticated_user(view_func):
    def wrapper_func(request, *args, **kwargs):
        if request.user.is_authenticated:
            return redirect('doc_dashboard')
        else:
            return view_func(request, *args, **kwargs)

    return wrapper_func


def unauthenticated_user_patient(view_func):
    def wrapper_func(request, *args, **kwargs):
        if request.user.is_authenticated:
            return redirect('user_dashboard')
        else:
            return view_func(request, *args, **kwargs)

    return wrapper_func


def allowed_users(allowed_roles=[]):
    def decorator(view_func):
        def wrapper_func(request, *args, **kwargs):

            group = None
            if request.user.groups.exists():
                group = request.user.groups.all()[0].name

            if group in allowed_roles:
                return view_func(request, *args, **kwargs)
            else:
                return HttpResponse('You Are Not Allowed To View This Page')
        return wrapper_func
    return decorator


def doctor_only(view_func):
    def wrapper_func(request, *args, **kwargs):
        group = None
        if request.user.groups.exists():
            group = request.user.groups.all()[0].name

        if group == 'patient':
            return redirect('user_dashboard')

        if group == 'doctor':
            return view_func(request, *args, **kwargs)

    return wrapper_func



def patient_only(view_func):
    def wrapper_func(request, *args, **kwargs):
        group = None
        if request.user.groups.exists():
            group = request.user.groups.all()[0].name

        if group == 'patient':
            return redirect('user_dashboard')

        if group == 'doctor':
            return view_func(request, *args, **kwargs)

    return wrapper_func

Это мои модели. py файл

from django.forms import ModelForm
from django.contrib.auth.forms import UserCreationForm
from django import forms
from .models import *
from django.contrib.auth.forms import User


class DoctorForm (ModelForm):
    class Meta:
        model = Doctor
        fields = '__all__'
        exclude = ['user']
        widgets = {
            'date_of_birth': forms.DateInput(attrs={'class': 'datepicker'}),
        }


class PatientForm (ModelForm):
    class Meta:
        model = Patient
        fields = '__all__'
        exclude = ['user']
        widgets = {
            'date_of_birth': forms.DateInput(attrs={'class': 'datepicker'}),
        }


class CreateDoctorForm(UserCreationForm):
    phone = forms.CharField(max_length=20, help_text='Enter Phone Number')

    class Meta:
        model = User
        fields = ['username', 'email', 'phone', 'password1', 'password2']


class CreatePatientForm(UserCreationForm):
    phone = forms.CharField(max_length=20, help_text='Enter Phone Number')
    address = forms.CharField(max_length=2025, help_text='Enter Address')

    class Meta:
        model = User
        fields = ['username', 'email', 'phone', 'password1', 'password2', 'address']

это шаблон для страницы обновления пациента

{% load static %}
{% load materializecss %}

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>E-Health</title>
        <!-- Compiled and minified CSS -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">
    <link rel="stylesheet" href="{% static '/css/main.css' %}">
    <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">

</head>
<body>

 {% include 'accounts/dash_nav_patient.html' %}
  <main>
      <div class="container">
          <div class="row">
              <div class="col s12">
                <div class="" style="margin:35px">



                        <div  class="row">
                            <h5>Profile Page </h5>
                        <form   method="POST" class="col s12" enctype="multipart/form-data">
                            {% csrf_token %}

                                          {{form.as_p}}
                            <input type="submit" name="Update" value="Update" class="waves-effect waves-light btn-large">
                        </form>
                      </div>




                </div>
            </div>

          </div>
      </div>

  <div class="fixed-action-btn">
  <a class="btn-floating btn-large red">
    <i class="large material-icons">mode_edit</i>
  </a>
  <ul>
    <li><a class="btn-floating red"><i class="material-icons">insert_chart</i></a></li>
    <li><a class="btn-floating yellow darken-1"><i class="material-icons">format_quote</i></a></li>
    <li><a class="btn-floating green"><i class="material-icons">publish</i></a></li>
    <li><a class="btn-floating blue"><i class="material-icons">attach_file</i></a></li>
  </ul>
</div>
  </main>

  <footer class="indigo page-footer">
    <div class="container">
      <div class="row">
        <div class="col s12">
          <h5 class="white-text">Icon Credits</h5>
          <ul id='credits'>
            <li>
              Gif Logo made using <a href="https://formtypemaker.appspot.com/" title="Form Type Maker">Form Type Maker</a> from <a href="https://github.com/romannurik/FORMTypeMaker" title="romannurik">romannurik</a>
            </li>
            <li>
              Icons made by <a href="https://material.io/icons/">Google</a>, available under <a href="https://www.apache.org/licenses/LICENSE-2.0" target="_blank">Apache License Version 2.0</a>
            </li>
          </ul>
        </div>
      </div>
    </div>
    <div class="footer-copyright">
      <div class="container">
         <span>Made By <a style='font-weight: bold;' href="https://github.com/piedcipher" target="_blank">Tirth Patel</a></span>
      </div>
    </div>
  </footer>



<!-- Compiled and minified JavaScript -->
    <script
  src="https://code.jquery.com/jquery-3.3.1.min.js"
  integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
  crossorigin="anonymous"></script>
    <script src="{% static '/js/main.js' %}" ></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0-rc.1/js/materialize.min.js" integrity="sha256-SrBfGi+Zp2LhAvy9M1bWOCXztRU9Ztztxmu5BcYPcPE=" crossorigin="anonymous"></script>
  <script>
      $(document).ready(function(){
        $('.sidenav').sidenav();
        $('.dropdown-trigger').dropdown();

        $('.button-collapse').sidenav();
        $('.fixed-action-btn').floatingActionButton();

        $('.collapsible').collapsible();



        //Initialize materialize data picker
        $('.datepicker').datepicker({'format': 'yyyy-mm-dd'});
        $('select').formSelect();
       });
  </script>

</body>
</html>

Это мой файл urls.py

from django.contrib import admin
from django.urls import path
from django.contrib.auth import views as auth_views
from . import views

urlpatterns = [
    path('', views.home, name='home'),
    path('about/', views.about, name='about'),
    path('login/', views.loginPage, name='login'),
    path('login_patient/', views.loginPagePatient, name='login_patient'),
    path('logout/', views.logoutUser, name='logout'),
    path('logout_patient/', views.logoutUserPatient, name='logout_patient'),
    path('casechart/', views.casechart, name='casechart'),
    path('bookappoint/', views.bookappoint, name='bookappoint'),
    path('doc_dashboard/', views.doc_dashboard, name='doc_dashboard'),
    path('user_dashboard/', views.user_dashboard, name='user_dashboard'),
    path('doctor/', views.doctor, name='doctor'),
    path('patient_profile/', views.profile, name='patient_profile'),
    path('patient/<str:pk>/', views.patient, name='patient'),
    path('patient_list/', views.patient_list, name='patient_list'),
    path('signup_med/', views.signup_doctor, name='signup_med'),
    path('reset_password/', auth_views.PasswordResetView.as_view(template_name="accounts/password_reset.html"), name="reset_password"),
    path('reset_password_sent/', auth_views.PasswordResetDoneView.as_view(template_name="accounts/password_reset_sent.html"),
         name="password_reset_done"),
    path('reset/<uidb64>/<token>',
         auth_views.PasswordResetConfirmView.as_view(template_name="accounts/password_reset_form.html"), name="password_reset_confirm"),
    path('reset_password_complete/',
         auth_views.PasswordResetCompleteView.as_view(template_name="accounts/password_reset_done.html"), name="password_reset_complete"),

]

Я новичок в Django так что простота в объяснении была бы очень признательна, спасибо

...