Zero to Django in 4 months - What I've learned - Part 2

  • Sun 28 October 2012

  • To further what I've learned in 4 short months of Django, the first thing pointed out to me came courtesy of IRC #django channel. I posted a bit of code, and a question was asked "Why don't you use 'create view'. Why? Cause I didn't know what the hell it was.

    Generic Views

    I was writing a bunch of stuff like this in the first project (this exists in an app's view.py):

    @login_required(login_url='/accounts/login')
    def add_artist(request):
        """Add a new Visiting Artist"""
        form = ArtistForm()
        if request.method == 'POST':
    form = ArtistForm(request.POST)
    if form.is_valid():
        form.save()
        return HttpResponseRedirect('/adm/artists')
        template = 'adm-artist.html'
        data = {
    'form': form,
        }
    
        return render_to_response(template, data, context_instance=RequestContext(request))
    
    
    @login_required(login_url='/accounts/login/')
    def delete_artist(self, pk=None):
        """Delete an Artists"""
        VisitingArtist.objects.get(pk=pk).delete()
    
        return HttpResponseRedirect('/adm/artists')
    
    
    @login_required(login_url='/accounts/login/')
    def edit_artist(self, pk=None):
        """Edit An Artist"""
        VisitingArtist.objects.get(pk=pk)
        return HttpResponseRedirect('/adm/sponsors')
    
    
    def displayArtists(request):
        """Display all Aritsts"""
        artists = VisitingArtist.objects.all().order_by('name')
        return render_to_response('artists.html',
    {'artists': artists},
        context_instance=RequestContext(request))
    

    With generic views, I could do something like this (in urls.py):

    ## Add a product
    url(r'^add/$', login_required(
    CreateView.as_view(
            model=Product,
            form_class=ShopProductForm,
            success_url=("/account/product"),
            template_name="account/admin_product_distributor_form.html")),
            name="add-product"),
    ##Update a product
    url(r'^edit/(?P<pk>\d+)/$',login_required(
    UpdateView.as_view(
            model=Product,
            form_class=ShopProductForm,
            success_url=("/account/product"),
            template_name="account/admin_product_distributor_form.html")),
            name="update-product"),
    ##Delete a product
    url(r'^delete/(?P<pk>\d+)/$', login_required(
            DeleteView.as_view(
            model=Product,
            success_url=("/account/product"))),
            name="delete-product"),
    

    To me the above seems simpler. Of each url, I'm defining a path r^delete/(?P<pk>\d+)/$. I'm using the login_required decorator to require a login. Then I'm using the generic DeleteView.as_view, defining model with model=, DeleteView requires a success_url and I'm naming the url with name=.

    render instead of render_to_response

    Something else I learned later on was render as a shortcut to render_to_response. render is new in 1.3

    In the above example, you see something like this:

    return render_to_response(template, data,
    context_instance=RequestContext(request))
    

    with render this is simplified even further like so:

    return render(request, template, data)
    

    Awesome, right?!

    Comments !

    social