Herramientas de usuario

Herramientas del sitio


wiki2:python:django:sites

Diferencias

Muestra las diferencias entre dos versiones de la página.

Enlace a la vista de comparación

Ambos lados, revisión anterior Revisión previa
Próxima revisión
Revisión previa
wiki2:python:django:sites [2020/04/22 08:49]
alfred [Beheaving depending on the site]
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 ====
 +<code python>
 +from django.contrib.sites.models import Site
 +from django.contrib.sites.managers import CurrentSiteManager
 +from django.db import models
 +
 +class Photo(models.Model):​
 +    photo = models.FileField(upload_to='​photos'​)
 +    photographer_name = models.CharField(max_length=100)
 +    pub_date = models.DateField()
 +    site = models.ForeignKey(Site,​ on_delete=models.CASCADE)
 +    objects = models.Manager()
 +    on_site = CurrentSiteManager()
 +</​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()''​
  
  
wiki2/python/django/sites.1587545356.txt.gz · Última modificación: 2020/05/09 09:24 (editor externo)