I have recently starting learning Django and trying to built a simple edit form based on the value selected from the dropdown list. This dropdown list is populated from the backend database column 'student_first_name' from the Students Model. When a particular student_first_name is selected and submitted, an edit form with all the details of the student should be generated in the same template for editing purpose. In that, only the student_id field should be read only. I am able to generate the dropdown list and get the 'student_id' value in the selected_item variable. But I am not able to understand on how to use this to generate an edit form. Also is there any other better way to achieve this? This is my first draft of the code so any suggestions would be really appreciated.
models.py
class Students(models.Model):
student_id = models.IntegerField(primary_key=True)
student_first_name = models.CharField(max_length=100, null=True)
student_last_name = models.CharField(max_length=100, null=True)
student_address = models.CharField(max_length=255, null=True)
student_dob = models.DateTimeField(null=True)
student_doa = models.DateTimeField(null=True)
views.py
def student_edit(request):
details = Students.objects.all()
form = request.POST
if request.method == 'POST':
selected_item = get_object_or_404(Students, pk=request.POST.get('student_id')).student_id
return render(request, 'student_edit.html', {'details': details})
student_edit.html
<form method="POST" novalidate>
{% csrf_token %}
<select name="student_id" class="form-control">
<option value="">Select Student Name</option>
{% for detail in details %}
<option value="{{ detail.student_id }}">{{ detail.student_first_name }}</option>
{% endfor %}
</select>
<button type="submit" class="btn btn-success">Select</button>
</form>