How do you make a Django app pluggable? - django

Say for example I have a Blog app that I want to be able to drop into different projects, but I always want the Blog to be associated with some other model. For example, in one case I may want it to be associated with a user:
site.com/someuser/blog
But on another site I want it to be associated with, say, a school:
site.com/someschool/blog
Is there a way to make the Blog app pluggable so that it's not necessary to redefine the model (adding a foreign key field) whenever I drop it into a project?

There are several important details for making sure an app can be reusable and I think it's best to link to two of the more important sets of documentation on the topic:
django-best-practices
django-reusable-apps-docs

You might want to look into the ContentTypes framework, I used it to create a comment app that can be used for commenting any model in the database (for different reasons, I didn't want to use the standard django comment app).
http://docs.djangoproject.com/en/dev/ref/contrib/contenttypes/

Generic relationships allow you to have a foreign key to any other model. However it's not clear from your question what type of object you want a foreign key to link to. I suspect that foreign key relationship isn't really generic - you just haven't spotted another part of your system that could also be a reusable app.

Related

How to add fields to third party app model?

I'm working on a web page which uses Django-quiz app. When you install the django-quiz, you can create quizes, questions etc. in Admin.
Unfortunately, there is no way, how to assign Quiz to my model Language so I'm looking for a way, how to add field Language into the model Quiz.
I've tried this but it does not work. I've tried already to create a proxy model with additional field but I realised that it is not possible in proxy models.
from quiz.models import Sitting,Quiz
class QuizAddLanguage(models.Model):
quiz = models.OneToOneField(Quiz)
language = models.ForeignKey(Language)
Do you know what to do to add field to third party app model?
For this time, OneToOne should be enough - for each language there will be one quiz
Since its one to one then you can just define the relationship on your own language class, django by default, will provide you the reverse lookup meaning
language_obj.quiz
quiz_obj.language
will both be valid.
Here is a relevant Django ticket, which was closed with a resolution of "wontfix" six years ago:
https://code.djangoproject.com/ticket/14969
I think this comment provides some good information:
Comments gives you the *right* way to handle this problem -- you define an interface, and make the model itself pluggable. Not all Django's contrib apps follow this approach, but that doesn't mean we bake monkeypatching into the core -- we fix the contrib apps.
django.contrib.comments is now a standalone app, but it still makes itself relatively easy to customize. Here is the relevant documentation:
https://django-contrib-comments.readthedocs.io/en/latest/custom.html
If a third party app doesn't make itself easy to customize, I would suggest asking the developer to update it and point them to the above links for examples on how to go about doing it.

Can I make Django admin reflect a hierarchy of models?

Assume a Django application with a few models connected by one-to-many relationships:
class Blog(models.Model):
...
class Post(models.Model):
blog = models.ForeignKey(Blog)
...
class Comment(models.Model):
post = models.ForeignKey(Post)
...
Conceptually, they form a hierarchy, a tree-like structure. I want the Django admin to reflect that. In particular:
in a changelist of posts, every post should have a link to the changelist of corresponding comments;
similarly, a post’s edit page should link to the changelist of comments from the top-right buttons area;
when I open that list of related comments, it needs to reflect the relationship in the breadcrumbs (something like: Posts › “Hello world” › Comments) and, ideally, also in the URL (post/123/comment/).
This should of course also apply to the other levels of the hierarchy.
Number 1 is pretty easy with a custom list_display entry and using the ?post__id= query to the comments changelist. But this is little more than a hack. Generally Django assumes my three models to be independent, top-level entities.
Is there a straightforward way to accomplish this? I guess I could override a bunch of templates and AdminModel methods, but perhaps there is a better solution for what seems like a common situation?
Are you sure you are not just looking at Django Admin Inline Models ?
There is no way that an automated admin will pick up your relationships, because in an RDBS there can be any number of foreign keys / one to one / many to many relations, and Django does not have a customized hierarchical behavior built in.
You can indeed edit the breadcrumb customizing an admin template if you want.
For relations you might also be interested into django MPTT that allows to make hierarchical model instances. Also see this question: Creating efficient database queries for hierarchical models (django) in that respect.
How is this a common situation? Consider the fact a model can have a virtually unlimited number of foreign key relationships, let alone visa versa. How would the admin 'know' how to represent this data the way a user requires without customizing things?
One would suggest you are used to work with content management systems rather than webframeworks (no pun intended). It's important to notice Django isn't a cms, but a webframework you can built on top of as you see fit. In a nutshell: 'Django is rather clueless and unaware of contextual requirements'.
Although the admin is quite a beast out-of-the-box, it can be hard to customize. There have been quite some discussions whether it should even be part of core. I can only suggest, if customizing things tends to get hacky, you should probably write your own 'admin', it's not that hard.

Single model for storing django application-wide options

I have a set of top-level configuration data fields that I want to be able to set within django admin for each deployment of my django app. I only want one set of these.
Example fields: site_logo, contact_person, address, facebook_url, twitter_url
The problem is that Django Admin is geared towards tables (lists) of models, so its not a good fit for this type of singular configuration model. I really only want one of these models to exist for the whole site, and to be able to click into it from admin and edit the various fields.
It seems i've come across a 3rd party app in the past to accomplish this but can't find it anywhere. Part of the problem is I'm finding it difficult to find the right words to google. Any ideas?
It looks like django-values will do what you're looking for.
Other possible contenders:
http://github.com/sciyoshi/django-dbsettings (doesn't look maintained)
http://github.com/jqb/django-settings
Have a look at django-livesettings it sounds like it might fit.
Not that i have used it, but i have heard good things about django-constance.
And there are even some more options listed in the Configuration-Grid on Django Packages.

What do I use instead of ForiegnKey relationship for multi-db relation

I need to provide my users a list of choices from a model which is stored in a separate legacy database. Foreign keys aren't supported in django multi-db setups. The ideal choice would be to use a foreign key, but since thats not possible I need to some up with something else.
So instead I created an IntegerField on the other database and tried using choices to get a list of available options.
class OtherDBTable(models.Model):
client = models.IntegerField(max_length=20, choices=Client.objects.values_list('id','name'))
the problem I'm having is that the choices seem to get populated once but never refreshed. How do I ensure that whenever the client list changes that those newest options area available to pick.
What I was really looking for was a way that I could simulate the behavior of a Foreign key field, at least as far as matching up ID's go.
There wasn't a clear way to do this, since it doesn't seem like you can actually specify an additional field when you instantiate a model (you can with forms, easily)
In any case to deal with the problem, since the database is MySQL based, I ended up creating views from the tables I needed in the other database.
To build on #Yuji's answer - if you do self.fields['field'].choices = whatever in the model's __init__, whatever can be any iterable.
This means you can inherit from iterable, and have that object interface to your legacy database, or you can use a generator function (in case you are unfamiliar, look up the yield keyword).
Citing a Django's manual:
Finally, note that choices can be any iterable object -- not necessarily a list or tuple. This lets you construct choices dynamically. But if you find yourself hacking choices to be dynamic, you're probably better off using a proper database table with a ForeignKey. choices is meant for static data that doesn't change much, if ever.
Why dont you want just export data from the legacy database and to import it into the new one? This could be done periodically, if the legacy database still in use.

Django auth.User

I'm developing web page with many type of users, each with different profiles properties. I would like to use built in auth system but:
a) I want to use django-registration.
b) I can point User.get_profile to only one profile model.
How to accomplish that in nice fashion?
I haven't used django-registration so I don't know what it entails. For the second part of your question one way would be to
Associate an UserProfile with every User
Add different kinds of ProfileProperty classes and link to them from UseProfile using a generic relationship.
I know, it is a bit of a stretch.
I'm not an expert nor in python, django or database but I encountered a somewhat similar issue few weeks ago and on #django someone advised me to use Generic relation to achieve that.
I created a UserProfile model that is liked (through a OneToOnefield) to the "true" profile, and using contrib.content-type and generic relation I'm able to use several distinct porfile types.
Note that should work for you if you don't fear to hit you database one more time on each get_profile().
An alternative would be to create a big table that contain all the field for all the profile type and using some kind of hook (or reimplementing a custom save()) to check the retired fields according the profile type. But it look complicated to me, especially if you want to have a lot of different profile type.
Another alternative could be to create a TextField derivated custom field and use it as a storage for a dictionary that you pickle to it on save and unpickle from it on load. With some hacking you could certainly map some of the model attribute to the dictionary key. That would allow a lot of flexibility.
Free hint for ya : I also use fixtures to test my application and forgot to check if the raw parameter of the post_save signal was True to prevent executing the UserProfile creation when using manage.py loaddata. As I had coded the creation of the "true" profile in my post_save callback the exception what kind of weird until I find out what was happening.
Usefull ressource :
defining a profile
generic relation