Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add crispy forms example #372

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 12 additions & 6 deletions django_unicorn/components/unicorn_view.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@

from .. import serializer
from ..decorators import timed
from ..errors import ComponentLoadError, UnicornCacheError
from ..errors import ComponentLoadError, MissingFormError, UnicornCacheError
from ..settings import get_setting
from ..utils import get_cacheable_component, is_non_string_sequence
from .fields import UnicornField
Expand Down Expand Up @@ -140,9 +140,6 @@ def construct_component(
return component


from django.utils.decorators import classonlymethod


class UnicornView(TemplateView):
response_class = UnicornTemplateResponse
component_name: str = ""
Expand Down Expand Up @@ -391,8 +388,6 @@ def get_frontend_context_variables(self) -> str:
form = self._get_form(attributes)

if form:
form.is_valid()

for key in attributes.keys():
if key in form.fields:
field = form.fields[key]
Expand Down Expand Up @@ -434,6 +429,16 @@ def _get_form(self, data):
except Exception as e:
logger.exception(e)

def get_form(self, **kwargs):
if hasattr(self, "form_class"):
# TODO: what to do with kwargs and attributes?
if kwargs:
return self._get_form(**kwargs)
else:
return self._get_form(self._attributes())

raise MissingFormError(f"{self.component_name} is missing a `form_class` field")

@timed
def get_context_data(self, **kwargs):
"""
Expand Down Expand Up @@ -671,6 +676,7 @@ def _is_public(self, name: str) -> bool:
"call",
"calls",
"component_cache_key",
"get_form",
)
excludes = []

Expand Down
4 changes: 4 additions & 0 deletions django_unicorn/errors.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,3 +24,7 @@ class MissingComponentViewElement(Exception):

class ComponentNotValid(Exception):
pass


class MissingFormError(Exception):
pass
2 changes: 2 additions & 0 deletions example/project/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@
"django.contrib.sessions",
"django.contrib.messages",
"django.contrib.staticfiles",
# Include `django-crispy-forms` for testing
"crispy_forms",
# Internal apps
"books",
"coffee",
Expand Down
76 changes: 76 additions & 0 deletions example/unicorn/components/crispy.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
from django import forms

from crispy_forms.helper import FormHelper
from crispy_forms.layout import Submit

from django_unicorn.components import UnicornView


class ExampleForm(forms.Form):
like_website = forms.TypedChoiceField(
label="Do you like this website?",
choices=((1, "Yes"), (0, "No")),
coerce=lambda x: bool(int(x)),
widget=forms.RadioSelect,
initial="1",
required=True,
)

favorite_food = forms.CharField(
label="What is your favorite food?",
max_length=80,
required=True,
)

favorite_color = forms.CharField(
label="What is your favorite color?",
max_length=80,
required=True,
)

favorite_number = forms.IntegerField(
label="Favorite number",
required=False,
)

notes = forms.CharField(
label="Additional notes or feedback",
required=False,
)

def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.helper = FormHelper()
self.helper.form_id = "id-exampleForm"
self.helper.form_class = "blueForms"
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

you can remove this line from the unicorn crispy example as well - this is just a CSS that is added, from the crispy example.

self.helper.form_method = "post"
self.helper.form_action = "submit_survey"

self.helper.add_input(Submit("submit", "Submit"))


class UnicornFormMixin:
# form_class: forms.Form = None

class Meta:
javascript_exclude = ("form",)

def __init__(self, **kwargs):
# print("l", self.form)
# print("m", self.get_form())

self.form = self.get_form()

for field_name, field in self.form.fields.items():
# set the classes Unicorn attrs dynamically
setattr(self.__class__, field_name, "")
field.widget.attrs["unicorn:model.lazy"] = field_name

super().__init__(**kwargs)


class CrispyView(UnicornFormMixin, UnicornView):
like_website = False
favorite_food = "Blueberries"

form_class = ExampleForm
2 changes: 0 additions & 2 deletions example/unicorn/components/direct_view.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
from django.utils.timezone import now

from django_unicorn.components import UnicornView


Expand Down
12 changes: 12 additions & 0 deletions example/unicorn/templates/unicorn/crispy-direct-view.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
{% extends "www/base.html" %}
{% load crispy_forms_tags unicorn %}

{% block content %}

<div unicorn:view>
<h2>Crispy</h2>

{% crispy view.form_class %}
</div>

{% endblock content %}
12 changes: 12 additions & 0 deletions example/unicorn/templates/unicorn/crispy.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
{% extends "www/base.html" %}
{% load crispy_forms_tags unicorn %}

{% block content %}

<div unicorn:view>
<h2>Crispy</h2>

{% crispy view.form_class view.form_class.helper %}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

the view.form_class.helper can be omitted (if FormHelper attr is called helper, as you did)

</div>

{% endblock content %}
2 changes: 2 additions & 0 deletions example/www/templates/www/base.html
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,8 @@ <h1>django-unicorn</h1>
<li><a href="{% url 'www:template' 'nested' %}">Nested components (table)</a></li>
<li><a href="{% url 'www:template' 'js' %}">JavaScript integration</a></li>
<li><a href="{% url 'www:direct-view' %}">Direct View</a></li>
<li><a href="{% url 'www:template' 'crispy' %}">Crispy form</a></li>
<li><a href="{% url 'www:crispy' %}">Crispy form (direct view)</a></li>
</ul>

{% block content %}{% endblock content %}
Expand Down
8 changes: 8 additions & 0 deletions example/www/templates/www/crispy.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{% extends "www/base.html" %}
{% load unicorn %}

{% block content %}

{% unicorn 'crispy' %}

{% endblock content %}
6 changes: 6 additions & 0 deletions example/www/urls.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from django.urls import path

from example.unicorn.components.crispy import CrispyView
from example.unicorn.components.direct_view import DirectViewView

from . import views
Expand All @@ -14,5 +15,10 @@
DirectViewView.as_view(),
name="direct-view",
),
path(
"crispy-direct-view",
CrispyView.as_view(template_name="unicorn/crispy-direct-view.html"),
name="crispy",
),
path("<str:name>", views.template, name="template"),
]
Loading