class UserForm(forms.ModelForm): affiliation = forms.ModelChoiceField(queryset=Affiliation.objects.all()) role = forms.ModelChoiceField(queryset=Role.objects.all()) language = forms.ModelChoiceField(queryset=Language.objects.all()) theme = forms.ChoiceField(choices=[(t, t) for t in THEMES]) def __init__(self, request, editing=True, *args, **kwargs): super(UserForm, self).__init__(*args, **kwargs) if not request.user.is_anonymous(): uprofile = request.user.userprofile # Only show roles lesser or equal to the current role of the user self.fields['role'].queryset = Role.objects.filter( projectlevel=False, id__lte=uprofile.role.id) # Set initial values for this user self.fields[ 'role'].initial = uprofile.role if not editing else kwargs[ 'instance'].userprofile.role self.fields['affiliation'].initial = uprofile.affiliation self.fields['language'].initial = uprofile.language self.fields['theme'].initial = uprofile.theme # We don't use Django groups and permissions for fi in ("groups", "user_permissions"): if fi in self.fields: del self.fields[fi] if editing: del self.fields["username"] def save(self, commit=True): u = super(UserForm, self).save(commit) up = u.userprofile up.affiliation = self.cleaned_data['affiliation'] up.role = self.cleaned_data['role'] up.language = self.cleaned_data['language'] up.theme = self.cleaned_data['theme'] up.save() return u class Meta: model = User fields = ("affiliation", "role", "language", "theme")
class AddProjectForm(ProjectForm): owner = forms.ChoiceField(widget=widgets.JQuerySelect) def __init__(self, owner=None, *args, **kwargs): super(AddProjectForm, self).__init__(*args, **kwargs) self.fields['owner'].initial = owner.id if owner else None
class UploadScriptForm(forms.Form): file = forms.FileField(help_text="Supported archives: zip") encoding = forms.ChoiceField(choices=((1, "ISO-8859-15"), (2, "UTF-8"), (3, "LATIN-1")), initial=1, help_text="Try to change this value when character"+ " issues arise.") exi_set = forms.ModelChoiceField(queryset=ArticleSet.objects.all(), label="Existing set", required=False) new_set = forms.CharField(max_length=100, required=False) script = forms.ChoiceField(choices=[(sc, sc) for sc in article_upload.__all__]) def __init__(self, project, *args, **kwargs): super(UploadScriptForm, self).__init__(*args, **kwargs) exi = self.fields['exi_set'] exi.queryset = exi.queryset.filter(project=project) self.project = project def _get_zip_files(self, fo): zip = zipfile.ZipFile(fo) for fi in zip.infolist(): if fi.filename.split('.')[-1].lower in ALLOWED_EXTENSIONS: yield fi.filename, zip.read(fi) else: logger.debug("%s not in ALLOWED_EXTENSIONS, skipping.." % fi.filename) def clean_new_set(self): if not (self.cleaned_data['new_set'] or self.cleaned_data['exi_set']): raise forms.ValidationError("Either choose an existing set from the list above or\ fill in this field to create a new set.") new_set = ArticleSet.objects.filter(project=self.project, name=self.cleaned_data['new_set']) if len(new_set) != 0: raise forms.ValidationError("Set already exists!") return self.cleaned_data['new_set'] def clean_file(self): data = self.cleaned_data['file'] ext = unicode(data).split('.')[-1] if ext.lower() not in ALLOWED_EXTENSIONS + ['zip']: raise forms.ValidationError("%s is not a supported format" % ext) # Extract all txt-files from archive if ext.lower() == 'zip': try: return list(self._get_zip_files(data)) except zipfile.BadZipfile: raise forms.ValidationError("%s is not a zipfile" % data) # Read txt file elif ext.lower() in ALLOWED_EXTENSIONS: return [(unicode(data), data.read())] def clean_encoding(self): ident = self.cleaned_data['encoding'] enc = dict(self.fields['encoding'].choices).get(int(ident)) if 'file' not in self.cleaned_data: # Fail silently, as 'file' will fail anyway return enc # Test encoding for fn, bytes in self.cleaned_data['file']: try: bytes.decode(enc) except UnicodeDecodeError: raise ValidationError("Couldn't decode '%s' with '%s'" % (fn, enc)) return enc