Nick Roper
Nick Roper

Reputation: 137

Django code organisation

I've recently started working with Django. I'm working on an existing Django/Python based site. In particular I'm implementing some functionality to create and display a PDF document when a particular URL is hit. I have an entry in the app's urls file that routes to a function in the views file and the PDF generation is working fine.

However, the view function is pretty big and I want to extract the code out somewhere to keep my view as thin as possible, but I'm not sure of the best/correct approach. I'll probably need to generate other PDFs in due course so would it make sense to create a 'pdfs' app and put code in there? If so, should it go in a model or view?

In a PHP/CodeIgniter environment for example I would put the code into a model, but models seem to be closely linked to database tables in Django and I don't need any db functionality for this.

Any pointers/advice from more experienced Django users would be appreciated.

Thanks

Upvotes: 0

Views: 113

Answers (2)

Wojtek Szkutnik
Wojtek Szkutnik

Reputation: 532

If you plan to scale your project, I would suggest moving it to a separate app. Generally speaking, generating PDFs based on an url hit directly is not the best thing to do performance-wise. Generating a PDF file is pretty heavy on you server, so if multiple people do it at the same time, the performance of your system will suffer.

As a first step, just put it in a separate class, and execute that code from the view. At some point you will probably want to do some permission checks etc - that stays in the view, while generation of the PDF itself will be cleanly separated.

Once you test your code, scale etc - then you can substitute that one line call in the view into putting the PDF generation in a queue and only pulling it once it's done - that will allow you to manage your computing powers better.

Upvotes: 4

Pynchia
Pynchia

Reputation: 11590

Yes you can in principle do it in an app (the concept of reusable apps is the basis for their existence)

However not many people do it/not many applications require it. It depends on how/if the functionality will be shared. In other words there must be a real benefit.

The code normally goes in both the view/s and in the models (to isolate code and for the model managers)

Upvotes: 2

Related Questions