I have 5 Model forms like below
class AccountForm(ModelForm):
class Meta:
model = Account
class TransactionForm(ModelForm):
class Meta:
model = Transaction
.
.
.
.
Now for first form i have this view
def create_account(request, acc_id=None):
if acc_id:
f = Account.objects.get(pk=acc_id)
act1 = 'update/' + acc_id
else:
f = None
act1 = 'create'
if request.method == 'POST': # If the form has been submitted...
form = AccountForm(request.POST, request.FILES, instance=f) # A form bound to the POST data
if form.is_valid(): # All validation rules pass
form.save()
return HttpResponseRedirect('/thanks/') # Redirect after POST
else:
form = AccountForm(instance=f) # An unbound form
return render_to_response('account_form.html', {
'form': form,
'action':act1,
'type':'account',
})
Now this view does the editing and creating of new AccountForm.
But i have to do same thing for other five forms. Now i have to copy the same code 5 times with minor chnages. I need to perform the same operation only Form name will be different.
Is there any way that i can use one function for all ModelForms.
The template i use is this
<form action="/{{type}}/{{ action }}/" method="post" enctype="multipart/form-data" >
{% csrf_token %}
{% for field in form %}
<div class="fieldWrapper">
{{ field.errors }}
{{ field.label_tag }}: {{ field }}
</div>
{% endfor %}
<p><input type="submit" value="Submit" /></p>
</form>
so basically template is also same
My URL.py also has to copy same lines like below
(r'^account/create/$', create_account),
(r'^account/update/(\d)/$', create_account),
(r'^txn/create/$', create_txn),
(r'^txn/update/(\d)/$', create_txn),
Is there any posibility of reducing the code
Store the forms in a dictionary, keyed by the model name.
… and so on.