""" This module defines views for user database handling. """ from __future__ import absolute_import, unicode_literals from django.shortcuts import redirect from django.utils.translation import ugettext as _ from django.views.generic.edit import ( CreateView, ) from django.contrib import messages from gvacommon.viewmixins import StaffOrSelfLoginRequiredMixin from gvawebcore.views import HostingPackageAndCustomerMixin from .forms import ( AddUserDatabaseForm, ) from .models import ( DB_TYPES, UserDatabase, ) class AddUserDatabase( HostingPackageAndCustomerMixin, StaffOrSelfLoginRequiredMixin, CreateView ): """ This view is used to setup new user databases. """ model = UserDatabase context_object_name = 'database' template_name_suffix = '_create' form_class = AddUserDatabaseForm def _get_dbtypes(self, hostingpackage): retval = [] db_options = hostingpackage.get_databases() for opt in db_options: dbs_of_type = UserDatabase.objects.filter( db_user__osuser=hostingpackage.osuser, db_user__db_type=opt['db_type']).count() if dbs_of_type < opt['number']: retval.append((opt['db_type'], DB_TYPES[opt['db_type']])) return retval def get_form_kwargs(self): kwargs = super(AddUserDatabase, self).get_form_kwargs() kwargs['hostingpackage'] = self.get_hosting_package() kwargs['dbtypes'] = self._get_dbtypes(kwargs['hostingpackage']) return kwargs def form_valid(self, form): userdatabase = form.save() messages.success( self.request, _('Successfully create new {type} database {dbname} for user ' '{dbuser}').format( type=userdatabase.db_user.db_type, dbname=userdatabase.db_name, db_user=userdatabase.db_user) ) return redirect(self.get_hosting_package())