0

Got a simple Django app, for some reason GET renders template as expected, but POST with exactly the same code does not error but also does not render either:

I've spent a lot of time looking for a reason for this and assume either I'm missing something stupid or a change in 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.

Tom Carrick
  • 6,349
  • 13
  • 54
  • 78
Zach Cleary
  • 458
  • 1
  • 4
  • 17

1 Answers1

0

Assuming you are having a form to post data with NameForm class in forms.py, form.html with form for posting .

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})
Joel Deleep
  • 1,308
  • 2
  • 14
  • 36