从POST查看未渲染模板

时间:2019-04-05 12:14:12

标签: python-3.7 django-2.2

有一个简单的Django应用程序,由于某种原因GET可以按预期方式渲染模板,但是使用完全相同的代码进行POST不会出错,但也不会渲染:

我已经花了很多时间寻找原因,并假设我错过了一些愚蠢的东西或Django 2.2中的更改?

class MyView(View):
    template_name = "index.html"```

    def get(self, request):
        return render(request, self.template_name, context={'test':'get_test'})

    def post(self, request):
        return render(request, self.template_name, context={'test':'post_test')

```urlpatterns = [
    path('index/', MyView.as_view(), name='index'),
]

```<h2>{{ test }}</h2>```


Hopefully I haven't simplified the example beyond the point of making sense, but in the example I wish to simply render post_test following a POST which should render the entire page again.

1 个答案:

答案 0 :(得分:0)

假设您有一个表单,可以在Forms.py,form.html中使用NameForm类发布数据,其中表单用于发布。

class MyForm(View):

form_class = NameForm
initial = {'key': 'value'}
template_name = 'form.html'

def get(self, request, *args, **kwargs):
    form = self.form_class(initial=self.initial)
    return render(request, self.template_name, {'form': form})

def post(self, request, *args, **kwargs):
    form = self.form_class(request.POST)
    if form.is_valid():
        # <process form cleaned data>
        return HttpResponseRedirect('/success/')

    return render(request, self.template_name, {'form': form})
相关问题