如何在HTML表单中实现年份区间选择并将年份列表传递至Django?
Hey there! It looks like you need a way to let users pick both a start and end year, then send that range to your Django backend. The code you found only handles a single year dropdown, so let's build something that fits your needs. Here are two solid approaches:
Option 1: Two Dropdown Select Boxes (User-Friendly, Restricted Choices)
This is great if you want to limit users to valid years (no typos!) and keep the interface straightforward.
HTML & JavaScript Code
<form method="POST" action="{% url 'your_django_view_name' %}"> {% csrf_token %} <!-- Don't forget this for Django POST requests! --> <label for="start_year">Start Year:</label> <select name="start_year" id="start_year"></select> <label for="end_year">End Year:</label> <select name="end_year" id="end_year"></select> <button type="submit">Submit Year Range</button> </form> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> <script> const startYearMin = 1800; const currentYear = new Date().getFullYear(); // Populate both dropdowns with years from 1800 to current year function populateYearDropdowns() { const startSelect = $('#start_year'); const endSelect = $('#end_year'); for (let year = startYearMin; year <= currentYear; year++) { startSelect.append($('<option />').val(year).text(year)); endSelect.append($('<option />').val(year).text(year)); } // Set default values (e.g., current year as end, 2000 as start) startSelect.val(2000); endSelect.val(currentYear); } // Add a check to make sure end year isn't before start year $('form').submit(function(e) { const start = parseInt($('#start_year').val()); const end = parseInt($('#end_year').val()); if (end < start) { alert('End year can\'t be earlier than start year!'); e.preventDefault(); // Stop form submission } }); // Run the function when the page loads $(document).ready(populateYearDropdowns); </script>
Django Backend Setup
In your view, you can grab the submitted years like this:
from django.shortcuts import render def your_year_view(request): if request.method == 'POST': start_year = request.POST.get('start_year') end_year = request.POST.get('end_year') # Do something with start_year and end_year (e.g., query a database) return render(request, 'results.html', {'start': start_year, 'end': end_year}) return render(request, 'year_input.html')
Option 2: Numeric Input Boxes (More Flexible)
If you want users to type in years instead of selecting, use number inputs with validation to ensure valid values.
HTML & JavaScript Code
<form method="POST" action="{% url 'your_django_view_name' %}"> {% csrf_token %} <label for="start_year">Start Year:</label> <input type="number" name="start_year" id="start_year" min="1800" max="{{ current_year }}" value="2000"> <label for="end_year">End Year:</label> <input type="number" name="end_year" id="end_year" min="1800" max="{{ current_year }}" value="{{ current_year }}"> <button type="submit">Submit Year Range</button> </form> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> <script> $('form').submit(function(e) { const start = parseInt($('#start_year').val()); const end = parseInt($('#end_year').val()); const currentYear = new Date().getFullYear(); if (start < 1800 || start > currentYear) { alert('Start year must be between 1800 and ' + currentYear); e.preventDefault(); } else if (end < 1800 || end > currentYear) { alert('End year must be between 1800 and ' + currentYear); e.preventDefault(); } else if (end < start) { alert('End year can\'t be earlier than start year!'); e.preventDefault(); } }); </script>
Note for Django Template
To pass the current year to the template, add this to your view:
from datetime import datetime from django.shortcuts import render def your_year_view(request): current_year = datetime.now().year return render(request, 'year_input.html', {'current_year': current_year})
Both options will let users input a valid year range and send it to your Django backend smoothly. Pick the one that fits your UI needs best!
内容的提问来源于stack exchange,提问作者project.py

