Поле выбора не отображается на HTML-странице в моем проекте Django
У меня есть модель с 3-мя полями символов с вариантами выбора, я изо всех сил пытаюсь отобразить варианты на моей html-странице. На html-странице у меня была цветовая кодировка карточки из 3-х цветов. Вместо рендеринга на основе выбранного варианта в серверной части, он отображает одни и те же результаты для разных поисковых запросов по vin.
Вот модель в model.py
class VehicleStatus(models.Model):
"""
Represents the status of a vehicle, including accident history, odometer fraud, and theft involvement.
"""
ACCIDENT_HISTORY = [
("NHA","No History of Accidents"),
("OIIA", "Once Involved In Accident"),
("CAD", "Currently Accident Damaged"),
]
ODOMETER_FRAUD = [
("NOF", "No Odometer Fraud"),
("SOF", "Suspected Odometer Fraud"),
]
THEFT_INVOLVEMENT = [
("NHT", "No History of Theft"),
("OIT", "Once Involved In Theft"),
("STI", "Suspected Theft Involvement"),
]
vin_number = models.OneToOneField(Vin, on_delete=models.CASCADE, related_name='vehiclestatus', db_index=True, help_text="Vehicle Identification Number")
accident_history = models.CharField(max_length=30, choices=ACCIDENT_HISTORY, default='NHA', help_text="History of accidents involving the vehicle")
odometer_fraud = models.CharField(max_length=30, choices=ODOMETER_FRAUD, default='NOF', help_text="Indicates if the vehicle has suspected odometer fraud")
theft_involvement = models.CharField(max_length=30, choices=THEFT_INVOLVEMENT, default='NHT', help_text="Indicates if the vehicle has been involved in theft")
owner_history = models.IntegerField(help_text="Number of previous owners of the vehicle", default=0)
def __str__(self):
return f"Vehicle Status for VIN {self.vin_number}"
class Meta:
verbose_name = "Vehicle Status"
verbose_name_plural = "Vehicle Statuses"
Вот представление, которое управляет отображением всего в виде search.html
def search(request):
# Retrieve the VIN number from the GET request
vin = request.GET.get('vin_number')
vehicle = None
specs = None
inspections = []
history_records = []
vehicle_status = []
message = None
if vin:
try:
# Query the Vin model
vehicle = get_object_or_404(Vin, vin_number=vin)
# Retrieve related model data
specs = getattr(vehicle, 'specs', None)
inspections = vehicle.inspections.all()
history_records = vehicle.history.all()
vehicle_status = vehicle.history.all()
except Vin.DoesNotExist:
# If no vehicle is found, set a message
message = "No vehicle found with the provided VIN number."
except Exception as e:
# Handle other potential errors
message = f"An error occurred: {str(e)}"
else:
# If the form is not filled, set a message
message = "Please enter a VIN number to search."
# Render the template with the data and message
return render(request, 'autohistory/search.html', {
'vehicle': vehicle,
'specs': specs,
'inspections': inspections,
'history_records': history_records,
'vehicle_status': vehicle_status,
'message': message,
})
Вот html-код для одного из полей выбора
<!-- Accident History Card -->
<div class="col-md-4 mb-3">
<div class="card
{% if vehicle_status.accident_history == 'NHA' %}bg-success text-white
{% elif vehicle_status.accident_history == 'OIIA' %}bg-warning text-dark
{% else%}bg-danger text-white{% endif %}">
<div class="card-header">
<h5 class="card-title mb-0">
<i class="fas fa-car-crash me-2"></i>
Accident History
</h5>
</div>
<div class="card-body">
<p class="card-text">
<strong>Status:</strong> {{ vehicle_status.get_accident_history_display }}
</p>
<p class="card-text small">
{% if vehicle_status.accident_history == 'NHA' %}
This vehicle has no history of accidents.
{% elif vehicle_status.accident_history == 'OIIA' %}
This vehicle was involved in an accident once.
{% else %}
This vehicle is currently damaged due to an accident.
{% endif %}
</p>
</div>
</div>
</div>
В режиме поиска вы устанавливаете vehicle_status
, используя vehicle.history.all()
вместо vehicle.vehiclestatus
.
Измените эту строку в вашей функции search
:
vehicle_status = vehicle.history.all() # Incorrect
vehicle_status = getattr(vehicle, 'vehiclestatus', None) # Correct
Теперь, поскольку vehicle_status
- это единственный объект (или ни один, если он не найден), обновите свой шаблон:
{% if vehicle_status %}
<div class="card
{% if vehicle_status.accident_history == 'NHA' %}bg-success text-white
{% elif vehicle_status.accident_history == 'OIIA' %}bg-warning text-dark
{% else %}bg-danger text-white{% endif %}">
<div class="card-header">
<h5 class="card-title mb-0">
<i class="fas fa-car-crash me-2"></i>
Accident History
</h5>
</div>
<div class="card-body">
<p class="card-text">
<strong>Status:</strong> {{ vehicle_status.get_accident_history_display }}
</p>
<p class="card-text small">
{% if vehicle_status.accident_history == 'NHA' %}
This vehicle has no history of accidents.
{% elif vehicle_status.accident_history == 'OIIA' %}
This vehicle was involved in an accident once.
{% else %}
This vehicle is currently damaged due to an accident.
{% endif %}
</p>
</div>
</div>
{% else %}
<p>No vehicle status found.</p>
{% endif %}