リファクタリング

views.pyのところがカコワルイので
manipulatorを使用して書き換えてみました。

ymasudaさんに色々聞いたのは内緒だ:-p

/tropy/views.py

from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
from django import forms 

from tropy.models import Tropy

import random
import string

def random_url(request):
    o = random.choice(Tropy.objects.all())

    return HttpResponseRedirect('/tropy/%s/' % o.url)

def create_object(request):

    url = ''.join([random.choice(string.digits) for i in range(8)])
    
    try:
        manipulator = Tropy.ChangeManipulator(url)
    except Tropy.DoesNotExist:
        manipulator = Tropy.AddManipulator()

    if request.POST:
        from_data = request.POST.copy()
        errors = manipulator.get_validation_errors(from_data)
        
        if not errors:
            from_data['url'] = url
            manipulator.do_html2python(from_data)
            o = manipulator.save(from_data)
            
            return HttpResponseRedirect('/tropy/%s/' % o.url)

    else:
        errors = {}

    form = forms.FormWrapper(manipulator, {}, errors)

    return render_to_response('tropy/tropy_create.html', dict(form=form))

/tropy/urls.py

from django.conf.urls.defaults import *
from django.views.generic import (list_detail, simple, create_update)

from tropy.models import Tropy
from tropy.views import (random_url, create_object)

query_dict = dict(queryset=Tropy.objects.all())
model_dict = dict(model=Tropy)

urlpatterns = patterns('',
    (r'^$', simple.redirect_to, dict(url='/tropy/random/')),

    (r'^random/$', random_url),

    (r'^(?P<object_id>\d+)/$', list_detail.object_detail, 
        dict(query_dict)),

    (r'^create/$', create_object),

    (r'^update/(?P<object_id>\d+)/$', create_update.update_object, 
        dict(model_dict, template_name='tropy/tropy_update.html')),
)