I setup simple CRUD in Django
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.core.urlresolvers import reverse_lazy
from django.http import HttpResponseRedirect
from intentions.models import User,Prayer,Intention
from intentions.forms import IntentionForm, DeleteIntentionForm
def index(request):
intentions = Intention.objects.all();
return render_to_response('intentions/templates/index.html',
{'intentions': intentions},
context_instance=RequestContext(request)
)
def show(request, id):
try:
intention = Intention.objects.get(pk=id)
except Intention.DoesNotExist:
return render_to_response('intentions/templates/404_show.html')
return render_to_response('intentions/templates/show.html',
{'intention': intention, 'delete_form': DeleteIntentionForm(instance=intention)},
context_instance=RequestContext(request)
)
def new(request):
if request.method == 'POST': # If the form has been submitted...
form = IntentionForm(request.POST) # A form bound to the POST data
if form.is_valid(): # All validation rules pass
# Process the data in form.cleaned_data
# ...
intention = form.save()
return HttpResponseRedirect(reverse_lazy('intention-show', args=[intention.id])) # Redirect after POST
else:
form = IntentionForm() # An unbound form
return render_to_response('intentions/templates/form.html',
{'form': form, 'form_url': reverse_lazy('intention-new')},
context_instance=RequestContext(request)
)
def edit(request, id):
intention = Intention.objects.get(pk=id)
if request.method == 'POST': # If the form has been submitted...
form = IntentionForm(request.POST, instance=intention) # A form bound to the POST data
if form.is_valid(): # All validation rules pass
# Process the data in form.cleaned_data
# ...
intention = form.save()
return HttpResponseRedirect(reverse_lazy('intention-show', args=[intention.id])) # Redirect after POST
else:
intention = Intention.objects.get(pk=id)
form = IntentionForm(instance=intention) # An unbound form
return render_to_response('intentions/templates/form.html',
{'form': form, 'form_url': reverse_lazy('intention-edit', args=[intention.id])},
context_instance=RequestContext(request)
)
def delete(request, id):
if request.method == 'POST':
try:
intention = Intention.objects.get(pk=id)
except Intention.DoesNotExist:
return render_to_response('intentions/templates/404_show.html')
intention.delete()
return HttpResponseRedirect('/')
else:
return render_to_response('intentions/templates/404_show.html')
I see some fragments for refactor, but I am newbie in Python and Django and I would like to get advices from more experienced users about refactoring this code too.