【问题标题】:how to put several objects in one template如何将多个对象放在一个模板中
【发布时间】:2017-04-08 03:44:03
【问题描述】:

如何将对象从 ClassDetail 传递给 CreateNewStudent 以便在其模板中使用它?

谢谢。

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"

【问题讨论】:

    标签: python django django-templates django-class-based-views


    【解决方案1】:

    我看到你有两个模型ClassStudent。在这种情况下,创建自定义视图的更好方法:

    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})
    

    【讨论】:

    • 我确实需要使用 CBV,还有其他方法可以使用 CBV 吗?
    • 根据官方文档“显示用于创建对象的表单的视图,重新显示带有验证错误的表单(如果有)并保存对象。”。所以,没有
    猜你喜欢
    • 2019-09-12
    • 2015-09-20
    • 2020-12-21
    • 1970-01-01
    • 2016-08-20
    • 2014-08-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多