Django: class representations, general representations, etc.

I am returning to Django after a brief meeting with version 1.2, and now in version 1.3 the preferred approach to views seems to use classes.

Keeping the code style, maintainability and modularity: when should I use classes and when are functions? Should I always spread from the general representations of the class (it seems there is no harm in using TemplateView), or should I use my own objects called by the object?

Thanks in advance.

+3
source share
2 answers

There are, in my opinion, two cases of the need for class (-generic) -views:

  • You really need common features in your views and a little more.
  • Django , .

- , . , , TemplateView , ( ). .

EDIT. , , , request.method 405 Method Not Allowed, . , , if request.method=='POST' if request.method=='GET', post get.

+3

, .

, , ( ) :

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,
    })

, ifs :

class Contact(FormView):
    template_name = 'contact.html'
    form_class = ContactForm
    success_url = '/thanks/'

    def form_valid(self, form):
        # Process the data in form.cleaned_data
        return super(Contact, self).form_valid(form)

, , , , Django . , , , .

+7

All Articles