I’ve successfully used forms before but this implementation is not working. My intention is the following. A particular classroom is shown at /gradebook/id. I want my view to take classroom_id and then save it with student names using the form.
#models.py
class Student(models.Model):
classroom = models.ForeignKey(Classroom, on_delete=models.CASCADE)
student_first = models.CharField(default='John', max_length=30)
student_last = models.CharField(default='Smith', max_length=30)
nickname = models.CharField(default='JohnS', max_length=31)
attend = models.BooleanField(default=True)
do_not_pick = models.BooleanField(default=False)
#forms.py
class SingleStudentForm(ModelForm):
class Meta:
model = Student
fields = ('student_first', 'student_last', 'classroom',)
widgets = {'classroom': forms.HiddenInput,}
#urls.py
app_name = 'gradebook'
urlpatterns = [path('<int:classroom_id>/', views.classdetail, name='classdetail'),]
#views.py
def classdetail(request, classroom_id):
context = {'classroom': classroom_id}
print("start")
if request.method == 'POST':
form = SingleStudentForm(request.POST)
print("post")
if form.is_valid():
student = form.save(commit=False)
student.save()
print("valid")
#form = SingleStudentForm(None)
#context['form'] = form
return render(request, "gradebook/classdetail.html", context)
else:
context['form'] = form
print("not valid")
return render(request, "gradebook/classdetail.html", context)
else:
form = SingleStudentForm(None)
context['form'] = form
print("here")
return render(request, "gradebook/classroom.html", context)
#templates
#classdetail.html
<div class="form-group">
<form action="{% url 'gradebook:classdetail' classblock.id %}" method="post">
{% csrf_token %} {{ form }}
<div class="form-group">
<button type="submit" class="btn btn-default">Submit</button>
</div>
</form>
</div>
#originating html template that takes you to the form/classroomdetail
<ul>
{% for classroom in classroom_list %}
<li><a href="{% url 'gradebook:classdetail' classroom.id %}">{{ classroom.classroom_name }}</a></li>
{% endfor %}
</ul>
When I run this, my terminal prints out “start” and “here”. This tells me that the my view does not think this is a post method since “post” never prints out. As well, I don’t think I’m passing the classroom_id to the SingleStudentForm.
Thank you.