Django 无法在基于 class 的视图中呈现表单

Django unable to render form in class based view

我有一个基于函数的视图,它输出一个形式,但是当我试图在class 基于视图 在页面上看不到任何表格,也没有错误

基于函数的视图

def edit_post(request,id):

    posts=Post.objects.get(id=id)
    forms = PostForm
    if request.method == 'POST':
        form = PostForm(request.POST, instance=posts)
        print form
        if form.is_valid():
            uncommit = form.save(commit=False)

            form.save()
            return redirect("home")
        else:
          print form.errors
    else:
        form = PostForm()
    return render(request, "edit_post.html", {'forms': forms,'posts':posts})

Class 基于视图

class CourseEntryCreateView(CreateView):
    form_class = PostForm
    model = Post
    template_name = 'edit_post.html'

    def dispatch(self, *args, **kwargs):
        self.course = get_object_or_404(Post, pk=kwargs['id'])
        return super(CourseEntryCreateView, self).dispatch(*args, **kwargs)

    def form_valid(self, form):
        self.object = form.save(commit=False)
        # self.object.course = self.course
        self.object.save()
        return HttpResponseRedirect(self.get_success_url())

我仍在学习 Django,如果有任何 要在基于 class 的视图中完成的更改,请告诉我

感谢任何帮助..提前致谢

您的基于函数的视图很混乱,因为它使用了两个变量 formforms。您应该将其更改为仅使用 form。然后更新您的模板以使用 {{ form }} 而不是 {{ forms }}.

修复模板后,表单应显示在模板中。如果您正在编辑现有对象,则应使用 UpdateView 而不是 CreateView。您不必重写 dispatchform_value,通常有更好的方法。