Goun2 Goun2 - 15 days ago 5
Python Question

how to put several objects in one template

How do I pass the object from ClassDetail to CreateNewStudent in order to use it in its template ?

Thanks.

class ClassDetail(DetailView):
context_object_name = "Class"
template_name = "temp/students.html"
model = Class

class CreateNewStudent(CreateView):
model = Student
form_class = forms.StudentForm
template_name = "temp/newstudent.html"

Answer

As I see you have two models Class and Student. In this case better way to create custom view:

def myCustomView(request, pk):
  get_class = get_object_or_404(Class, pk=pk)
  student_form = StudentForm
    if request.POST:
      student_form = StudentForm(request.POST)
      if student_form.is_valid():
        ...
        return ...
      else:
        return render(request, 'index.html', {'get_class':get_class, 'student_form':sudent_form})
    else:
      return render(request, 'index.html', {'get_class':get_class, 'student_form':sudent_form})