I'm a newbie at Django and I want to do something that I'm not sure how to do.
I have a model SimplePage, which simply stands for a webpage that is visible on the website and whose contents can be edited in the admin. (I think this is similar to FlatPage.)
So I have a bunch of SimplePages for my site, and I want one of them to be the main page. (a.k.a. the index page.) I know how to make it available on the url /
. But I also want i开发者_运维技巧t to receive slightly different processing. (It contains different page elements than the other pages.)
What would be a good way to mark a page as the main page? I considered adding a boolean field is_main_page
to the SimplePage model, but how could I assure that only one page could be marked as the main page?
Create MAIN_PAGE setting inside settings.py with primary key. Then create view main_page nad retrieve the main_page object from the database using the setting.
EDIT:
You can also do it like this: add a model, which will reference a SimplePage and point to the main page. In main page view, you will retrieve the wanted SimplePage and it can be easily changed by anyone in django admin.
Easiest way to do this would be to create the boolean value, as you suggested and use the pre_save
signal to remove the boolean value from everything else in the database.
from django.db.models import signals
def simple_page_pre_save(sender, instance, **kwargs):
if instance.is_main_page == True:
SimplePage.objects.update(is_main_page=False)
signals.pre_save.connect(simple_page_pre_save, sender=SimplePage)
This way whenever you save a SimplePage
, it will see if is_main_page
is true, and if it is set is_main_page
for every other page to False
. There is still some work to be done to ensure that there is always one is_main_page
, but that is more up to you.
精彩评论