简体   繁体   中英

Use function from another file in Django views.py

I've created a whole function in my Django views.py and it works. It looks like this:

SOME IMPORTS

def get_campaigns(request):

SOME CODE

    campaign_data = []

    for batch in stream:
        for row in batch.results:
            data = {}
            data["campaign_id"] = row.campaign.id
            data["campaign_name"] = row.campaign.name
            campaign_data.append(data)

    return render(request, 'hello/get.html',{ 'data' : data })

But then I learned that having your whole functions on views.py is not a good practice at all. I should move the "big" functions to a different file and then call them on views.py, right?

So I tried different options and the only one that worked for me is copying exactly that same code on a different file and then adding to my views.py:

def index(request):
    data = get_campaigns(request),
    return render(request, 'index.html',{ 'data' : data })

So I'm repeating the same line (return render...) in both files. It works, but looks very ugly and maybe it's slow, buggy or even insecure.

Is there a better solution?

PD: As you can guess from my question, I'm a complete beginner and I don't really know what I'm doing, so any pointers to beginner-friendly tutorials related to this are much appreciated. 😅

It's not too clear what code is going where, but I understand your issue. I remember writing a HUGE views.py when I started.

I think what you've done is OK. You can also define the request for a get, post, etc. Good practice.

I assume in your function which you're importing simply performs the data stream and doesn't render the page. You leave that to the view.py?

Apologies for not commenting and answering, my reputation score doesn't allow me too yet.

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