Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django TemplateView and form

I have some problem to figure out how new django views (template view) and forms can works I also can't find good resources, official doc don't explain me how can get request ( I mean get and post) and forms in new django views class

Thanks

added for better explain

for example I have this form :

from django import forms

class ContactForm(forms.Form):
    subject = forms.CharField(max_length=100)
    message = forms.CharField()
    sender = forms.EmailField()
    cc_myself = forms.BooleanField(required=False)

and this is the code for read and print the form (old fashion way):

def contact(request):
    if request.method == 'POST': # If the form has been submitted...
        form = ContactForm(request.POST) # A form bound to the POST data
        if form.is_valid(): # All validation rules pass
            # Process the data in form.cleaned_data
            # ...
            return HttpResponseRedirect('/thanks/') # Redirect after POST
    else:
        form = ContactForm() # An unbound form

    return render_to_response('contact.html', {
        'form': form,
    })

well my question is how you can do the same thing with template view thanks

like image 952
LXG Avatar asked Nov 15 '11 08:11

LXG


People also ask

What is TemplateView Django?

Django provides several class based generic views to accomplish common tasks. The simplest among them is TemplateView. It Renders a given template, with the context containing parameters captured in the URL. TemplateView should be used when you want to present some information on an HTML page.

What are forms in Django?

Django provides a Form class which is used to create HTML forms. It describes a form and how it works and appears. It is similar to the ModelForm class that creates a form by using the Model, but it does not require the Model.

How do you customize a form in Django?

So, we have to just design the HTML with css, and use it in Django by just replacing the input tag with render_field and form. field_name with {% %} at the end and design it with our choice.

What is form AS_P in Django?

{{ form.as_p }} – Render Django Forms as paragraph. {{ form.as_ul }} – Render Django Forms as list.


2 Answers

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.

like image 93
radtek Avatar answered Oct 23 '22 03:10

radtek


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
like image 30
AndreasT Avatar answered Oct 23 '22 04:10

AndreasT