简体   繁体   中英

How can i use one view for different forms in Django

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.

FORMS = {
    'account': AccountForm,
    'transaction': TransactionForm,
    ...
}

def create_object(request, object_class, object_id=None):
    form_class = FORMS[object_class]
    model = form_class._meta.model
    if object_id:
        object = model.object.get(pk=object_id)

... and so on.

Look how people do something like this at Django Generic Views .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM