[Django]-Django TemplateView and form

18πŸ‘

βœ…

I would recommend just plodding through the official tutorial and I think realization will dawn and enlightenment will come automatically.

Basically:
When you issue a request: ”’http://mydomain/myblog/foo/bar”’
Django will:

  1. resolve myblog/foo/bar to a function/method call through the patterns defined in urls.py
  2. call that function with the request as parameter, e.g. myblog.views.foo_bar_index(request).
  3. and just send whatever string that function returns to the browser. Usually that’s your generated html code.

The view function usually does the following:

  1. Fill the context dict for the view
  2. Renders the template using that context
  3. returns the resulting string

The template generic view allows you to skip writing that function, and just pass in the context dictionary.

Quoting the django docs:

from django.views.generic import TemplateView

class AboutView(TemplateView):
    template_name = "about.html"

All views.generic.*View classes have views.generic.View as their base. In the docs to that you find the information you require.
Basically:

# urls.py
urlpatterns = patterns('',
        (r'^view/$', MyView.as_view(size=42)),
    )

MyView.as_view will generate a callable that calls views.generic.View.dispatch()
which in turn will call MyView.get(), MyView.post(), MyView.update() etc.
which you can override.

To quote the docs:

class View

dispatch(request, *args, **kwargs)

The view part of the view β€” the method that accepts a request
argument plus arguments, and returns a HTTP response. The default
implementation will inspect the HTTP method and attempt to delegate to
a method that matches the HTTP method; a GET will be delegated to
get(), a POST to post(), and so on.

The default implementation also sets request, args and kwargs as
instance variables, so any method on the view can know the full
details of the request that was made to invoke the view.

The big plusses of the class based views (in my opinion):

  1. Inheritance makes them dry.
  2. More declarative form of programming
πŸ‘€AndreasT

51πŸ‘

Use a FormView instead, i.e.

from django.views.generic import TemplateView, FormView

from forms import ContactUsEmailForm


class ContactView(FormView):
    template_name = 'contact_us/contact_us.html'
    form_class = ContactUsEmailForm
    success_url = '.'

    def get_context_data(self, **kwargs):
        context = super(ContactView, self).get_context_data(**kwargs)
        #context["testing_out"] = "this is a new context var"
        return context

    def form_valid(self, form):
        # This method is called when valid form data has been POSTed.
        # It should return an HttpResponse.
        #form.send_email()
        #print "form is valid"
        return super(ContactView, self).form_valid(form)

More on FormView in Django Docs

Technically TemplateView can also be used, just overwrite the post method, since by default template view does not allow you to post to it:

class ContactUsView(TemplateView):
    template_name = 'contact_us/contact_us.html'

    def post(self, request, *args, **kwargs):
        context = self.get_context_data()
        if context["form"].is_valid():
            print 'yes done'
            #save your model
            #redirect

        return super(TemplateView, self).render_to_response(context)

    def get_context_data(self, **kwargs):
        context = super(ContactUsView, self).get_context_data(**kwargs)

        form = ContactUsEmailForm(self.request.POST or None)  # instance= None

        context["form"] = form
        #context["latest_article"] = latest_article

        return context

I think the FormView makes more sense though.

πŸ‘€radtek

Leave a comment