Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reusing a Django app within a single project

Tags:

python

django

In trying to save as much time as possible in my development and make as many of my apps as reusable as possible, I have run into a bit of a roadblock. In one site I have a blog app and a news app, which are largely identical, and obviously it would be easier if I could make a single app and extend it where necessary, and then have it function as two separate apps with separate databases, etc.

To clarify, consider the following: hypothetically speaking, I would like to have a single, generic news_content app, containing all the relevant models, views, url structure and templatetags, which I could then include and extend where necessary as many times as I like into a single project.

It breaks down as follows:

news_content/
    templatetags/
        __init__.py
        news_content.py
    __init__.py
    models.py (defines generic models - news_item, category, etc.)
    views.py (generic views for news, archiving, etc.)
    urls.py
    admin.py

Is there a way to include this app multiple times in a project under various names? I feel like it should be obvious and I'm just not thinking clearly about it. Does anybody have any experience with this?

I'd appreciate any advice people can give. Thank you.

like image 612
Gary Chambers Avatar asked Jul 27 '09 13:07

Gary Chambers


People also ask

Can a Django project have multiple apps?

A single Django project contains multiple apps in it. Multiple Django apps are created in a single project.

How many apps can a Django project have?

Django comes with six built-in apps that we can examine.


2 Answers

What's the actual difference between blogs and news? Perhaps that difference ought to be part of the blog/news app and you include it just once.

If you have a blog page with blog entries and a news page with news entries and the only difference is a field in the database (kind_of_item = "blog" vs. kind_of_item = "news") then perhaps have you have this.

urls.py

(r'^/(?P<kind>blog)/$', 'view.stuff'),
(r'^/(?P<kind>news)/$', 'view.stuff'),

views.py

def stuff( request, kind ):
    content= news_blog.objects.filter( kind=kind )
    return render_to_response( kind+"_page", { 'content': content } )

Perhaps you don't need the same app twice, but need to extend the app to handle both use cases.

like image 120
S.Lott Avatar answered Oct 09 '22 23:10

S.Lott


In this case you could create the common piece of code as a Python module instead of a whole new application.

Then for each instance you would like to use it, create an app and import the bits from that module.

like image 43
Andre Miller Avatar answered Oct 10 '22 00:10

Andre Miller