forms.py
79 lines
| 2.8 KiB
| text/x-python
|
PythonLexer
r348 | import os | ||
import json | |||
from django import forms | |||
from django.utils.safestring import mark_safe | |||
from apps.main.models import Device | |||
from apps.main.forms import add_empty_choice | |||
from .models import GeneratorConfiguration | |||
def create_choices_from_model(model, conf_id, all_choice=False): | |||
instance = globals()[model] | |||
choices = instance.objects.all().values_list('pk', 'name') | |||
return choices | |||
class GeneratorConfigurationForm(forms.ModelForm): | |||
def __init__(self, *args, **kwargs): | |||
super(GeneratorConfigurationForm, self).__init__(*args, **kwargs) | |||
instance = getattr(self, 'instance', None) | |||
if instance and instance.pk: | |||
devices = Device.objects.filter(device_type__name='generator') | |||
r360 | #if instance.experiment: | ||
#self.fields['experiment'].widget.attrs['read_only'] = True | |||
r348 | #self.fields['experiment'].widget.choices = [(instance.experiment.id, instance.experiment)] | ||
r360 | #self.fields['device'].widget.choices = [(device.id, device) for device in devices] | ||
r348 | |||
if 'initial' in kwargs and 'experiment' in kwargs['initial'] and kwargs['initial']['experiment'] not in (0, '0'): | |||
self.fields['experiment'].widget.attrs['readonly'] = True | |||
class Meta: | |||
model = GeneratorConfiguration | |||
exclude = ('type', 'parameters', 'status', 'total_units', 'author', 'hash') | |||
def clean(self): | |||
form_data = super(GeneratorConfigurationForm, self).clean() | |||
return form_data | |||
def save(self, *args, **kwargs): | |||
conf = super(GeneratorConfigurationForm, self).save(*args, **kwargs) | |||
conf.save() | |||
return conf | |||
class ExtFileField(forms.FileField): | |||
""" | |||
Same as forms.FileField, but you can specify a file extension whitelist. | |||
>>> from django.core.files.uploadedfile import SimpleUploadedFile | |||
>>> | |||
>>> t = ExtFileField(ext_whitelist=(".pdf", ".txt")) | |||
>>> | |||
>>> t.clean(SimpleUploadedFile('filename.pdf', 'Some File Content')) | |||
>>> t.clean(SimpleUploadedFile('filename.txt', 'Some File Content')) | |||
>>> | |||
>>> t.clean(SimpleUploadedFile('filename.exe', 'Some File Content')) | |||
Traceback (most recent call last): | |||
... | |||
ValidationError: [u'Not allowed filetype!'] | |||
""" | |||
def __init__(self, *args, **kwargs): | |||
extensions = kwargs.pop("extensions") | |||
self.extensions = [i.lower() for i in extensions] | |||
super(ExtFileField, self).__init__(*args, **kwargs) | |||
def clean(self, *args, **kwargs): | |||
data = super(ExtFileField, self).clean(*args, **kwargs) | |||
filename = data.name | |||
ext = os.path.splitext(filename)[1] | |||
ext = ext.lower() | |||
if ext not in self.extensions: | |||
raise forms.ValidationError('Not allowed file type: %s' % ext) | |||
class GeneratorImportForm(forms.Form): | |||
file_name = ExtFileField(extensions=['.racp', '.json', '.dat']) |