diff --git a/conntrackt/views.py b/conntrackt/views.py --- a/conntrackt/views.py +++ b/conntrackt/views.py @@ -14,6 +14,7 @@ from django.views.generic import Templat from braces.views import MultiplePermissionsRequiredMixin # Application imports. +from .forms import EntityForm from .models import Project, Entity, Location from .utils import generate_entity_iptables @@ -417,3 +418,58 @@ class LocationDeleteView(MultiplePermiss messages.success(self.request, "Location %s has been removed." % self.get_object().name, extra_tags="alert alert-success") return super(LocationDeleteView, self).post(*args, **kwargs) + + +class EntityCreateView(MultiplePermissionsRequiredMixin, CreateView): + """ + View for creating a new entity. + """ + + model = Entity + form_class = EntityForm + template_name_suffix = "_create_form" + + # Required permissions. + permissions = { + "all": ("conntrackt.add_entity",), + } + + # Raise authorisation denied exception for unmet permissions. + raise_exception = True + + def get_form(self, form_class): + """ + Returns an instance of form that can be used by the view. + + The method will limit the project or location select inputs if request + contained this information. + """ + + form = super(EntityCreateView, self).get_form(form_class) + + # Limit the project selection if required. + project_id = self.request.GET.get("project", None) + if project_id: + form.fields["project"].queryset = Project.objects.filter(pk=project_id) + form.fields["project"].widget.attrs["readonly"] = True + + # Limit the location selection if required. + location_id = self.request.GET.get("location", None) + if location_id: + form.fields["location"].queryset = Location.objects.filter(pk=location_id) + form.fields["location"].widget.attrs["readonly"] = True + + return form + + def get_initial(self): + """ + Returns initial values that should be pre-selected (if they were + specified through a GET parameter). + """ + + initial = super(EntityCreateView, self).get_initial() + + initial["project"] = self.request.GET.get("project", None) + initial["location"] = self.request.GET.get("location", None) + + return initial