Commit a383b8e4 by Őry Máté

dashboard: use real Forms for vm-create

parent ff738cc3
...@@ -28,10 +28,13 @@ class VmCreateForm(forms.Form): ...@@ -28,10 +28,13 @@ class VmCreateForm(forms.Form):
disks = forms.ModelMultipleChoiceField( disks = forms.ModelMultipleChoiceField(
queryset=Disk.objects.exclude(type="qcow2-snap"), queryset=Disk.objects.exclude(type="qcow2-snap"),
required=False
) )
managed_networks = forms.ModelMultipleChoiceField(queryset=VLANS) managed_networks = forms.ModelMultipleChoiceField(
unmanaged_networks = forms.ModelMultipleChoiceField(queryset=VLANS) queryset=VLANS, required=False)
unmanaged_networks = forms.ModelMultipleChoiceField(
queryset=VLANS, required=False)
def __init__(self, *args, **kwargs): def __init__(self, *args, **kwargs):
super(VmCreateForm, self).__init__(*args, **kwargs) super(VmCreateForm, self).__init__(*args, **kwargs)
......
...@@ -177,8 +177,18 @@ function vmCreateLoaded() { ...@@ -177,8 +177,18 @@ function vmCreateLoaded() {
type: 'POST', type: 'POST',
data: $('form').serialize(), data: $('form').serialize(),
success: function(data, textStatus, xhr) { success: function(data, textStatus, xhr) {
if(data.pk) { if(data.redirect) {
window.location.replace('/dashboard/vm/' + data.pk + '/#activity'); window.location.replace(data.redirect + '#activity');
}
else {
$('#vm-create-modal').remove();
$('body').append(data);
vmCreateLoaded();
addSliderMiscs();
$('#vm-create-modal').modal('show');
$('#vm-create-modal').on('hidden.bs.modal', function() {
$('#vm-create-modal').remove();
});
} }
}, },
error: function(xhr, textStatus, error) { error: function(xhr, textStatus, error) {
......
...@@ -6,7 +6,7 @@ import re ...@@ -6,7 +6,7 @@ import re
from django.contrib.auth.models import User, Group from django.contrib.auth.models import User, Group
from django.contrib.messages import warning from django.contrib.messages import warning
from django.core.exceptions import ( from django.core.exceptions import (
PermissionDenied, SuspiciousOperation, ObjectDoesNotExist, PermissionDenied, SuspiciousOperation,
) )
from django.core import signing from django.core import signing
from django.core.urlresolvers import reverse, reverse_lazy from django.core.urlresolvers import reverse, reverse_lazy
...@@ -343,17 +343,26 @@ class NodeList(SingleTableView): ...@@ -343,17 +343,26 @@ class NodeList(SingleTableView):
class VmCreate(TemplateView): class VmCreate(TemplateView):
form_class = VmCreateForm
form = None
def get_template_names(self): def get_template_names(self):
if self.request.is_ajax(): if self.request.is_ajax():
return ['dashboard/modal-wrapper.html'] return ['dashboard/modal-wrapper.html']
else: else:
return ['dashboard/nojs-wrapper.html'] return ['dashboard/nojs-wrapper.html']
def get(self, request, *args, **kwargs): def get(self, request, form=None, *args, **kwargs):
if form is None:
form = self.form_class()
context = self.get_context_data(**kwargs) context = self.get_context_data(**kwargs)
context.update({ context.update({
'template': 'dashboard/vm-create.html', 'template': 'dashboard/vm-create.html',
'box_title': 'Create a VM' 'box_title': 'Create a VM',
'templates': InstanceTemplate.objects.all(),
'vlans': Vlan.objects.all(),
'disks': Disk.objects.exclude(type="qcow2-snap"),
'vm_create_form': form,
}) })
return self.render_to_response(context) return self.render_to_response(context)
...@@ -361,81 +370,49 @@ class VmCreate(TemplateView): ...@@ -361,81 +370,49 @@ class VmCreate(TemplateView):
context = super(VmCreate, self).get_context_data(**kwargs) context = super(VmCreate, self).get_context_data(**kwargs)
# TODO acl # TODO acl
context.update({ context.update({
'templates': InstanceTemplate.objects.all(),
'vlans': Vlan.objects.all(),
'disks': Disk.objects.exclude(type="qcow2-snap"),
'vm_create_form': VmCreateForm,
}) })
return context return context
# TODO handle not ajax posts # TODO handle not ajax posts
def post(self, request, *args, **kwargs): def post(self, request, *args, **kwargs):
if self.request.user.is_authenticated(): if not self.request.user.is_authenticated():
user = self.request.user raise PermissionDenied()
else:
user = None
resp = {} form = self.form_class(request.POST)
try: if not form.is_valid():
pk = request.POST.get('template') return self.get(request, form, *args, **kwargs)
template = InstanceTemplate.objects.get( post = form.cleaned_data
pk=pk) user = request.user
except ValueError:
resp['error'] = True template = post['template']
resp['message'] = _("Select a VM from the list!") if request.user.has_perm('vm.set_resources'):
except InstanceTemplate.DoesNotExist as e: ikwargs = {
logger.warning('VmCreate.post: %s (pk=%d, user=%s)', 'num_cores': post['cpu_count'],
unicode(e), pk, unicode(request.user)) 'ram_size': post['ram_size'],
resp['error'] = True 'priority': post['cpu_priority'],
}
networks = (
[InterfaceTemplate(vlan=l, managed=True)
for l in post['unmanaged_networks']] +
[InterfaceTemplate(vlan=l, managed=False)
for l in post['unmanaged_networks']])
disks = post['disks']
inst = Instance.create_from_template(
template=template, owner=user, networks=networks,
disks=disks, **ikwargs)
else: else:
if request.user.has_perm('vm.set_resources'): inst = Instance.create_from_template(
ikwargs = { template=template, owner=user)
'num_cores': int(request.POST.get('cpu_count')), inst.deploy_async(user=request.user)
'ram_size': int(request.POST.get('ram_size')), messages.success(request, _('VM successfully created!'))
'priority': int(request.POST.get('cpu_priority')), path = inst.get_absolute_url()
}
try:
networks = [InterfaceTemplate(vlan=Vlan.objects.get(pk=l),
managed=True)
for l in request.POST.getlist(
'managed_networks')
]
unmanaged = request.POST.getlist('unmanaged_networks')
networks.extend([
InterfaceTemplate(vlan=Vlan.objects.get(pk=l),
managed=False)
for l in unmanaged])
disks = Disk.objects.filter(
pk__in=request.POST.getlist('disks'))
inst = Instance.create_from_template(
template=template, owner=user, networks=networks,
disks=disks, **ikwargs)
except ObjectDoesNotExist as e:
raise
logger.warning('VmCreate.post: %s (user=%s)',
unicode(e), unicode(request.user))
raise SuspiciousOperation()
else:
inst = Instance.create_from_template(
template=template, owner=user)
inst.deploy_async(user=request.user)
resp['pk'] = inst.pk
messages.success(request, _('VM successfully created!'))
if request.is_ajax(): if request.is_ajax():
return HttpResponse(json.dumps(resp), return HttpResponse(json.dumps({'redirect': path}),
content_type="application/json", content_type="application/json")
status=500 if resp.get('error') else 200)
else: else:
if 'error' in resp: return redirect(path)
messages.error(request, _('Failed to create VM.'))
return redirect(reverse('dashboard.index'))
else:
return redirect(reverse('dashboard.views.detail',
args=resp.values()))
class VmDelete(DeleteView): class VmDelete(DeleteView):
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or sign in to comment