Choices field not rendering in HTML page in my Django project

I have a model with 3 Charfields with choices, I am struggling to render the choices in my html page. On the html page, I had a card color coded between 3 colors. Instead of rendering based on selected choice in the backend, it renders the same results across different vin searches.

Here is the model in 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"

Here is the view that handles the rendering everything to the 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,
    })

Here is the html code for one the choices field

<!-- 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>

In your search view, you're setting vehicle_status using vehicle.history.all() instead of vehicle.vehiclestatus.

Change this line in your search function:

vehicle_status = vehicle.history.all() # Incorrect
vehicle_status = getattr(vehicle, 'vehiclestatus', None) # Correct

Now, since vehicle_status is a single object (or None if not found), update your template:

{% 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 %}

Вернуться на верх