Skip to content

Instantly share code, notes, and snippets.

@JackAtOmenApps
Created April 24, 2021 18:38
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save JackAtOmenApps/b76638287286a475a36404e919658ce1 to your computer and use it in GitHub Desktop.
Django and HTMX Preferences Example
from django.db import models
from django.contrib.auth.models import AbstractBaseUser
from django.utils.translation import ugettext_lazy as _
class MyUser(AbstractBaseUser):
receive_email_messages = models.BooleanField(
_("Receive Email Messages"),
default=False,
help_text="",
)
receive_sms_messages = models.BooleanField(
_("Receive SMS Messages"),
default=False,
help_text="",
)
class NotificationChoices(models.TextChoices):
NONE = "NONE", _("None")
IMMEDIATE = "IMMEDIATE", _("Immediately")
DAILY = "DAILY", _("Daily Archive")
WEEKLY = "WEEKLY", _("Weekly Archive")
order_notification_freq = models.CharField(
max_length=9,
choices=NotificationChoices.choices,
default=NotificationChoices.NONE,
help_text=_(
"How often do you want to receive notifications about your orders?"
),
)
<!doctype html>
<html lang="en">
<head>
<title>User Preferences</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
</head>
<body>
<script src="https://unpkg.com/htmx.org@1.3.3"></script>
<script src="https://unpkg.com/hyperscript.org@0.0.9"></script>
<h3>User Preferences</h3>
<div class="row m-5">
<div class="custom-control custom-switch col-lg-3 mt-3 mb-1">
<form method="POST">
<input type="checkbox" class="form-check-input" {% if request.user.receive_email_messages == True %}checked{% endif %} name="set_value" id="set_email_value" hx-post="{% url "users:toggle_preference" %}" hx-trigger="click" hx-target="#email_response">
<label class="form-check-label" for="set_email_value">Receive Email Messages</label>
<input type="hidden" name="preference" value="email_msg">
{% csrf_token %}
</form>
<div id="email_response"></div>
</div>
<div class="custom-control custom-switch col-lg-3 mt-3 mb-2">
<form method="POST">
<input type="checkbox" class="form-check-input" {% if request.user.receive_sms_messages == True %}checked{% endif %} name="set_value" id="set_sms_value" hx-post="{% url "users:toggle_preference" %}" hx-trigger="click" hx-target="#sms_response">
<label class="form-check-label" for="set_sms_value">Receive SMS Messages</label>
<input type="hidden" name="preference" value="sms_msg">
{% csrf_token %}
</form>
<div id="sms_response"></div>
</div>
<div class="col-lg-6 mb-1">
<form method="POST">
<label class="form-label" for="order_notify">Order Notification Frequency</label>
<select class="form-control" name="order_notify" id="order_notify" hx-post="{% url "users:select_order_notification_freq" %}" hx-trigger="change" hx-target="#notification_response">
<option value="NONE" {% if user.order_notification_freq == "NONE" %}selected{% endif %}>None</option>
<option value="IMMEDIATE" {% if user.order_notification_freq == "IMMEDIATE" %}selected{% endif %}>Immediate</option>
<option value="DAILY" {% if user.order_notification_freq == "DAILY" %}selected{% endif %}>Daily</option>
<option value="WEEKLY" {% if user.order_notification_freq == "WEEKLY" %}selected{% endif %}>Weekly</option>
</select>
{% csrf_token %}
</form>
<div id="notification_response"></div>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script>
</body>
</html>
import logging
from django.urls import path
from users import views
app_name = "users"
urlpatterns = [
path("preferences/", views.preferences, name="preferences"),
path("preferences/toggle_preference/", views.toggle_preference, name="toggle_preference"),
path("preferences/select_order_notification_freq/", views.select_order_notification_freq, name="select_order_notification_freq"),
]
from django.contrib.auth import get_user_model
from django.contrib.auth.decorators import login_required
from django.http import HttpResponse
from django.shortcuts import render
User = get_user_model()
@login_required
def preferences(request):
return render(request, "users/preferences.html")
@login_required
def toggle_preference(request):
if request.method == "POST":
user = request.user
successful_toggle = False
# Set/un-set email messaging preference
if (request.POST.get("preference", None) == "email_msg"):
if request.POST.get("set_value", None) is not None:
user.receive_email_messages = True
user.save()
successful_toggle = True
else:
user.receive_email_messages = False
user.save()
successful_toggle = True
# Set/un-set sms messaging preference
if (request.POST.get("preference", None) == "sms_msg"):
if request.POST.get("set_value", None) is not None:
user.receive_sms_messages = True
user.save()
successful_toggle = True
else:
user.receive_sms_messages = False
user.save()
successful_toggle = True
if successful_toggle:
return HttpResponse(
(
'<div _="on load wait 2s then remove me" class="alert alert-success alert-dismissible fade show" role="alert">'
"<strong>Success!</strong> Your preferences were updated."
"</div>"
),
status=200,
content_type="text/html",
)
# If we did not successfully toggle one of the preferences, notify the user of the failure
return HttpResponse(
(
'<div _="on load wait 2s then remove me" class="alert alert-warning alert-dismissible fade show" role="alert">'
"<strong>Warning!</strong> Preferences were not updated. Notify the webmaster."
"</div>"
),
status=200,
content_type="text/html",
)
@login_required
def select_order_notification_freq(request):
if request.method == "POST":
user = request.user
order_notify = request.POST.get("order_notify", None)
if order_notify is not None:
if order_notify in User.NotificationChoices.values:
user.order_notification_freq = order_notify
user.save()
else:
return HttpResponse(
(
'<div _="on load wait 2s then remove me" class="alert alert-warning" role="alert">'
"<strong>Warning!</strong> Preferences were not updated. Notify the webmaster."
"</div>"
),
status=200,
content_type="text/html",
)
else:
user.order_notification_freq = User.NotificationChoices.NONE
user.save()
return HttpResponse(
(
'<div _="on load wait 2s then remove me" class="alert alert-success" role="alert">'
"<strong>Success!</strong> Preferences were updated."
"</div>"
),
status=200,
content_type="text/html",
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment