From a9ab625a3d6c016a3b68bb5a5ecd762d993dfc8d Mon Sep 17 00:00:00 2001 From: Andros Fenollosa Date: Tue, 5 Mar 2024 09:42:05 +0100 Subject: [PATCH] Update --- one.org | 44 ++++++++++++++++++++++++++++++++++++++++++++ onerc.el | 2 ++ 2 files changed, 46 insertions(+) diff --git a/one.org b/one.org index de57304..c9fbf5a 100644 --- a/one.org +++ b/one.org @@ -339,6 +339,50 @@ And open the browser at ~http://localhost:8000/~. You should see the home page w #+ATTR_HTML: :class block-center [[#/img/quickstart/minimal-template.webp][Random number]] +* Views +:PROPERTIES: +:ONE: one-custom-default-doc +:CUSTOM_ID: /docs/views/ +:TITLE: Views +:DESCRIPTION: Views of Django LiveView. +:END: + +Django LiveView uses the same views as Django, but the main difference is that the views are asynchronous by default. + +To make a view renderable by SSR (Server Side Rendering) and by SPA (Single Page Application), you need to create a function with the following structure: + +#+BEGIN_SRC python + from .actions.home import get_context as get_home_context + + async def home(request): + return render(request, settings.TEMPLATE_BASE, await get_home_context()) +#+END_SRC + +The ~get_home_context()~ function returns a dictionary with the context of the page present in the action. The ~settings.TEMPLATE_BASE~ is the base template that will be rendered, por example ~layouts/base.html~. + +If you want to render data from a database on the template, for example: + +#+BEGIN_SRC html +{% for article in articles %} + {{ article.title }} + {{ article.content }} +{% endfor %} +#+END_SRC + +You will see an error: ~You cannot call this from an async context - use a thread or sync_to_async.~. + +You can use the ~sync_to_async~ function from ~asgiref~. + +#+BEGIN_SRC python + from asgiref.sync import sync_to_async + from .actions.blog_list import get_context as get_list_context + + async def blog_list(request): + return await sync_to_async(render)(request, settings.TEMPLATE_BASE, await get_list_context()) +#+END_SRC + +Or transform ~articles~ to a list. But you lose the benefits of ORM. + * Deploy :PROPERTIES: :ONE: one-custom-default-doc diff --git a/onerc.el b/onerc.el index f84cd41..79328b9 100644 --- a/onerc.el +++ b/onerc.el @@ -105,6 +105,8 @@ (:ul.nav__list.nav__list--docs.nav-docs__list (:li.nav-docs__item (:a.nav-docs__link (@ :href "/docs/quickstart/") "Quickstart")) + (:li.nav-docs__item + (:a.nav-docs__link (@ :href "/docs/views/") "Views")) (:li.nav-docs__item (:a.nav-docs__link (@ :href "/docs/deploy/") "Deploy")) (:li.nav-docs__item