使用Django表单预约医生

jgzswidk  于 2023-10-21  发布在  Go
关注(0)|答案(1)|浏览(133)

我是Django的新手。我试图建立一个基本的牙医网站,可用于病人预约,作为一个实践项目。
我面临的问题是,我无法动态显示可用的时间段,以防止重复预订。时隙字段显示为空白。
我尝试在Django表单本身的构造函数中构建逻辑,以便在用户选择日期时只显示可用的时间段。
Django的形式是:

`from django import forms
from django.forms.widgets import DateInput
from .models import Appointment

class DatePickerInput(DateInput):
    def __init__(self, *args, **kwargs):
        attrs = kwargs.get('attrs', {})
        attrs.update({'data-provide': 'datepicker','data-date-start-date': '0d'})
        kwargs['attrs'] = attrs
        super().__init__(*args, **kwargs)

class AppointmentForm(forms.Form):
    first_name = forms.CharField(max_length=100, widget=forms.TextInput(attrs={'class': 'form-control ', 'placeholder': 'First Name'}))
    last_name = forms.CharField(max_length=100, widget=forms.TextInput(attrs={'class': 'form-control ', 'placeholder': 'Last Name'}))
    age = forms.IntegerField(widget=forms.NumberInput(attrs={'class': 'form-control ', 'placeholder': 'Age'}))
    date = forms.DateField(
        widget=DatePickerInput(
            attrs={'class': 'form-control datepicker px-2', 'placeholder': 'Date of visit'}
        )
    )
    time_slot = forms.ChoiceField(choices=[('', 'Select Time Slot')] + [(option, option) for option in [
        '09:00 AM', '10:00 AM', '11:00 AM', '12:00 PM', '02:00 PM', '03:00 PM', '04:00 PM', '05:00 PM', '06:00 PM', '07:00 PM',
    ]], widget=forms.Select(attrs={'class': 'form-control'}))
    contact_number = forms.CharField(max_length=15, widget=forms.TextInput(attrs={'class': 'form-control ', 'placeholder': 'Contact Number'}))
    email = forms.EmailField(required=False, widget=forms.EmailInput(attrs={'class': 'form-control ', 'placeholder': 'Email'}))
    treatment_needed = forms.ChoiceField(choices=[('', 'Select Treatment')] + [(option, option) for option in [
        'Apicectomy', 'Bone grafting', 'Ceramic venner/laminates', 'Cast partial denture', 'Consultation',
        'Dental filling', 'Dental implants', 'Dental implants crown', 'Direct sinus lift surgery', 'E-max crown',
        'Gum depigmentation', 'Gum recontouring/gum esthetic surgery', 'IOPA X-Ray', 'Inlay/onlay composite',
        'Inlay/onlay metallic', 'Indirect sinus lift surgery', 'Metal Ceramic Crown', 'Metal Crown', 'Operculectomy',
        'Orthodontic ceramic braces', 'Orthodontic metallic braces', 'Orthodontic self-ligating ceramic braces',
        'Orthodontic treatment (aligners)', 'Orthodontic treatment (self-ligating metallic braces)',
        'Pediatric Root canal Treatment with metal cap', 'Pediatric Root canal Treatment with zirconia cap',
        'Pediatric dental filling', 'Pediatric extraction', 'Pediatric fluoride application (each arch)',
        'Pediatric scaling & polishing', 'Pediatric space maintainer', 'Periodontal flap surgery',
        'Pit & fissure sealant', 'Post & Core', 'Post Root canal treatment Filling (Composite)',
        'Premium dental implant', 'Removable acrylic partial denture', 'RE-Root canal treatment', 'Root canal Treatment',
        'Scaling & polishing', 'Simple extraction/tooth removal', 'Smile designing', 'Specialized complete denture',
        'Std.complete denture', 'Surgical extraction/wisdom tooth removal', 'Teeth Whitening',
    ]], widget=forms.Select(attrs={'class': 'form-control '}), required=False)
    notes = forms.CharField(required=False, widget=forms.Textarea(attrs={'class': 'form-control ', 'rows': 5, 'placeholder': 'Write your notes or questions here...'}))
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        
        selected_date = self.data.get('date')
        
        if selected_date:
            booked_appointments = Appointment.objects.filter(date=selected_date).values_list('time_slot', flat=True)
            all_time_slots = [
                '09:00 AM', '10:00 AM', '11:00 AM', '12:00 PM', '02:00 PM',
                '03:00 PM', '04:00 PM', '05:00 PM', '06:00 PM', '07:00 PM',
            ]
            available_time_slots = [slot for slot in all_time_slots if slot not in booked_appointments]

            self.fields['time_slot'].choices = [('', 'Select Time Slot')] + [(slot, slot) for slot in available_time_slots]
`

