django-components/docs/concepts/fundamentals/component_views_urls.md
Juro Oravec 485027b308
Some checks are pending
Docs - build & deploy / docs (push) Waiting to run
Run tests / build (windows-latest, 3.10) (push) Waiting to run
Run tests / build (ubuntu-latest, 3.10) (push) Waiting to run
Run tests / build (ubuntu-latest, 3.11) (push) Waiting to run
Run tests / build (ubuntu-latest, 3.12) (push) Waiting to run
Run tests / build (ubuntu-latest, 3.13) (push) Waiting to run
Run tests / build (ubuntu-latest, 3.8) (push) Waiting to run
Run tests / build (ubuntu-latest, 3.9) (push) Waiting to run
Run tests / build (windows-latest, 3.11) (push) Waiting to run
Run tests / build (windows-latest, 3.12) (push) Waiting to run
Run tests / build (windows-latest, 3.13) (push) Waiting to run
Run tests / build (windows-latest, 3.8) (push) Waiting to run
Run tests / build (windows-latest, 3.9) (push) Waiting to run
Run tests / test_docs (3.13) (push) Waiting to run
Run tests / test_sampleproject (3.13) (push) Waiting to run
refactor: make Component.View.public optional (#1451)
Co-authored-by: RohanDisa <105740583+RohanDisa@users.noreply.github.com>
2025-10-12 20:33:14 +02:00

6.4 KiB

New in version 0.34

Note: Since 0.92, Component is no longer a subclass of Django's View. Instead, the nested Component.View class is a subclass of Django's View.


For web applications, it's common to define endpoints that serve HTML content (AKA views).

django-components has a suite of features that help you write and manage views and their URLs:

  • For each component, you can define methods for handling HTTP requests (GET, POST, etc.) - get(), post(), etc.

  • Use Component.as_view() to be able to use your Components with Django's urlpatterns. This works the same way as View.as_view().

  • Or use get_component_url() to retrieve the component URL - an anonymous HTTP endpoint that triggers the component's handlers without having to register the component in urlpatterns.

    To expose a component, simply define a handler, or explicitly expose/hide the component with Component.View.public = True/False.

  • In addition, Component has a render_to_response() method that renders the component template based on the provided input and returns an HttpResponse object.

Define handlers

Here's an example of a calendar component defined as a view. Simply define a View class with your custom get() method to handle GET requests:

from django_components import Component, ComponentView, register

@register("calendar")
class Calendar(Component):
    template = """
        <div class="calendar-component">
            <div class="header">
                {% slot "header" / %}
            </div>
            <div class="body">
                Today's date is <span>{{ date }}</span>
            </div>
        </div>
    """

    class View:
        # Handle GET requests
        def get(self, request, *args, **kwargs):
            # Return HttpResponse with the rendered content
            return Calendar.render_to_response(
                request=request,
                kwargs={
                    "date": request.GET.get("date", "2020-06-06"),
                },
                slots={
                    "header": "Calendar header",
                },
            )

!!! info

The View class supports all the same HTTP methods as Django's [`View`](https://docs.djangoproject.com/en/5.2/ref/class-based-views/base/#django.views.generic.base.View) class. These are:

`get()`, `post()`, `put()`, `patch()`, `delete()`, `head()`, `options()`, `trace()`

Each of these receive the [`HttpRequest`](https://docs.djangoproject.com/en/5.2/ref/request-response/#django.http.HttpRequest) object as the first argument.

!!! warning

**Deprecation warning:**

Previously, the handler methods such as `get()` and `post()` could be defined directly on the `Component` class:

```py
class Calendar(Component):
    def get(self, request, *args, **kwargs):
        return self.render_to_response(
            kwargs={
                "date": request.GET.get("date", "2020-06-06"),
            }
        )
```

This is deprecated from v0.137 onwards, and will be removed in v1.0.

Acccessing component class

You can access the component class from within the View methods by using the View.component_cls attribute:

class Calendar(Component):
    ...

    class View:
        def get(self, request):
            return self.component_cls.render_to_response(request=request)

Register URLs manually

To register the component as a route / endpoint in Django, add an entry to your urlpatterns. In place of the view function, create a view object with Component.as_view():

from django.urls import path
from components.calendar.calendar import Calendar

urlpatterns = [
    path("calendar/", Calendar.as_view()),
]

Component.as_view() internally calls View.as_view(), passing the component class as one of the arguments.

Register URLs automatically

If you don't care about the exact URL of the component, you can let django-components manage the URLs.

Each component has an "anonymous" URL that triggers the component's HTTP handlers without having to define the component in urlpatterns.

This way you don't have to mix your app URLs with component URLs.

To obtain such "anonymous" URL, use get_component_url():

from django_components import get_component_url

url = get_component_url(MyComponent)

The component is automatically registered in urlpatterns when you define a handler. You can also explicitly expose/hide the component with Component.View.public:

class MyComponent(Component):
    class View:
        public = False

        def get(self, request):
            return self.component_cls.render_to_response(request=request)
    ...

!!! info

If you need to pass query parameters or a fragment to the component URL, you can do so by passing the `query` and `fragment` arguments to [`get_component_url()`](../../../reference/api#django_components.get_component_url):

```py
url = get_component_url(
    MyComponent,
    query={"foo": "bar", "enabled": True, "debug": False, "unused": None},
    fragment="baz",
)
# /components/ext/view/components/c1ab2c3?foo=bar&enabled#baz
```

**Query parameter handling:**

- `True` values are rendered as flag parameters without values (e.g., `?enabled`)
- `False` and `None` values are omitted from the URL
- Other values are rendered normally (e.g., `?foo=bar`)