network_inventory/src/customers/forms.py

76 lines
2.1 KiB
Python
Raw Permalink Normal View History

2021-12-22 19:14:18 +01:00
from django import forms
2022-02-10 21:40:49 +01:00
from django.urls import reverse_lazy
from crispy_forms.helper import FormHelper
2022-03-05 15:13:27 +01:00
from crispy_forms.layout import Submit, Button
2022-02-10 21:40:49 +01:00
from crispy_forms.bootstrap import FormActions
2021-12-22 19:14:18 +01:00
2022-03-05 15:13:27 +01:00
from core import utils
2022-03-23 13:49:58 +01:00
from .models import Customer, DummyLocation, Location
2021-12-22 19:14:18 +01:00
class CustomerForm(forms.ModelForm):
class Meta:
model = Customer
2022-03-27 14:50:44 +02:00
fields = ("name", "description")
2022-02-10 21:40:49 +01:00
def __init__(self, *args, **kwargs):
super(CustomerForm, self).__init__(*args, **kwargs)
2022-02-11 08:38:51 +01:00
self.helper = FormHelper(self)
2022-02-10 21:40:49 +01:00
self.helper.attrs = {
2022-03-27 14:50:44 +02:00
"hx-post": reverse_lazy("customer_create"),
"id": "customer-form",
2022-02-10 21:40:49 +01:00
}
2022-02-11 08:38:51 +01:00
self.helper.layout.append(
2022-02-10 21:40:49 +01:00
FormActions(
2022-03-27 14:50:44 +02:00
Submit("save", "Save"),
Button(
"cancel",
"Cancel",
css_class="btn btn-secondary",
onclick="closeModal()",
),
)
)
2022-03-05 15:13:27 +01:00
class LocationForm(forms.ModelForm):
class Meta:
model = Location
2022-03-27 14:50:44 +02:00
fields = ("name", "customer")
2022-03-05 15:13:27 +01:00
2022-03-23 12:18:40 +01:00
def __init__(self, *args, **kwargs):
user = kwargs.pop("user")
2022-03-05 15:13:27 +01:00
super(LocationForm, self).__init__(*args, **kwargs)
"""
If the user is not a superuser it's always assigned to a customer which
we can use to assign to the field.
"""
2022-03-27 14:50:44 +02:00
self.fields["customer"].queryset = utils.objects_for_allowed_customers(
Customer, user=user
)
2022-03-05 15:13:27 +01:00
self.helper = FormHelper(self)
self.helper.attrs = {
2022-03-27 14:50:44 +02:00
"hx-post": reverse_lazy("htmx_create_location"),
"id": "location-form",
2022-03-05 15:13:27 +01:00
}
self.helper.layout.append(
FormActions(
2022-03-27 14:50:44 +02:00
Submit("save_location", "Save"),
Button(
"cancel",
"Cancel",
css_class="btn btn-secondary",
onclick="closeModal()",
),
)
)
2022-03-23 13:49:58 +01:00
class DummyLocationForm(forms.ModelForm):
class Meta:
model = DummyLocation
2022-03-27 14:50:44 +02:00
fields = ("location",)