Improvements on database form validation

This commit is contained in:
Marc Aymerich 2015-06-04 14:15:17 +00:00
parent 7d54299b28
commit b4670610ee
5 changed files with 24 additions and 28 deletions

View File

@ -193,6 +193,8 @@ class AccountAdminMixin(object):
if obj and not obj.account.is_active: if obj and not obj.account.is_active:
help_text += "<br><b style='color:red;'>This user's account is dissabled</b>" help_text += "<br><b style='color:red;'>This user's account is dissabled</b>"
field.help_text = _(help_text) field.help_text = _(help_text)
# Not available in POST
form.initial_account = self.get_changeform_initial_data(request).get('account')
return form return form
def get_fields(self, request, obj=None): def get_fields(self, request, obj=None):

View File

@ -1,5 +1,6 @@
from django import forms from django import forms
from django.contrib.auth.forms import ReadOnlyPasswordHashField from django.contrib.auth.forms import ReadOnlyPasswordHashField
from django.core.exceptions import ValidationError
from django.utils.html import format_html from django.utils.html import format_html
from django.utils.safestring import mark_safe from django.utils.safestring import mark_safe
from django.utils.translation import ugettext_lazy as _ from django.utils.translation import ugettext_lazy as _
@ -25,7 +26,7 @@ class DatabaseUserCreationForm(forms.ModelForm):
password2 = self.cleaned_data.get("password2") password2 = self.cleaned_data.get("password2")
if password1 and password2 and password1 != password2: if password1 and password2 and password1 != password2:
msg = _("The two password fields didn't match.") msg = _("The two password fields didn't match.")
raise forms.ValidationError(msg) raise ValidationError(msg)
return password2 return password2
@ -45,29 +46,34 @@ class DatabaseCreationForm(DatabaseUserCreationForm):
def __init__(self, *args, **kwargs): def __init__(self, *args, **kwargs):
super(DatabaseCreationForm, self).__init__(*args, **kwargs) super(DatabaseCreationForm, self).__init__(*args, **kwargs)
account_id = self.initial.get('account', None) account_id = self.initial.get('account', self.initial_account)
if account_id: if account_id:
qs = self.fields['user'].queryset.filter(account=account_id) qs = self.fields['user'].queryset.filter(account=account_id)
choices = [ (u.pk, "%s (%s)" % (u, u.get_type_display())) for u in qs ] choices = [ (u.pk, "%s (%s)" % (u, u.get_type_display())) for u in qs ]
self.fields['user'].queryset = qs self.fields['user'].queryset = qs
self.fields['user'].choices = [(None, '--------'),] + choices self.fields['user'].choices = [(None, '--------'),] + choices
def clean_username(self):
username = self.cleaned_data.get('username')
if DatabaseUser.objects.filter(username=username).exists():
raise ValidationError("Provided username already exists.")
def clean_password2(self): def clean_password2(self):
username = self.cleaned_data.get('username') username = self.cleaned_data.get('username')
password1 = self.cleaned_data.get('password1') password1 = self.cleaned_data.get('password1')
password2 = self.cleaned_data.get('password2') password2 = self.cleaned_data.get('password2')
if username and not (password1 and password2): if username and not (password1 and password2):
raise forms.ValidationError(_("Missing password")) raise ValidationError(_("Missing password"))
if password1 and password2 and password1 != password2: if password1 and password2 and password1 != password2:
msg = _("The two password fields didn't match.") msg = _("The two password fields didn't match.")
raise forms.ValidationError(msg) raise ValidationError(msg)
return password2 return password2
def clean_user(self): def clean_user(self):
user = self.cleaned_data.get('user') user = self.cleaned_data.get('user')
if user and user.type != self.cleaned_data.get('type'): if user and user.type != self.cleaned_data.get('type'):
msg = _("Database type and user type doesn't match") msg = _("Database type and user type doesn't match")
raise forms.ValidationError(msg) raise ValidationError(msg)
return user return user
def clean(self): def clean(self):
@ -75,9 +81,9 @@ class DatabaseCreationForm(DatabaseUserCreationForm):
if 'user' in cleaned_data and 'username' in cleaned_data: if 'user' in cleaned_data and 'username' in cleaned_data:
msg = _("Use existing user or create a new one?") msg = _("Use existing user or create a new one?")
if cleaned_data['user'] and self.cleaned_data['username']: if cleaned_data['user'] and self.cleaned_data['username']:
raise forms.ValidationError(msg) raise ValidationError(msg)
elif not (cleaned_data['username'] or cleaned_data['user']): elif not (cleaned_data['username'] or cleaned_data['user']):
raise forms.ValidationError(msg) raise ValidationError(msg)
return cleaned_data return cleaned_data

View File

