0

Newbie Question: I have a FormView which displays a sign-up form, using Django's validations, etc. It all works fine, however, I can't seem to work out how to provide any data (context) to the template. Currently, I have:

from django.shortcuts import render
from django.shortcuts import redirect
from django.http import HttpResponse
from accounts.forms import SignUpForm

class SignUpView(FormView):
    template_name = 'accounts/signup.html'
    form_class = SignUpForm 

    def form_valid(self, form):
        # executes when form validates..
        (...)
        return redirect('/account/')

I tried adding some context data via get() per below, which I need when the page first displays, which sort of works except the input fields of the form are gone (the labels are all there):

def get(self, request):
    return render(self.request, self.template_name, {'data': data })

Could someone please clarify why that is, and how to get it to work? To put it another way: When using FormView with form_valid(), where do I place code intended for the initial GET request?

pete
  • 2,739
  • 4
  • 32
  • 46

1 Answers1

0

You have to methods of doing it, if the data is related only to that get view then you can move on:

def get_context_data(self, **kwargs):
    context = super(SignUpView, self).get_context_data(**kwargs)
    something = something
    context['something'] = something
    return context

Or use a Mixin:

class SomeMixin(object):

    def get_context_data(self, **kwargs):
        context = super(SomeMixin, self).get_context_data(**kwargs)
        something = something
        context['something'] = something
        return context

And then:

class SignUpView(SomeMixin, FormView):

    def form_valid(self, form):
        ...
petkostas
  • 7,250
  • 3
  • 26
  • 29
  • I tried the first approach above but I doesn't look like the context hits the template -- getting `TypeError at /account/signup/ 'NoneType' object is not iterable` (which it should be). Victor's solution above, using `get_context_data(self, **kwargs)` did the trick. Thanks guys! – pete Jan 17 '14 at 22:43
  • I am sorry I made a mistake in the first code, it should be get_context_data for the context I am editing it now. – petkostas Jan 17 '14 at 22:46