devicehub-django/device/forms.py

70 lines
2.2 KiB
Python
Raw Normal View History

2024-07-05 13:32:07 +00:00
from django import forms
from utils.device import create_annotation, create_doc, create_index
2024-10-15 14:58:51 +00:00
from utils.save_snapshots import move_json, save_in_disk
2024-11-27 05:05:57 +00:00
from django.utils.translation import gettext_lazy as _
#TODO: translate device types
2024-07-23 13:37:40 +00:00
DEVICE_TYPES = [
("Desktop", "Desktop"),
("Laptop", "Laptop"),
("Server", "Server"),
("GraphicCard", "GraphicCard"),
("HardDrive", "HardDrive"),
("SolidStateDrive", "SolidStateDrive"),
("Motherboard", "Motherboard"),
("NetworkAdapter", "NetworkAdapter"),
("Processor", "Processor"),
("RamModule", "RamModule"),
("SoundCard", "SoundCard"),
("Display", "Display"),
("Battery", "Battery"),
("Camera", "Camera"),
]
2024-07-19 15:40:01 +00:00
class DeviceForm(forms.Form):
2024-11-27 05:05:57 +00:00
type = forms.ChoiceField(choices = DEVICE_TYPES, required=False, label= _(u"Type"))
amount = forms.IntegerField(required=False, initial=1, label= _(u"Amount"))
custom_id = forms.CharField(required=False, label=_(u"Custom id"))
name = forms.CharField(required=False, label= _(u"Name"))
value = forms.CharField(required=False, label=_(u"Value"))
2024-07-23 13:37:40 +00:00
class BaseDeviceFormSet(forms.BaseFormSet):
2024-07-30 11:37:08 +00:00
def clean(self):
for x in self.cleaned_data:
if x.get("amount"):
return True
return False
2024-07-23 13:37:40 +00:00
def save(self, user, commit=True):
self.user = user
row = {}
2024-07-23 13:37:40 +00:00
for f in self.forms:
d = f.cleaned_data
if not d:
continue
2024-07-23 13:37:40 +00:00
if d.get("type"):
row["type"] = d["type"]
2024-07-23 13:37:40 +00:00
if d.get("amount"):
row["amount"] = d["amount"]
2024-07-23 13:37:40 +00:00
if d.get("name"):
row[d["name"]] = d.get("value", '')
2024-09-26 02:10:41 +00:00
if d.get("custom_id"):
row['CUSTOM_ID']= d["custom_id"]
2024-07-23 13:37:40 +00:00
doc = create_doc(row)
2024-07-23 13:37:40 +00:00
if not commit:
return doc
2024-10-15 14:58:51 +00:00
path_name = save_in_disk(doc, self.user.institution.name, place="placeholder")
create_index(doc, self.user)
create_annotation(doc, user, commit=commit)
move_json(path_name, self.user.institution.name, place="placeholder")
2024-10-15 14:58:51 +00:00
2024-07-23 13:37:40 +00:00
return doc
2024-07-19 15:40:01 +00:00
2024-07-23 13:37:40 +00:00
DeviceFormSet = forms.formset_factory(form=DeviceForm, formset=BaseDeviceFormSet, extra=1)
2024-07-19 15:40:01 +00:00