Herramientas de usuario

Herramientas del sitio


wiki2:python:medium_django

Diferencias

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

Enlace a la vista de comparación

Próxima revisión
Revisión previa
wiki2:python:medium_django [2018/07/28 07:21]
alfred creado
wiki2:python:medium_django [2020/05/09 09:25] (actual)
Línea 1: Línea 1:
-====== Django ​gotchas ​======+====== Django ​Gotchas ​======
  
 +===== Django hows =====
 +==== Cómo tener varios setting files ====
 +Símplemente has de definir una variable de entorno denominada ''​DJANGO_SETTINGS_MODULE''​ e indicar la ruta del módulo de settings deseado:
 +<​code>​
 +DJANGO_SETTINGS_MODULE = coopolis_backoffice.settings.alfred
 +</​code>​
 +
 +==== Loggear las peticiones a DB ====
 +En las settings:
 +<​code>​
 +LOGGING = {
 +    '​version':​ 1,
 +    '​disable_existing_loggers':​ False,
 +    '​handlers':​ {
 +        '​console':​ {
 +            '​class':​ '​logging.StreamHandler',​
 +        },
 +    },
 +    '​loggers':​ {
 +        '​django.db.backends':​ {
 +            '​handlers':​ ['​console'​],​
 +            '​level':​ '​DEBUG',​
 +        },
 +    },
 +}
 +
 +</​code>​
 +==== How Django manages Url's? ====
 +It only needs a module for url configs, which will be a simple mapping between URL patterns to python functions corresponding to views.
 +<code python>
 +from django.conf.urls import url
 +
 +from . import views
 +
 +urlpatterns = [
 +    url(r'​^articles/​2003/​$',​ views.special_case_2003),​
 +    url(r'​^articles/​([0-9]{4})/​$',​ views.year_archive),​
 +    url(r'​^articles/​([0-9]{4})/​([0-9]{2})/​$',​ views.month_archive),​
 +    url(r'​^articles/​([0-9]{4})/​([0-9]{2})/​([0-9]+)/​$',​ views.article_detail),​
 +]
 +</​code>​
 +To capture a value from the URL, just put parenthesis around it. Example requests: A request to ''/​articles/​2005/​03/''​ would match the third entry in the list. Django would call the function ''​views.month_archive(request,​ '​2005',​ '​03'​)''​. \\ 
 +''/​articles/​2005/​3/''​ would not match any URL patterns, because the third entry in the list requires two digits for the month. \\
 +''/​articles/​2003/''​ would match the first pattern in the list, not the second one, because the patterns are tested in order, and the first one is the first test to pass. \\ 
 +''/​articles/​2003''​ would not match any of these patterns, because each pattern requires that the URL end with a slash. ''/​articles/​2003/​03/​03/''​ would match the final pattern. Django would call the function ''​views.article_detail(request,​ '​2003',​ '​03',​ '​03'​)''​. \\ \\
 +
 +You can name the variables like this:
 +<code python>
 +urlpatterns = [
 +    url(r'​^articles/​2003/​$',​ views.special_case_2003),​
 +    url(r'​^articles/​(?​P<​year>​[0-9]{4})/​$',​ views.year_archive),​
 +    url(r'​^articles/​(?​P<​year>​[0-9]{4})/​(?​P<​month>​[0-9]{2})/​$',​ views.month_archive),​
 +    url(r'​^articles/​(?​P<​year>​[0-9]{4})/​(?​P<​month>​[0-9]{2})/​(?​P<​day>​[0-9]{2})/​$',​ views.article_detail),​
 +]
 +</​code>​
 +
 +The URLconf doesn’t look at the request method. In other words, all request methods – POST, GET, HEAD, etc. – will be routed to the same function for the same URL.
 +
 +You can specify default values:
 +<code python>
 +urlpatterns = [
 +    url(r'​^blog/​$',​ views.page),​
 +    url(r'​^blog/​page(?​P<​num>​[0-9]+)/​$',​ views.page),​
 +]
 +
 +def page(request,​ num="​1"​):​
 +    # Output the appropriate page of blog entries, according to num.
 +    ...
 +</​code>​
 +
 +At any point, your urlpatterns can “include” other URLconf modules. This essentially “roots” a set of URLs below other ones.
 +<code python>
 +urlpatterns = [
 +    # ... snip ...
 +    url(r'​^community/',​ include('​django_website.aggregator.urls'​)),​
 +    url(r'​^contact/',​ include('​django_website.contact.urls'​)),​
 +    # ... snip ...
 +]
 +</​code>​
 +Note that the regular expressions in this example don’t have a $ (end-of-string match character) but do include a trailing slash. Whenever Django encounters include() (django.conf.urls.include()),​ it chops off whatever part of the URL matched up to that point and sends the remaining string to the included URLconf for further processing.
 +<code python>
 +extra_patterns = [
 +    url(r'​^reports/​$',​ credit_views.report),​
 +    url(r'​^reports/​(?​P<​id>​[0-9]+)/​$',​ credit_views.report),​
 +    url(r'​^charge/​$',​ credit_views.charge),​
 +]
 +
 +urlpatterns = [
 +    url(r'​^$',​ main_views.homepage),​
 +    url(r'​^help/',​ include('​apps.help.urls'​)),​
 +    url(r'​^credit/',​ include(extra_patterns)),​
 +]
 +</​code>​
 +We can write some url patterns in several ways:
 +<code python>
 +urlpatterns = [
 +    url(r'​^(?​P<​page_slug>​[\w-]+)-(?​P<​page_id>​\w+)/​history/​$',​ views.history),​
 +    url(r'​^(?​P<​page_slug>​[\w-]+)-(?​P<​page_id>​\w+)/​edit/​$',​ views.edit),​
 +    url(r'​^(?​P<​page_slug>​[\w-]+)-(?​P<​page_id>​\w+)/​discuss/​$',​ views.discuss),​
 +    url(r'​^(?​P<​page_slug>​[\w-]+)-(?​P<​page_id>​\w+)/​permissions/​$',​ views.permissions),​
 +]
 +
 +urlpatterns = [
 +    url(r'​^(?​P<​page_slug>​[\w-]+)-(?​P<​page_id>​\w+)/',​ include([
 +        url(r'​^history/​$',​ views.history),​
 +        url(r'​^edit/​$',​ views.edit),​
 +        url(r'​^discuss/​$',​ views.discuss),​
 +        url(r'​^permissions/​$',​ views.permissions),​
 +    ])),
 +]
 +</​code>​
 +You can send extra options:
 +<code python>
 +urlpatterns = [
 +    url(r'​^blog/​(?​P<​year>​[0-9]{4})/​$',​ views.year_archive,​ {'​foo':​ '​bar'​}),​
 +]
 +</​code>​
 +In this example, for a request to ''/​blog/​2005/'',​ Django will call ''​views.year_archive(request,​ year='​2005',​ foo='​bar'​)''​.
 +You can send extra parameters:
 +<code python>
 +urlpatterns = [
 +    url(r'​^blog/',​ include('​inner'​)),​
 +]
 +
 +
 +urlpatterns = [
 +    url(r'​^archive/​$',​ views.archive,​ {'​blogid':​ 3}),
 +    url(r'​^about/​$',​ views.about,​ {'​blogid':​ 3}),
 +]
 +</​code>​
 +
 +=== URL namespaces ===
 +A URL namespace comes in two parts, both of which are strings:
 +  * Application namespace: This describes the name of the application that is being deployed. ​
 +  * Instance namespace: This identifies a specific instance of an application and should be unique across your entire project. ​
 +
 +
 +Namespaced URLs are specified using the ':'​ operator. For example, the main index page of the admin application is referenced using '​admin:​index'​. This indicates a namespace of '​admin',​ and a named URL of '​index'​. Namespaces can also be nested. The named URL '​sports:​polls:​index'​ would look for a pattern named '​index'​ in the namespace '​polls'​ that is itself defined within the top-level namespace '​sports'​.
 +
 +==== Dynamic fields ====
 +For example in urls:
 +<​code>​
 +urlpatterns = [
 +    path('',​ TemplateView.as_view(
 +        template_name="​fok/​home.html",​
 +        extra_context={
 +            # The lambda makes this expression to be executed each call of home (because of the admin updates)
 +            '​campaigns':​ lambda: Campaign.objects.filter(visible=True).order_by('​-created_at'​)
 +        }
 +    ), name='​home'​),​
 +...
 +</​code>​
 +
 +===== Questions =====
 +
 +[[https://​stackoverflow.com/​questions/​39904458/​should-my-django-sites-main-page-be-an-app|La página principal debería ser una app?]]
 +
 +[[https://​simpleisbetterthancomplex.com/​tutorial/​2017/​08/​01/​how-to-setup-amazon-s3-in-a-django-project.html|S3 in Django]]
 +
 +[[https://​simpleisbetterthancomplex.com/​tutorial/​2016/​07/​22/​how-to-extend-django-user-model.html|Formas de extender el modelo de usuario]]
wiki2/python/medium_django.1532762481.txt.gz · Última modificación: 2020/05/09 09:24 (editor externo)