The preceding section discussed how to determine the current Site object inside a view function. Using the Site object, you can easily alter the view's behavior. You can also alter what data is displayed in the view if the model implements a ManyToManyField or ForeignKey field linked to the Site class.
For example, the Story model you created earlier includes the site field. You could use the following code in a view function to limit the Story objects to the current site:
from django.contrib.sites.models import Site from iFriends.News.models import Story def viewStories(request): currentSite = Site.objects.get_current() stories = Story.objects.filter(site=currentSite)
Django also provides the django.contrib.sites.managers.CurrentSiteManager class to provide a shortcut to limit content to the current class. The CurrentSiteManager class is a model manager that automatically filters queries to include only objects that are associated with the current Site.
You implement the CurrentSiteManager class by adding it to the on_site field of the model using the following syntax:
from django.contrib.sites.managers import CurrentSiteManager class Story(models.Model): . . . site = models.ForiegnKey(Site) on_site = CurrentSiteManager()
If you still want to be able to perform queries that are not filtered on the site first, add your own objects model manager:
from django.contrib.sites.managers import CurrentSiteManager class Story(models.Model): . . . site = models.ForiegnKey(Site) objects = models.Manager() on_site = CurrentSiteManager()
By the Way
The CurrentSiteManager class looks for a ManyToManyField or ForeignKey field called site. If you name the field that relates to the Site object something different, pass the name of the field into the CurrentSiteManager() function:
pubSite = models.ForiegnKey(Site) on_site = CurrentSiteManager('pubSite')
Try It Yourself: Modify a View's Behavior and Content Based on the SiteIn this section, you will add a CurrentSiteManager to the Story and Announcement models you created earlier in this hour. You will also modify the home_view() view function to render two different templates with different data depending on what the current site is. Follow these steps to make the changes:
Listing 22.3. The Announcement and Story Class Definitions in the iFriends/News/models.py File
Listing 22.4. The Additional Imports and the home_view() View Function in the iFriends/News/models.py File
Listing 22.5. The Table Cell Code for Announcements That Replaces the Largest Blog Table Cell in the iFriends/templates/Home/homepage.html File
Listing 22.6. Full Contents of the iFriends/templates/Home/newshomepage.html File
|