from django.shortcuts import render from django.views import View class IndexView(View): def get(self, request, *args, **kwargs): # For now, units are hardcoded. This will be moved to the database later. units = { 'Length': ['meters', 'feet', 'inches'], 'Mass': ['kilograms', 'pounds', 'ounces'], 'Temperature': ['Celsius', 'Fahrenheit', 'Kelvin'] } context = { 'units': units, 'page_title': 'Engineering Unit Converter', } return render(request, 'core/index.html', context) def post(self, request, *args, **kwargs): # Hardcoded units and conversion factors for the first iteration units = { 'Length': ['meters', 'feet', 'inches'], 'Mass': ['kilograms', 'pounds', 'ounces'], 'Temperature': ['Celsius', 'Fahrenheit', 'Kelvin'] } value_in = request.POST.get('value_in') unit_in = request.POST.get('unit_in') unit_out = request.POST.get('unit_out') result = None error = None try: value_in_float = float(value_in) # Basic, non-comprehensive conversion logic # This should be replaced with a more robust library or model-driven approach # Length if unit_in == 'meters' and unit_out == 'feet': result = value_in_float * 3.28084 elif unit_in == 'feet' and unit_out == 'meters': result = value_in_float / 3.28084 # Mass elif unit_in == 'kilograms' and unit_out == 'pounds': result = value_in_float * 2.20462 elif unit_in == 'pounds' and unit_out == 'kilograms': result = value_in_float / 2.20462 # Temperature elif unit_in == 'Celsius' and unit_out == 'Fahrenheit': result = (value_in_float * 9/5) + 32 elif unit_in == 'Fahrenheit' and unit_out == 'Celsius': result = (value_in_float - 32) * 5/9 elif unit_in == unit_out: result = value_in_float else: # Placeholder for conversions not yet implemented error = f"Conversion from {unit_in} to {unit_out} is not yet supported." except (ValueError, TypeError): error = "Invalid input value. Please enter a number." context = { 'units': units, 'result': round(result, 4) if result is not None else None, 'error': error, 'value_in': value_in, 'unit_in': unit_in, 'unit_out': unit_out, 'page_title': 'Engineering Unit Converter', } return render(request, 'core/index.html', context)