模型类为:

`
from django.db import models

class Appointment(models.Model):
    first_name = models.CharField(max_length=100)
    last_name = models.CharField(max_length=100)
    age = models.IntegerField()  
    date = models.DateField()
    time_slot = models.CharField(max_length=20)
    contact_number = models.CharField(max_length=10)
    email = models.EmailField()
    treatment_needed = models.CharField(max_length=100)
    notes = models.TextField()
    is_available = models.BooleanField(default=True)`

约会表单的HTML模板是:

<form method="post" action="{% url 'home' %}" class="p-5 bg-white">
              {% csrf_token %}
<div class="row form-group">
                <div class="col-md-6 mb-3 mb-md-0">
                  <label class="font-weight-bold" for="{{ appointment_form.first_name.id_for_label }}">First Name*</label>
                  {{ appointment_form.first_name }}
                </div>
                <div class="col-md-6">
                  <label class="font-weight-bold" for="{{ appointment_form.last_name.id_for_label }}">Last Name*</label>
                  {{ appointment_form.last_name }}
                </div>
              </div>
            
              <div class="row form-group">
                <div class="col-md-6 mb-3 mb-md-0">
                  <label class="font-weight-bold" for="{{ appointment_form.age.id_for_label }}">Age*</label>
                  {{ appointment_form.age }}
                </div>
                <div class="col-md-6">
                  <label class="font-weight-bold" for="{{ appointment_form.contact_number.id_for_label }}">Contact Number*</label>
                  {{ appointment_form.contact_number }}
                </div>
              </div>
                          
              <div class="row form-group">
                <div class="col-md-6 mb-3 mb-md-0">
                    <label class="font-weight-bold" for="{{ appointment_form.date.id_for_label }}">Date*</label>
                    {{ appointment_form.date }}
                </div>
                <div class="col-md-6 mb-3 mb-md-0">
                    <label class="font-weight-bold">Time Slot*</label>
                    {{ appointment_form.time_slot }}
                    <!-- Error message div for Time Slot -->
                    <div id="time_slot_error" class="text-danger">
                      {% if error_message %}
                          {{ error_message }}
                      {% endif %}
                    </div>
                </div>                                        
              </div>                           
              <div class="row form-group">
                <div class="col-md-12">
                  <label class="font-weight-bold" for="{{ appointment_form.email.id_for_label }}">Email</label>
                  {{ appointment_form.email }}
                </div>             
              </div>
            
              <div class="row form-group">                
                <div class="col-md-12">
                  
                  <label class="font-weight-bold" for="{{ appointment_form.treatment_needed.name }}">Treatment Needed</label>
                  {{ appointment_form.treatment_needed }}
                  
                </div>
              </div>
            
              <div class="row form-group">
                <div class="col-md-12">
                  <label class="font-weight-bold" for="{{ appointment_form.notes.id_for_label }}">Notes</label>
                  {{ appointment_form.notes }}
                </div>
              </div>
            
              <div class="row form-group">
                <div class="col-md-12">
                  <input type="submit" value="Send" class="btn btn-primary">
                </div>
              </div>  
            </form>
s6fujrry

s6fujrry1#

如果你使用的是postgres数据库,你可以使用DateTimeRangeField并做你需要避免重叠的约束。

相关问题