پروژه ای دارم به شرح زیر فایل view from django.shortcuts import render from django.http…
- User
پروژه ای دارم به شرح زیر فایل view
from django.shortcuts import render from django.http import JsonResponse from rest_framework import viewsets from .models import PatientsAppointment, DoctorsInfo from .serializers import PatientsAppointmentSerializer
class PatientsAppointmentViewSet(viewsets.ModelViewSet): queryset = PatientsAppointment.objects.all() serializer_class = PatientsAppointmentSerializer
def get_doctor_info(request, doctor_id): try: doctor = DoctorsInfo.objects.get(pk=doctor_id) return JsonResponse({ 'first_name': doctor.user.first_name, 'last_name': doctor.user.last_name }) except DoctorsInfo.DoesNotExist: return JsonResponse({'error': 'Doctor not found'}, status=404)
فایل urls
from django.urls import path, include from rest_framework.routers import DefaultRouter from .views import PatientsAppointmentViewSet, get_doctor_info
router = DefaultRouter() router.register(r'appointments', PatientsAppointmentViewSet)
app_name = 'app_healthFile' urlpatterns = [ path('', include(router.urls)), path('get-doctor-info/int:doctor_id/', get_doctor_info, name='get_doctor_info'), ]
فایل سریالایزر ها
from rest_framework import serializers from .models import PatientsAppointment, PrescribedMedicationDetail
class PrescribedMedicationDetailSerializer(serializers.ModelSerializer): class Meta: model = PrescribedMedicationDetail fields = ['id', 'medication', 'dosage', 'duration', 'additional_instructions']
class PatientsAppointmentSerializer(serializers.ModelSerializer): medication_details = PrescribedMedicationDetailSerializer(many=True)
class Meta: model = PatientsAppointment fields = ['id', 'sick', 'doctor', 'doctor_name', 'appointment_date', 'symptoms', 'doctors_diagnosis', 'medical_tests', 'medical_imaging', 'medication_details'] def create(self, validated_data): medication_details_data = validated_data.pop('medication_details') appointment = PatientsAppointment.objects.create(**validated_data) for medication_detail_data in medication_details_data: PrescribedMedicationDetail.objects.create(appointment=appointment, **medication_detail_data) return appointment def update(self, instance, validated_data): medication_details_data = validated_data.pop('medication_details') instance.sick = validated_data.get('sick', instance.sick) instance.doctor = validated_data.get('doctor', instance.doctor) instance.doctor_name = validated_data.get('doctor_name', instance.doctor_name) instance.symptoms.set(validated_data.get('symptoms', instance.symptoms.all())) instance.doctors_diagnosis.set(validated_data.get('doctors_diagnosis', instance.doctors_diagnosis.all())) instance.medical_tests.set(validated_data.get('medical_tests', instance.medical_tests.all())) instance.medical_imaging.set(validated_data.get('medical_imaging', instance.medical_imaging.all())) instance.save() # Updating medication details instance.medication_details.all().delete() # remove existing details for medication_detail_data in medication_details_data: PrescribedMedicationDetail.objects.create(appointment=instance, **medication_detail_data) return instanceفایل مدل ها
from django.contrib import admin from django.conf import settings from django.db import models from app_patients.models import PatientsInfo, DiseaseInfo, PatientSymptoms from app_doctors.models import DoctorsInfo, Specialty from app_pharmacy.models import MedicinesInfo from app_laboratory.models import MedicalTestTypes from app_medicalImaging.models import PhotographyTypes
class PrescribedMedicationDetail(models.Model): appointment = models.ForeignKey( 'PatientsAppointment', on_delete=models.CASCADE, related_name='medication_details', verbose_name="مراجعه" ) medication = models.ForeignKey( MedicinesInfo, on_delete=models.CASCADE, verbose_name="دارو" ) dosage = models.CharField( max_length=255, verbose_name="دوز مصرف" ) duration = models.CharField( max_length=255, verbose_name="دوره مصرف" ) additional_instructions = models.TextField( blank=True, null=True, verbose_name="توضیحات تکمیلی" )
class Meta: db_table = 'tbl_prescribed_medication_detail' verbose_name_plural = 'جزئیات داروهای تجویز شده'class PrescribedMedicationDetail(models.Model): appointment = models.ForeignKey( 'PatientsAppointment', on_delete=models.CASCADE, related_name='medication_details', verbose_name="مراجعه" ) medication = models.ForeignKey( MedicinesInfo, on_delete=models.CASCADE, verbose_name="دارو" ) dosage = models.CharField( max_length=255, verbose_name="دوز مصرف" ) duration = models.CharField( max_length=255, verbose_name="دوره مصرف" ) additional_instructions = models.TextField( blank=True, null=True, verbose_name="توضیحات تکمیلی" )
class Meta: db_table = 'tbl_prescribed_medication_detail' verbose_name_plural = 'جزئیات داروهای تجویز شده'class PatientsAppointment(models.Model): patient = models.CharField( max_length=255, blank=True, null=True, verbose_name="بیمار" ) doctor = models.CharField( max_length=255, blank=True, null=True, verbose_name="پزشک معالج" ) appointment_date = models.DateTimeField( auto_now_add=True, verbose_name="تاریخ مراجعه" ) symptoms = models.CharField( max_length=255, blank=True, null=True, verbose_name="علائم بیمار" ) doctors_diagnosis = models.CharField( max_length=255, blank=True, null=True, verbose_name="تشخیص پزشک" ) medical_tests = models.CharField( max_length=255, blank=True, null=True, verbose_name="آزمایشات تجویز شده" ) medical_imaging = models.CharField( max_length=255, blank=True, null=True, verbose_name="تصویربرداری های تجویز شده" )
doctor_description = models.TextField( blank=True, null=True, verbose_name='توضیحات' ) class Meta: db_table = 'tbl_patient_appointment' verbose_name_plural = 'مراجعات بیمار'فایل فرم ها
from django import forms from django_select2.forms import Select2MultipleWidget from .models import PatientsAppointment from app_patients.models import PatientsInfo, PatientSymptoms, DiseaseInfo from app_laboratory.models import MedicalTestTypes from app_doctors.models import DoctorsInfo, Specialty from app_medicalImaging.models import PhotographyTypes
class PatientsAppointmentForm(forms.ModelForm): patient = forms.CharField( label='بیمار', widget=forms.TextInput(attrs={'list': 'patients-list'}), )
doctor = forms.CharField( label='پزشک معالج', widget=forms.TextInput(attrs={'list': 'doctors-list'}), ) symptoms_existing = forms.MultipleChoiceField( label='انتخاب علائم', choices=[(symptom.name, symptom.name) for symptom in PatientSymptoms.objects.all()], required=False, widget=Select2MultipleWidget ) symptoms = forms.CharField( label='علائم', required=False, widget=forms.TextInput(attrs={'placeholder': 'وارد کردن علائم جدید'}), ) doctors_diagnosis_existing = forms.MultipleChoiceField( label='انتخاب تشخیصها', choices=[(diagnosis.name, diagnosis.name) for diagnosis in DiseaseInfo.objects.all()], required=False, widget=Select2MultipleWidget ) doctors_diagnosis = forms.CharField( label='تشخیصها', required=False, widget=forms.TextInput(attrs={'placeholder': 'وارد کردن تشخیصهای جدید'}), ) medical_tests_existing = forms.MultipleChoiceField( label='انتخاب آزمایشات', choices=[(test.name, test.name) for test in MedicalTestTypes.objects.all()], required=False, widget=Select2MultipleWidget ) medical_tests = forms.CharField( label='آزمایشات', required=False, widget=forms.TextInput(attrs={'placeholder': 'وارد کردن آزمایشات جدید'}), ) medical_imaging_existing = forms.MultipleChoiceField( label='انتخاب تصویربرداریها', choices=[(imaging.name, imaging.name) for imaging in PhotographyTypes.objects.all()], required=False, widget=Select2MultipleWidget ) medical_imaging = forms.CharField( label='تصویربرداریها', required=False, widget=forms.TextInput(attrs={'placeholder': 'وارد کردن تصویربرداریهای جدید'}), ) class Meta: model = PatientsAppointment fields = '__all__' class Media: css = { 'all': ('app_doctors/css/custom_select2.css',) } def clean_fields(self): cleaned_data = super().clean() # Add your custom cleaning logic if needed return cleaned_dataو فایل ادمین
import jdatetime from django.contrib import admin from .forms import PatientsAppointmentForm from .models import PatientsAppointment, PrescribedMedicationDetail from app_patients.models import PatientsInfo from app_doctors.models import DoctorsInfo
class PrescribedMedicationDetailInline(admin.TabularInline): model = PrescribedMedicationDetail extra = 1
@admin.register(PatientsAppointment) class PatientsAppointmentAdmin(admin.ModelAdmin): form = PatientsAppointmentForm change_form_template = 'admin/app_healthFile/PatientsAppointment/change_form.html'
list_display = ('get_patient_info', 'get_doctor_info', 'get_jalali_appointment_date') readonly_fields = ('appointment_date',) inlines = [PrescribedMedicationDetailInline] fields = ( 'patient', 'doctor', 'appointment_date', 'symptoms_existing', 'symptoms', 'doctors_diagnosis_existing', 'doctors_diagnosis', 'medical_tests_existing', 'medical_tests', 'medical_imaging_existing', 'medical_imaging', ) def get_patient_info(self, obj): try: username = obj.patient.split('(')[-1].strip(')') patient_info = PatientsInfo.objects.get(sick__username=username) full_name = f"{patient_info.sick.first_name} {patient_info.sick.last_name}" return f"{full_name} (کد ملی: {patient_info.sick.username})" except PatientsInfo.DoesNotExist: return "اطلاعات بیمار یافت نشد" get_patient_info.short_description = 'بیمار - نام و کد ملی' def get_doctor_info(self, obj): try: medical_id = obj.doctor.split('(')[-1].strip(')') doctor_info = DoctorsInfo.objects.get(medical_id=medical_id) full_name = f"{doctor_info.user.first_name} {doctor_info.user.last_name}" return f"{full_name} (شماره نظام پزشکی: {doctor_info.medical_id})" except DoctorsInfo.DoesNotExist: return "پزشک: اطلاعات یافت نشد یا کد اشتباه است" get_doctor_info.short_description = 'پزشک - نام و شماره نظام پزشکی' def get_jalali_appointment_date(self, obj): # استفاده از jdatetime برای تبدیل تاریخ به شمسی jalali_date = jdatetime.datetime.fromgregorian(datetime=obj.appointment_date) return jalali_date.strftime('%Y/%m/%d') get_jalali_appointment_date.short_description = 'تاریخ مراجعه' def get_extra_context(self, request): return { 'patients_list': [ f"{patient.sick.first_name} {patient.sick.last_name} ({patient.sick.username})" for patient in PatientsInfo.objects.all() ], 'doctors_list': [ f"{doctor.user.first_name} {doctor.user.last_name} ({doctor.medical_id})" for doctor in DoctorsInfo.objects.all() ], } def add_view(self, request, form_url='', extra_context=None): extra_context = extra_context or {} extra_context.update(self.get_extra_context(request)) return super().add_view(request, form_url, extra_context=extra_context) def change_view(self, request, object_id, form_url='', extra_context=None): extra_context = extra_context or {} extra_context.update(self.get_extra_context(request)) return super().change_view(request, object_id, form_url, extra_context=extra_context) - Assistant
Your Django project involves setting up a healthcare application to manage patient appointments, with various components such as views, serializers, models, forms, and admin configuration. Here’s a breakdown of how each component works based on your code:
Views
-
PatientsAppointmentViewSet:
- This is a standard Django REST Framework viewset for handling CRUD operations on
PatientsAppointmentobjects. - It uses
PatientsAppointmentSerializerto serialize data.
- This is a standard Django REST Framework viewset for handling CRUD operations on
-
get_doctor_info:
- This function-based view retrieves doctor information based on a given
doctor_id. - If the doctor is found, it returns the first and last name in a JSON response; otherwise, it returns a 404 error.
- This function-based view retrieves doctor information based on a given
URLs
- The
urls.pyfile registers thePatientsAppointmentViewSetwith a REST API router and maps theget_doctor_infoview to a URL pattern for retrieving doctor information by ID.
Serializers
-
PatientsAppointmentSerializer:
- Serializes and deserializes
PatientsAppointmentobjects, including relatedPrescribedMedicationDetaildata. - It overrides the
createandupdatemethods to handle nested medication details correctly.
- Serializes and deserializes
-
PrescribedMedicationDetailSerializer:
- Handles serialization for
PrescribedMedicationDetailfields.
- Handles serialization for
Models
-
PrescribedMedicationDetail:
- Represents details about medication prescribed to a patient during an appointment.
- Linked to
PatientsAppointmentvia a ForeignKey.
-
PatientsAppointment:
- Captures appointment information like patient, doctor, date, symptoms, diagnosis, tests, and imaging related to a patient's visit.
Forms
- PatientsAppointmentForm:
- Manages the form representation of
PatientsAppointmentin the Django admin with the ability to select or enter symptoms, diagnoses, tests, and imaging.
- Manages the form representation of
Admin
- Customizes the Django admin interface for
PatientsAppointment. - Uses
PatientsAppointmentFormwith inlines forPrescribedMedicationDetail. - Includes functionality to display human-readable representations of patient and doctor information.
- Converts Gregorian dates to Jalali using the
jdatetimelibrary for display in admin.
Overall Improvements
While your project setup looks comprehensive, here are a few suggestions for improving or ensuring best practices:
-
Duplicate Model Definitions:
- You have defined
PrescribedMedicationDetailtwice in the models file; you should remove the duplicate definition.
- You have defined
-
Optimization:
- Consider using select_related or prefetch_related in queryset configurations to optimize database queries, especially when dealing with related models like
PatientsInfoandDoctorsInfo.
- Consider using select_related or prefetch_related in queryset configurations to optimize database queries, especially when dealing with related models like
-
Validation and Error Handling:
- Implement more robust validation and error handling mechanisms to manage edge cases and incorrect data inputs, particularly in forms and serializers.
-
Code Organization:
- Ensure that your code is well-organized across modules/files, and follow Python's PEP 8 style guide for clean code formatting.
-
Testing:
- Always try to write unit tests for views, serializers, and forms to ensure expected behavior and catch any regressions early during changes.
This should give you a comprehensive understanding of the setup and a pathway to enhance your project's functionality and performance.
-
- User
اول بهم بگو کد های داخل فایل فرم دقیقا چیکار میکنن
- Assistant
Sure, let's break down the code in your form file to understand its functionality:
Overview
The
PatientsAppointmentFormis a DjangoModelFormclass that provides a way to create or update instances of thePatientsAppointmentmodel through a form interface. Here's a detailed explanation of each part:Form Fields
-
Patient Field:
patient = forms.CharField( label='بیمار', widget=forms.TextInput(attrs={'list': 'patients-list'}), )- Allows users to input the patient’s name.
- Uses a text input widget with a datalist attribute, which suggests patient names as the user types.
-
Doctor Field:
doctor = forms.CharField( label='پزشک معالج', widget=forms.TextInput(attrs={'list': 'doctors-list'}), )- Similar to the patient field, this lets users input the doctor’s name.
- Also uses a datalist for auto-suggest functionality.
-
Symptoms Existing Field:
symptoms_existing = forms.MultipleChoiceField( label='انتخاب علائم', choices=[(symptom.name, symptom.name) for symptom in PatientSymptoms.objects.all()], required=False, widget=Select2MultipleWidget )- A multiple-choice field for selecting existing patient symptoms using data from
PatientSymptomsmodel. - Uses a
Select2MultipleWidgetfor enhanced UI/UX.
- A multiple-choice field for selecting existing patient symptoms using data from
-
Symptoms (New) Field:
symptoms = forms.CharField( label='علائم', required=False, widget=forms.TextInput(attrs={'placeholder': 'وارد کردن علائم جدید'}), )- Allows users to enter new symptoms that may not be in the existing list.
-
Doctors Diagnosis Existing Field:
doctors_diagnosis_existing = forms.MultipleChoiceField( label='انتخاب تشخیصها', choices=[(diagnosis.name, diagnosis.name) for diagnosis in DiseaseInfo.objects.all()], required=False, widget=Select2MultipleWidget )- Similar to symptoms, this field is for selecting existing diagnoses.
- Uses data from the
DiseaseInfomodel.
-
Doctors Diagnosis (New) Field:
doctors_diagnosis = forms.CharField( label='تشخیصها', required=False, widget=forms.TextInput(attrs={'placeholder': 'وارد کردن تشخیصهای جدید'}), )- Input for new diagnoses not present in the existing list.
-
Medical Tests Existing Field:
medical_tests_existing = forms.MultipleChoiceField( label='انتخاب آزمایشات', choices=[(test.name, test.name) for test in MedicalTestTypes.objects.all()], required=False, widget=Select2MultipleWidget )- Multiple-choice field for selecting existing medical tests using
MedicalTestTypesmodel data.
- Multiple-choice field for selecting existing medical tests using
-
Medical Tests (New) Field:
medical_tests = forms.CharField( label='آزمایشات', required=False, widget=forms.TextInput(attrs={'placeholder': 'وارد کردن آزمایشات جدید'}), )- For entering new medical tests not in the existing data.
-
Medical Imaging Existing Field:
medical_imaging_existing = forms.MultipleChoiceField( label='انتخاب تصویربرداریها', choices=[(imaging.name, imaging.name) for imaging in PhotographyTypes.objects.all()], required=False, widget=Select2MultipleWidget )- Allows selecting existing medical imaging types using
PhotographyTypesmodel.
- Allows selecting existing medical imaging types using
-
Medical Imaging (New) Field:
medical_imaging = forms.CharField( label='تصویربرداریها', required=False, widget=forms.TextInput(attrs={'placeholder': 'وارد کردن تصویربرداریهای جدید'}), )- Enables input of new imaging procedures not available in the existing list.
Meta Class
class Meta: model = PatientsAppointment fields = '__all__'- Associates the form with the
PatientsAppointmentmodel. - Includes all model fields in the form.
Media Class
class Media: css = { 'all': ('app_doctors/css/custom_select2.css',) }- Custom CSS file
custom_select2.cssis included, probably to style the Select2 widget.
Clean Method
def clean_fields(self): cleaned_data = super().clean() # Add your custom cleaning logic if needed return cleaned_data- Overrides the
cleanmethod to allow custom validation or cleaning of fields. - Currently, it calls the parent class’s
cleanmethod and returns cleaned data without modification.
Conclusion
The form is designed to handle appointments by letting users select or input details regarding the patient, doctor, symptoms, diagnoses, tests, and imaging. It leverages existing model data for selection fields and offers a flexible UI with the help of the
Select2widget and datalist attributes. -
- User
به فارسی بهم توضیح بده
- Assistant
البته! در این قسمت به توضیح کد فایل فرم پروژهی شما به زبان فارسی میپردازیم:
نمای کلی
PatientsAppointmentFormیک کلاسModelFormدر جنگو است که به شما اجازه میدهد تا نمونههایی از مدلPatientsAppointmentرا از طریق یک فرم ایجاد یا بروزرسانی کنید. در ادامه، هر بخش از فرم توضیح داده میشود:فیلدهای فرم
-
فیلد بیمار:
patient = forms.CharField( label='بیمار', widget=forms.TextInput(attrs={'list': 'patients-list'}), )- این فیلد به کاربران اجازه میدهد نام بیمار را وارد کنند.
- از یک ویجت ورودی متنی با یک ویژگی datalist استفاده میکند که نام بیماران را به صورت پیشنهادی ارائه میدهد.
-
فیلد پزشک:
doctor = forms.CharField( label='پزشک معالج', widget=forms.TextInput(attrs={'list': 'doctors-list'}), ) - این فیلد مشابه فیلد بیمار است و به کاربران اجازه میدهد نام پزشک را وارد کنند. - از datalist برای ارائه پیشنهادات خودکار استفاده میکند. -
فیلد علائم موجود:
symptoms_existing = forms.MultipleChoiceField( label='انتخاب علائم', choices=[(symptom.name, symptom.name) for symptom in PatientSymptoms.objects.all()], required=False, widget=Select2MultipleWidget )- این فیلد انتخاب چندگانه برای انتخاب علائم بیمار موجود از طریق دادههای مدل
PatientSymptomsاست. - از ویجت
Select2MultipleWidgetبرای بهبود رابط کاربری استفاده میکند.
- این فیلد انتخاب چندگانه برای انتخاب علائم بیمار موجود از طریق دادههای مدل
-
فیلد علائم جدید:
symptoms = forms.CharField( label='علائم', required=False, widget=forms.TextInput(attrs={'placeholder': 'وارد کردن علائم جدید'}), )- به کاربران اجازه میدهد علائم جدیدی که ممکن است در لیست موجود نباشند را وارد کنند.
-
فیلد تشخیصهای پزشک موجود:
doctors_diagnosis_existing = forms.MultipleChoiceField( label='انتخاب تشخیصها', choices=[(diagnosis.name, diagnosis.name) for diagnosis in DiseaseInfo.objects.all()], required=False, widget=Select2MultipleWidget )- این فیلد مشابه فیلد علائم است و برای انتخاب تشخیصهای موجود استفاده میشود.
- از دادههای مدل
DiseaseInfoاستفاده میکند.
-
فیلد تشخیصهای پزشک جدید:
doctors_diagnosis = forms.CharField( label='تشخیصها', required=False, widget=forms.TextInput(attrs={'placeholder': 'وارد کردن تشخیصهای جدید'}), )- برای وارد کردن تشخیصهای جدید که در لیست موجود نیستند.
-
فیلد آزمایشات پزشکی موجود:
medical_tests_existing = forms.MultipleChoiceField( label='انتخاب آزمایشات', choices=[(test.name, test.name) for test in MedicalTestTypes.objects.all()], required=False, widget=Select2MultipleWidget )- فیلد انتخاب چندگانه برای انتخاب آزمایشات پزشکی موجود با استفاده از دادههای مدل
MedicalTestTypes.
- فیلد انتخاب چندگانه برای انتخاب آزمایشات پزشکی موجود با استفاده از دادههای مدل
-
فیلد آزمایشات پزشکی جدید:
medical_tests = forms.CharField( label='آزمایشات', required=False, widget=forms.TextInput(attrs={'placeholder': 'وارد کردن آزمایشات جدید'}), )- برای وارد کردن آزمایشات پزشکی جدید که در لیست موجود نیستند.
-
فیلد تصویربرداری پزشکی موجود:
medical_imaging_existing = forms.MultipleChoiceField( label='انتخاب تصویربرداریها', choices=[(imaging.name, imaging.name) for imaging in PhotographyTypes.objects.all()], required=False, widget=Select2MultipleWidget )- برای انتخاب انواع تصویربرداریهای پزشکی موجود با استفاده از مدل
PhotographyTypes.
- برای انتخاب انواع تصویربرداریهای پزشکی موجود با استفاده از مدل
-
فیلد تصویربرداری پزشکی جدید:
medical_imaging = forms.CharField( label='تصویربرداریها', required=False, widget=forms.TextInput(attrs={'placeholder': 'وارد کردن تصویربرداریهای جدید'}), )- اجازه میدهد که روشهای تصویربرداری جدیدی که در لیست موجود نیستند وارد شوند.
کلاس Meta
class Meta: model = PatientsAppointment fields = '__all__'- این فرم را با مدل
PatientsAppointmentاتصال میدهد. - شامل تمام فیلدهای مدل در فرم است.
کلاس Media
class Media: css = { 'all': ('app_doctors/css/custom_select2.css',) }- یک فایل CSS سفارشی
custom_select2.cssگنجانده شده، احتمالا برای استایل ویجت Select2.
متد Clean
def clean_fields(self): cleaned_data = super().clean() # Add your custom cleaning logic if needed return cleaned_data- متد
cleanرا بازنویسی میکند تا امکان اعتبارسنجی یا پاکسازی سفارشی فیلدها فراهم شود. - در حال حاضر، متد
cleanکلاس پدر را صدا زده و دادههای پاکشده را بدون تغییر برمیگرداند.
نتیجهگیری
این فرم برای مدیریت نوبتهای بیمار طراحی شده است و به کاربران اجازه میدهد جزئیات مربوط به بیمار، پزشک، علائم، تشخیصها، آزمایشات و تصویربرداری را انتخاب یا وارد کنند. این فرم از دادههای مدل موجود برای فیلدهای انتخابی و از رابط کاربری پیشرفته ویجت Select2 و ویژگی datalist استفاده میکند.
-
- User
من از فرم ها چطور میتونم توی رست api استفاده کنم ؟
- Assistant
استفاده از فرمهای Django در REST API معمولاً توصیه نمیشود زیرا Django REST Framework (DRF) به طور خاص برای مدیریت و پردازش APIها از سریالایزرها استفاده میکند. سریالایزرها در DRF نقش فرمها را در APIها بازی میکنند و برای تبدیل دادهها بین JSON و مدلهای Django به کار میروند.
با این حال، اگر دلایلی دارید که میخواهید از فرمهای Django در کنار API خود استفاده کنید (مثلاً برای منطق اعتبارسنجی که قبلاً پیادهسازی کردهاید)، میتوانید از رویکرد زیر استفاده کنید:
روش پیشنهادی: استفاده از سریالایزرها
به صورت پیشفرض بهتر است از سریالایزرهای Django REST Framework استفاده کنید که به خوبی با JSON کار میکنند و برای ارتباط با مدلهای Django طراحی شدهاند.
مثال:
from rest_framework import serializers from .models import PatientsAppointment class PatientsAppointmentSerializer(serializers.ModelSerializer): class Meta: model = PatientsAppointment fields = '__all__'استفاده از فرم در REST API
اگر به هر دلیلی میخواهید از فرمهای Django با REST API استفاده کنید، میتوانید یک ویو API سفارشی بنویسید که فرم را مدیریت کند. این کار مستلزم این است که درخواستهایی که به ویو ارسال میشوند را پردازش کنید و به صورت دستی داده را به فرم ارسال کنید.
مثال:
- ایجاد ویو API سفارشی:
from django.http import JsonResponse from django.views.decorators.csrf import csrf_exempt from .forms import PatientsAppointmentForm @csrf_exempt def create_appointment(request): if request.method == 'POST': form = PatientsAppointmentForm(request.POST) if form.is_valid(): appointment = form.save() return JsonResponse({'message': 'Appointment created successfully'}, status=201) else: return JsonResponse({'errors': form.errors}, status=400) return JsonResponse({'error': 'Invalid request'}, status=405)- تنظیم URL برای ویو:
from django.urls import path from .views import create_appointment urlpatterns = [ path('api/create-appointment/', create_appointment, name='create_appointment'), ]در این مثال، ویو
create_appointmentیک درخواست POST را میپذیرد، دادهها را به فرم ارسال میکند و دادهها را اعتبارسنجی میکند. اگر فرم معتبر باشد، یک نوبت جدید ایجاد میکند و در غیر این صورت، خطاهای فرم را بازمیگرداند.مشکلات این رویکرد
-
غیر استاندارد بودن: روش استفاده از فرم با REST API برخلاف یکپارچگی و استاندارد بودن معماری API عمل میکند.
-
کاهش کارایی: در این روش معمولاً کارایی کاهش مییابد چرا که فرمها برای تعامل با HTML ایجاد شدهاند نه JSON.
بنابراین بهتر است منطق اعتبارسنجی را به سریالایزرهای Django REST Framework منتقل کنید تا از تمام قابلیتهای این فریمورک قدرتمند برای مدیریت APIهای خود بهرهمند شوید.