Muestra las diferencias entre dos versiones de la página.
| Próxima revisión | Revisión previa | ||
|
wiki2:python:django:sites [2020/04/22 08:48] alfred creado |
wiki2:python:django:sites [2020/05/09 09:25] (actual) |
||
|---|---|---|---|
| Línea 46: | Línea 46: | ||
| + | If you don’t have access to the request object, you can use the ''get_current()'' method of the Site model’s manager. You should then ensure that your settings file does contain the ''SITE_ID'' setting. | ||
| + | |||
| + | <code python> | ||
| + | from django.contrib.sites.models import Site | ||
| + | |||
| + | def my_function_without_request(): | ||
| + | current_site = Site.objects.get_current() | ||
| + | if current_site.domain == 'foo.com': | ||
| + | # Do something | ||
| + | pass | ||
| + | else: | ||
| + | # Do something else. | ||
| + | pass | ||
| + | </code> | ||
| + | |||
| + | ==== The middleware ==== | ||
| + | To add the ''site'' attribute to the ''request'' for a view just add ''django.contrib.sites.middleware.CurrentSiteMiddleware'' to ''MIDDLEWARE''. | ||
| ==== The full url ==== | ==== The full url ==== | ||
| <code python> | <code python> | ||
| Línea 88: | Línea 105: | ||
| If you wanted to choose different templates refer to [[https://docs.djangoproject.com/en/3.0/ref/contrib/sites/#getting-the-current-domain-for-display|this link]]. | If you wanted to choose different templates refer to [[https://docs.djangoproject.com/en/3.0/ref/contrib/sites/#getting-the-current-domain-for-display|this link]]. | ||
| - | + | ==== Querying depending on the site ==== | |
| - | If you don’t have access to the request object, you can use the ''get_current()'' method of the Site model’s manager. You should then ensure that your settings file does contain the ''SITE_ID'' setting. | + | <code python> |
| - | + | ||
| - | <code> | + | |
| from django.contrib.sites.models import Site | from django.contrib.sites.models import Site | ||
| + | from django.contrib.sites.managers import CurrentSiteManager | ||
| + | from django.db import models | ||
| - | def my_function_without_request(): | + | class Photo(models.Model): |
| - | current_site = Site.objects.get_current() | + | photo = models.FileField(upload_to='photos') |
| - | if current_site.domain == 'foo.com': | + | photographer_name = models.CharField(max_length=100) |
| - | # Do something | + | pub_date = models.DateField() |
| - | pass | + | site = models.ForeignKey(Site, on_delete=models.CASCADE) |
| - | else: | + | objects = models.Manager() |
| - | # Do something else. | + | on_site = CurrentSiteManager() |
| - | pass | + | |
| </code> | </code> | ||
| + | |||
| + | Having this we can: | ||
| + | * Query all Photo objects in the database with ''Photo.objects.all()''. | ||
| + | * Query only the Photo objects associated with the current site (according to the ''SITE_ID''): ''Photo.on_site.all()'' | ||