from typing import NamedTuple from django.http import HttpRequest, HttpResponse from django_components import Component, get_component_url, register, types DESCRIPTION = "Handle the entire form submission flow in a single file and without Django's Form class." @register("thank_you_message") class ThankYouMessage(Component): class Kwargs(NamedTuple): name: str def get_template_data(self, args, kwargs: Kwargs, slots, context): return {"name": kwargs.name} template: types.django_html = """

Thank you for your submission, {{ name }}!

""" @register("contact_form") class ContactFormComponent(Component): def get_template_data(self, args, kwargs: NamedTuple, slots, context): # Send the form data to the HTTP handlers of this component submit_url = get_component_url(ContactFormComponent) return { "submit_url": submit_url, } template: types.django_html = """
{% csrf_token %}
""" # noqa: E501 class View: # Submit handler def post(self, request: HttpRequest, *args, **kwargs) -> HttpResponse: # Access the submitted data name = request.POST.get("name", "stranger") # Respond with the "thank you" message return ThankYouMessage.render_to_response(kwargs={"name": name})