@ -94,8 +94,8 @@ class MiscellaneousAdmin(AccountAdminMixin, SelectPluginAdminMixin, admin.ModelA
def clean_identifier(self, service=service): def clean_identifier(self, service=service):
identifier = self.cleaned_data['identifier'] identifier = self.cleaned_data['identifier']
validator_path = settings.MISCELLANEOUS_IDENTIFIER_VALIDATORS.get(service.name, None) validator_path = settings.MISCELLANEOUS_IDENTIFIER_VALIDATORS.get(service.name, None)
if validator_path:
validator = import_class(validator_path) validator = import_class(validator_path)
if validator:
validator(identifier) validator(identifier)
return identifier return identifier
@ -117,5 +117,6 @@ class MiscellaneousAdmin(AccountAdminMixin, SelectPluginAdminMixin, admin.ModelA
setattr(obj, self.plugin_field, plugin.model.objects.get(**kwargs)) setattr(obj, self.plugin_field, plugin.model.objects.get(**kwargs))
obj.save() obj.save()
admin.site.register(MiscService, MiscServiceAdmin) admin.site.register(MiscService, MiscServiceAdmin)
admin.site.register(Miscellaneous, MiscellaneousAdmin) admin.site.register(Miscellaneous, MiscellaneousAdmin)

View File

@ -8,6 +8,7 @@ from orchestra.admin.utils import admin_link, admin_date, admin_colored, display
from . import settings, helpers from . import settings, helpers
from .backends import ServiceBackend from .backends import ServiceBackend
from .forms import RouteForm
from .models import Server, Route, BackendLog, BackendOperation from .models import Server, Route, BackendLog, BackendOperation
from .widgets import RouteBackendSelect from .widgets import RouteBackendSelect
@ -24,19 +25,6 @@ STATE_COLORS = {
} }
from django import forms
from orchestra.forms.widgets import SpanWidget
from orchestra.forms.widgets import paddingCheckboxSelectMultiple
class RouteForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(RouteForm, self).__init__(*args, **kwargs)
if self.instance:
self.fields['backend'].widget = SpanWidget()
self.fields['backend'].required = False
self.fields['async_actions'].widget = paddingCheckboxSelectMultiple(45)
self.fields['async_actions'].choices = ((action, action) for action in self.instance.backend_class.actions)
class RouteAdmin(ExtendedModelAdmin): class RouteAdmin(ExtendedModelAdmin):
list_display = ( list_display = (
'backend', 'host', 'match', 'display_model', 'display_actions', 'async', 'is_active' 'backend', 'host', 'match', 'display_model', 'display_actions', 'async', 'is_active'
@ -131,6 +119,7 @@ class BackendLogAdmin(admin.ModelAdmin):
) )
list_display_links = ('id', 'backend') list_display_links = ('id', 'backend')
list_filter = ('state', 'backend') list_filter = ('state', 'backend')
date_hierarchy = 'created_at'
inlines = (BackendOperationInline,) inlines = (BackendOperationInline,)
fields = ( fields = (
'backend', 'server_link', 'state', 'mono_script', 'mono_stdout', 'backend', 'server_link', 'state', 'mono_script', 'mono_stdout',

View File

@ -60,9 +60,7 @@ class PHPApp(AppType):
return self.instance.data.get('php_version', '') return self.instance.data.get('php_version', '')
def get_php_init_vars(self, merge=settings.WEBAPPS_MERGE_PHP_WEBAPPS): def get_php_init_vars(self, merge=settings.WEBAPPS_MERGE_PHP_WEBAPPS):
""" """ Prepares PHP options for inclusion on php.ini """
process php options for inclusion on php.ini
"""
init_vars = OrderedDict() init_vars = OrderedDict()
options = self.instance.get_options(merge=merge) options = self.instance.get_options(merge=merge)
php_version_number = float(self.get_php_version_number()) php_version_number = float(self.get_php_version_number())
@ -75,7 +73,7 @@ class PHPApp(AppType):
# Filter non-deprecated PHP options # Filter non-deprecated PHP options
if opt.group == opt.PHP and (opt.deprecated or 999) > php_version_number: if opt.group == opt.PHP and (opt.deprecated or 999) > php_version_number:
init_vars[name] = value init_vars[name] = value
# Enable functions # Disable functions
if self.PHP_DISABLED_FUNCTIONS: if self.PHP_DISABLED_FUNCTIONS:
enable_functions = init_vars.pop('enable_functions', '') enable_functions = init_vars.pop('enable_functions', '')
if enable_functions or self.is_fpm: if enable_functions or self.is_fpm:
@ -87,7 +85,7 @@ class PHPApp(AppType):
if function not in enable_functions: if function not in enable_functions:
disable_functions.append(function) disable_functions.append(function)
init_vars['disable_functions'] = ','.join(disable_functions) init_vars['disable_functions'] = ','.join(disable_functions)
# process timeout # Process timeout
if timeout: if timeout:
# Give a little slack here # Give a little slack here
timeout = str(int(timeout)-2) timeout = str(int(timeout)-2)
@ -97,7 +95,7 @@ class PHPApp(AppType):
context = self.get_directive_context() context = self.get_directive_context()
error_log_path = os.path.normpath(self.PHP_ERROR_LOG_PATH % context) error_log_path = os.path.normpath(self.PHP_ERROR_LOG_PATH % context)
init_vars['error_log'] = error_log_path init_vars['error_log'] = error_log_path
# auto update max_post_size # Auto update max_post_size
if 'upload_max_filesize' in init_vars: if 'upload_max_filesize' in init_vars:
upload_max_filesize = init_vars['upload_max_filesize'] upload_max_filesize = init_vars['upload_max_filesize']
post_max_size = init_vars.get('post_max_size', '0') post_max_size = init_vars.get('post_max_size', '0')