从POST查看不呈现模板

问题描述 投票:0回答:1

有一个简单的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.
python-3.7 django-2.2
1个回答
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})
© www.soinside.com 2019 - 2024. All rights reserved.