Last active
March 12, 2024 15:52
-
-
Save danjac/1443fbd7b1e7abc1dff7ce9e3b83eb00 to your computer and use it in GitHub Desktop.
Django form using AlpineJS to render rating field
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{# | |
class ReviewForm(forms.ModelForm): | |
class Meta: | |
model = Review | |
fields = ( | |
"comment", | |
"score", | |
) | |
help_texts: ClassVar = { | |
"comment": "Review (max 500 chars)", | |
} | |
validators: ClassVar = { | |
"comment": MaxLengthValidator(500, "Max 500 characters") | |
} | |
widgets: ClassVar = {"score": forms.HiddenInput()} | |
#} | |
{% load heroicons widget_tweaks %} | |
<form post="{{ request.path }}" | |
hx-post="{{ request.path }}" | |
class="space-y-3" | |
x-data="{score: {{ form.score.value }}, scores: [1, 2, 3, 4, 5]}" | |
id="review-form"> | |
<label class="space-y-3 font-semibold">Score</label> | |
{# "score" Integer field rendered as hidden widget #} | |
{# x-model will set the value of the field automatically when changed #} | |
{{ form.score|append_attr:"x-model=score" }} | |
<div class="flex items-center"> | |
{# render 5 stars #} | |
<template x-for="value in scores"> | |
<div class="mr-3"> | |
<button :title="`Score: ${value}`" | |
x-show="value > score" | |
@click.prevent.debounce="score=value">{% heroicon_outline "star" %}</button> | |
<button :title="`Score: ${value}`" | |
x-show="value == score" | |
@click.prevent.debounce="score=value-1">{% heroicon_solid "star" %}</button> | |
<button :title="`Score: ${value}`" | |
x-show="value < score" | |
@click.prevent.debounce="score=value">{% heroicon_solid "star" %}</button> | |
</div> | |
</template> | |
</div> | |
{{ form.comment.as_field_group }} | |
<button class="flex items-center btn btn-primary"> | |
{% heroicon_mini "plus" class="mr-2" %} | |
Submit | |
</button> | |
</form> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment