简体   繁体   中英

Improve Django View with Methods

I'm looking to improve my Django web application and mainly project scripts. I'm using many times the same Python code and I would like to simplify my views.py file.

For example, I have several times this part :

if request.method == 'POST':

    form = FormBase(request.POST or None, request.FILES or None)

    if form.is_valid() :
        post = form.save()

        return HttpResponseRedirect(reverse('ReverseTemplate', kwargs={'id': post.id}))

else :
    form = FormBase()
    form.fields['Utilisateur'].initial = request.user.last_name + " " + request.user.first_name

So, instead of copy/past this part in my different view function, I would like to set :

def DjangoFormID(request, FormBase, ReverseTemplate) :

    if request.method == 'POST':

        form = FormBase(request.POST or None, request.FILES or None)

        if form.is_valid() :
            post = form.save()

            return HttpResponseRedirect(reverse('ReverseTemplate', kwargs={'id': post.id}))

    else :
        form = FormBase()
        form.fields['Utilisateur'].initial = request.user.last_name + " " + request.user.first_name

And call this function in my view :

DjangoFormID(request, IndividuFormulaire, IndividuResume)

I would like to know if my process is fine ? Is it a better way to programming rather than what I've done ?

Then, I'm getting this error : name 'IndividuResume' is not defined

How I could write my Django template inside my method ?

Thank you

It looks like the error is because 'IndividuResume' should be a string, not a variable name.

DjangoFormID(request, IndividuFormulaire, 'IndividuResume')

Inside your template, you should use the variable ReverseTemplate , not the hardcoded string 'ReverseTemplate'

return HttpResponseRedirect(reverse(ReverseTemplate, kwargs={'id': post.id}))

The advantage of including the same boilerplate in each view is that it's very easy to follow what is going on. If you are worried about the repetition, I would consider looking at class based views, because they are designed for this kind of use case. I would avoid defining your own DjangoFormID -- if I was new to your project I would not know what DjangoFormID(request, IndividuFormulaire, 'IndividuResume') did, so it would slow me down.

If you do stick with your DjangoFormID method then here's a couple of recommendations:

  • Make sure it always returns a response. At the moment, it returns a redirect response for a valid form, and None the rest of the time, which is going to cause problems.
  • when I see DjangoFormID I assume it's a class, not a function. Rename it to django_form_id .

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