Python django.forms.formset_factory() Examples

The following are 28 code examples for showing how to use django.forms.formset_factory(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module django.forms , or try the search function .

Example 1
Project: cadasta-platform   Author: Cadasta   File: test_widgets.py    License: GNU Affero General Public License v3.0 7 votes vote down vote up
def test_value_from_datadict(self):
        formset = formset_factory(ContactsForm)
        widget = widgets.ContactsWidget(attrs={'formset': formset})
        data = {
            'contacts-TOTAL_FORMS': '2',
            'contacts-INITIAL_FORMS': '1',
            'contacts-MIN_NUM_FORMS': '0',
            'contacts-MAX_NUM_FORMS': '1000',
            'contacts-0-name': 'Ringo',
            'contacts-0-email': 'ringo@beatles.uk',
            'contacts-0-tel': '555-555',
            'contacts-1-name': '',
            'contacts-1-email': '',
            'contacts-1-tel': ''
        }
        q_dict = QueryDict('', mutable=True)
        q_dict.update(data)
        value = widget.value_from_datadict(q_dict, {}, 'contacts')
        assert isinstance(value, formset) 
Example 2
Project: cadasta-platform   Author: Cadasta   File: test_fields.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def test_clean(self):
        ContactFormset = formset_factory(form=ContactsForm)
        value = ContactFormset({
            'form-TOTAL_FORMS': '2',
            'form-INITIAL_FORMS': '1',
            'form-MIN_NUM_FORMS': '0',
            'form-MAX_NUM_FORMS': '1000',
            'form-0-name': 'Ringo',
            'form-0-email': 'ringo@beatles.uk',
            'form-0-tel': '555-555',
            'form-1-name': 'john',
            'form-1-email': 'john@beatles.uk',
            'form-1-tel': '555-555',
            'form-1-remove': True,
            'form-2-name': '',
            'form-2-email': '',
            'form-2-tel': '',
        })
        field = org_fields.ContactsField(form=ContactsForm)
        expected = [{
            'name': 'Ringo',
            'email': 'ringo@beatles.uk',
            'tel': '555-555'
        }]
        assert field.clean(value) == expected 
Example 3
Project: cadasta-platform   Author: Cadasta   File: test_fields.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def test_invalid_clean(self):
        ContactFormset = formset_factory(form=ContactsForm)
        value = ContactFormset({
            'form-TOTAL_FORMS': '2',
            'form-INITIAL_FORMS': '1',
            'form-MIN_NUM_FORMS': '0',
            'form-MAX_NUM_FORMS': '1000',
            'form-0-name': 'Ringo',
            'form-0-email': 'ringo@beatles',
            'form-0-tel': '',
            'form-1-name': '',
            'form-1-email': '',
            'form-1-tel': ''
        })
        field = org_fields.ContactsField(form=ContactsForm)
        with raises(ValidationError):
            field.clean(value) 
Example 4
Project: coldfront   Author: ubccr   File: views.py    License: GNU General Public License v3.0 6 votes vote down vote up
def post(self, request, *args, **kwargs):
        search_ids = list(set(request.POST.get('search_id').split()))
        project_pk = self.kwargs.get('project_pk')

        project_obj = get_object_or_404(Project, pk=project_pk)
        pubs = []
        for ele in search_ids:
            pub_dict = self._search_id(ele)
            if pub_dict:
                pubs.append(pub_dict)

        formset = formset_factory(PublicationResultForm, max_num=len(pubs))
        formset = formset(initial=pubs, prefix='pubform')

        context = {}
        context['project_pk'] = project_obj.pk
        context['formset'] = formset
        context['search_ids'] = search_ids
        context['pubs'] = pubs

        return render(request, self.template_name, context) 
Example 5
Project: coldfront   Author: ubccr   File: views.py    License: GNU General Public License v3.0 6 votes vote down vote up
def get(self, request, *args, **kwargs):
        pk = self.kwargs.get('pk')
        allocation_obj = get_object_or_404(Allocation, pk=pk)

        allocation_attributes_to_delete = self.get_allocation_attributes_to_delete(
            allocation_obj)
        context = {}

        if allocation_attributes_to_delete:
            formset = formset_factory(AllocationAttributeDeleteForm, max_num=len(
                allocation_attributes_to_delete))
            formset = formset(
                initial=allocation_attributes_to_delete, prefix='attributeform')
            context['formset'] = formset
        context['allocation'] = allocation_obj
        return render(request, self.template_name, context) 
Example 6
Project: coldfront   Author: ubccr   File: views.py    License: GNU General Public License v3.0 6 votes vote down vote up
def get(self, request, *args, **kwargs):
        pk = self.kwargs.get('pk')
        allocation_obj = get_object_or_404(Allocation, pk=pk)

        users_in_allocation = self.get_users_in_allocation(
            allocation_obj)
        context = {}

        if users_in_allocation:
            formset = formset_factory(
                AllocationReviewUserForm, max_num=len(users_in_allocation))
            formset = formset(initial=users_in_allocation, prefix='userform')
            context['formset'] = formset

            context['resource_eula'] = {}
            if allocation_obj.get_parent_resource.resourceattribute_set.filter(resource_attribute_type__name='eula').exists():
                value = allocation_obj.get_parent_resource.resourceattribute_set.get(resource_attribute_type__name='eula').value
                context['resource_eula'].update({'eula': value})

        context['allocation'] = allocation_obj
        return render(request, self.template_name, context) 
Example 7
Project: djongo   Author: nesdis   File: fields.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def __init__(self, name, model_form_class, model_container, mdl_form_kw_l,
                 widget=None, admin=None, request=None, *args, **kwargs):

        self.name = name
        self.model_container = model_container
        self.model_form_class = _get_model_form_class(
            model_form_class, model_container, admin, request)
        self.mdl_form_kw_l = mdl_form_kw_l
        self.admin = admin
        self.request = request

        if not widget:
            widget = ArrayFormWidget(self.model_form_class.__name__)

        error_messages = {
            'incomplete': 'Enter all required fields.',
        }

        self.ArrayFormSet = forms.formset_factory(
            self.model_form_class, formset=NestedFormSet, can_delete=True)
        super().__init__(error_messages=error_messages,
                         widget=widget, *args, **kwargs) 
Example 8
Project: django-idcops   Author: Wenvki   File: edit.py    License: Apache License 2.0 5 votes vote down vote up
def _create_formset(self, extra=0):
        from django.forms import formset_factory
        # from django.forms import BaseFormSet
        FormSet = formset_factory(self.get_form_class(), extra=extra)
        formset = FormSet(form_kwargs=self.get_form_kwargs())
        return formset 
Example 9
Project: cadasta-platform   Author: Cadasta   File: fields.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def __init__(self, form=None, *args, **kwargs):
        self.formset = forms.formset_factory(form)
        super().__init__(*args, **kwargs) 
Example 10
Project: cadasta-platform   Author: Cadasta   File: test_fields.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def test_init(self):
        field = org_fields.ContactsField(form=ContactsForm)
        assert isinstance(field.formset, type(formset_factory(ContactsForm))) 
Example 11
Project: coldfront   Author: ubccr   File: views.py    License: GNU General Public License v3.0 5 votes vote down vote up
def get(self, request, *args, **kwargs):
        pk = self.kwargs.get('pk')
        project_obj = get_object_or_404(Project, pk=pk)

        users_to_remove = self.get_users_to_remove(project_obj)
        context = {}

        if users_to_remove:
            formset = formset_factory(
                ProjectRemoveUserForm, max_num=len(users_to_remove))
            formset = formset(initial=users_to_remove, prefix='userform')
            context['formset'] = formset

        context['project'] = get_object_or_404(Project, pk=pk)
        return render(request, self.template_name, context) 
Example 12
Project: coldfront   Author: ubccr   File: views.py    License: GNU General Public License v3.0 5 votes vote down vote up
def post(self, request, *args, **kwargs):
        project_obj = get_object_or_404(
            Project, pk=self.kwargs.get('project_pk'))

        publications_do_delete = self.get_publications_to_delete(project_obj)
        context = {}

        formset = formset_factory(
            PublicationDeleteForm, max_num=len(publications_do_delete))
        formset = formset(
            request.POST, initial=publications_do_delete, prefix='publicationform')

        publications_deleted_count = 0

        if formset.is_valid():
            for form in formset:
                publication_form_data = form.cleaned_data
                if publication_form_data['selected']:

                    publication_obj = Publication.objects.get(
                        project=project_obj,
                        title=publication_form_data.get('title'),
                        year=publication_form_data.get('year')
                    )
                    publication_obj.delete()
                    publications_deleted_count += 1

            messages.success(request, 'Deleted {} publications from project.'.format(
                publications_deleted_count))
        else:
            for error in formset.errors:
                messages.error(request, error)

        return HttpResponseRedirect(reverse('project-detail', kwargs={'pk': project_obj.pk})) 
Example 13
Project: coldfront   Author: ubccr   File: views.py    License: GNU General Public License v3.0 5 votes vote down vote up
def get(self, request, *args, **kwargs):
        project_obj = get_object_or_404(Project, pk=self.kwargs.get('project_pk'))

        grants_to_delete = self.get_grants_to_delete(project_obj)
        context = {}

        if grants_to_delete:
            formset = formset_factory(GrantDeleteForm, max_num=len(grants_to_delete))
            formset = formset(initial=grants_to_delete, prefix='grantform')
            context['formset'] = formset

        context['project'] = project_obj
        return render(request, self.template_name, context) 
Example 14
Project: coldfront   Author: ubccr   File: views.py    License: GNU General Public License v3.0 5 votes vote down vote up
def post(self, request, *args, **kwargs):
        project_obj = get_object_or_404(Project, pk=self.kwargs.get('project_pk'))

        grants_to_delete = self.get_grants_to_delete(project_obj)
        context = {}

        formset = formset_factory(GrantDeleteForm, max_num=len(grants_to_delete))
        formset = formset(request.POST, initial=grants_to_delete, prefix='grantform')

        grants_deleted_count = 0

        if formset.is_valid():
            for form in formset:
                grant_form_data = form.cleaned_data
                if grant_form_data['selected']:

                    grant_obj = Grant.objects.get(
                        project=project_obj,
                        title=grant_form_data.get('title'),
                        grant_number=grant_form_data.get('grant_number')
                    )
                    grant_obj.delete()
                    grants_deleted_count += 1

            messages.success(request, 'Deleted {} grants from project.'.format(grants_deleted_count))
        else:
            for error in formset.errors:
                messages.error(request, error)

        return HttpResponseRedirect(reverse('project-detail', kwargs={'pk': project_obj.pk})) 
Example 15
Project: coldfront   Author: ubccr   File: views.py    License: GNU General Public License v3.0 5 votes vote down vote up
def get(self, request, *args, **kwargs):
        pk = self.kwargs.get('pk')
        allocation_obj = get_object_or_404(Allocation, pk=pk)

        users_to_add = self.get_users_to_add(allocation_obj)
        context = {}

        if users_to_add:
            formset = formset_factory(
                AllocationAddUserForm, max_num=len(users_to_add))
            formset = formset(initial=users_to_add, prefix='userform')
            context['formset'] = formset

        context['allocation'] = allocation_obj
        return render(request, self.template_name, context) 
Example 16
Project: coldfront   Author: ubccr   File: views.py    License: GNU General Public License v3.0 5 votes vote down vote up
def post(self, request, *args, **kwargs):
        pk = self.kwargs.get('pk')
        allocation_obj = get_object_or_404(Allocation, pk=pk)

        users_to_remove = self.get_users_to_remove(allocation_obj)

        formset = formset_factory(
            AllocationRemoveUserForm, max_num=len(users_to_remove))
        formset = formset(
            request.POST, initial=users_to_remove, prefix='userform')

        remove_users_count = 0

        if formset.is_valid():
            allocation_user_removed_status_choice = AllocationUserStatusChoice.objects.get(
                name='Removed')
            for form in formset:
                user_form_data = form.cleaned_data
                if user_form_data['selected']:

                    remove_users_count += 1

                    user_obj = User.objects.get(
                        username=user_form_data.get('username'))
                    if allocation_obj.project.pi == user_obj:
                        continue

                    allocation_user_obj = allocation_obj.allocationuser_set.get(
                        user=user_obj)
                    allocation_user_obj.status = allocation_user_removed_status_choice
                    allocation_user_obj.save()
                    allocation_remove_user.send(sender=self.__class__,
                                                allocation_user_pk=allocation_user_obj.pk)

            messages.success(
                request, 'Removed {} users from allocation.'.format(remove_users_count))
        else:
            for error in formset.errors:
                messages.error(request, error)

        return HttpResponseRedirect(reverse('allocation-detail', kwargs={'pk': pk})) 
Example 17
Project: coldfront   Author: ubccr   File: views.py    License: GNU General Public License v3.0 5 votes vote down vote up
def post(self, request, *args, **kwargs):
        pk = self.kwargs.get('pk')
        allocation_obj = get_object_or_404(Allocation, pk=pk)

        allocation_attributes_to_delete = self.get_allocation_attributes_to_delete(
            allocation_obj)

        formset = formset_factory(AllocationAttributeDeleteForm, max_num=len(
            allocation_attributes_to_delete))
        formset = formset(
            request.POST, initial=allocation_attributes_to_delete, prefix='attributeform')

        attributes_deleted_count = 0

        if formset.is_valid():
            for form in formset:
                form_data = form.cleaned_data
                if form_data['selected']:

                    attributes_deleted_count += 1

                    allocation_attribute = AllocationAttribute.objects.get(
                        pk=form_data['pk'])
                    allocation_attribute.delete()

            messages.success(request, 'Deleted {} attributes from allocation.'.format(
                attributes_deleted_count))
        else:
            for error in formset.errors:
                messages.error(request, error)

        return HttpResponseRedirect(reverse('allocation-detail', kwargs={'pk': pk})) 
Example 18
Project: coldfront   Author: ubccr   File: views.py    License: GNU General Public License v3.0 5 votes vote down vote up
def get(self, request, *args, **kwargs):
        pk = self.kwargs.get('pk')
        allocation_obj = get_object_or_404(Allocation, pk=pk)
        notes_to_delete = self.get_notes_to_delete(allocation_obj)
        context = {}
        if notes_to_delete:
            formset = formset_factory(
                AllocationInvoiceNoteDeleteForm, max_num=len(notes_to_delete))
            formset = formset(initial=notes_to_delete, prefix='noteform')
            context['formset'] = formset
        context['allocation'] = allocation_obj
        return render(request, self.template_name, context) 
Example 19
Project: registrasion   Author: chrisjrn   File: forms.py    License: Apache License 2.0 5 votes vote down vote up
def ProductsForm(category, products):
    ''' Produces an appropriate _ProductsForm subclass for the given render
    type. '''

    # Each Category.RENDER_TYPE value has a subclass here.
    cat = inventory.Category
    RENDER_TYPES = {
        cat.RENDER_TYPE_QUANTITY: _QuantityBoxProductsForm,
        cat.RENDER_TYPE_RADIO: _RadioButtonProductsForm,
        cat.RENDER_TYPE_ITEM_QUANTITY: _ItemQuantityProductsForm,
        cat.RENDER_TYPE_CHECKBOX: _CheckboxProductsForm,
    }

    # Produce a subclass of _ProductsForm which we can alter the base_fields on
    class ProductsForm(RENDER_TYPES[category.render_type]):
        pass

    products = list(products)
    products.sort(key=lambda prod: prod.order)

    ProductsForm.set_fields(category, products)

    if category.render_type == inventory.Category.RENDER_TYPE_ITEM_QUANTITY:
        ProductsForm = forms.formset_factory(
            ProductsForm,
            formset=_ItemQuantityProductsFormSet,
        )

    return ProductsForm 
Example 20
Project: registrasion   Author: chrisjrn   File: forms.py    License: Apache License 2.0 5 votes vote down vote up
def staff_products_formset_factory(user):
    ''' Creates a formset of StaffProductsForm for the given user. '''
    form_type = staff_products_form_factory(user)
    return forms.formset_factory(form_type) 
Example 21
Project: iguana   Author: iguana-project   File: views.py    License: Creative Commons Attribution Share Alike 4.0 International 5 votes vote down vote up
def get(self, request):
        formset = formset_factory(EmailFormField, extra=0, max_num=self.max_number_of_invitables,
                                  min_num=1, validate_max=True, formset=EmailFormSet)
        cp = request.GET.copy()
        # TODO how can i provide the platform via function to the template?
        #      somehow i couldn't call the desired function from template
        return render(request, 'invite_users/invite_users.html', {'form': self.form_class(), 'formset': formset,
                                                                  'platform': settings.PLATFORM}) 
Example 22
Project: wagtail   Author: wagtail   File: collections.py    License: BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def collection_member_permission_formset_factory(
    model, permission_types, template, default_prefix=None
):

    permission_queryset = Permission.objects.filter(
        content_type__app_label=model._meta.app_label,
        codename__in=[codename for codename, short_label, long_label in permission_types]
    ).select_related('content_type')

    if default_prefix is None:
        default_prefix = '%s_permissions' % model._meta.model_name

    class PermissionMultipleChoiceField(forms.ModelMultipleChoiceField):
        """
        Allows the custom labels from ``permission_types`` to be applied to
        permission checkboxes for the ``CollectionMemberPermissionsForm`` below
        """
        def label_from_instance(self, obj):
            for codename, short_label, long_label in permission_types:
                if codename == obj.codename:
                    return long_label
            return str(obj)

    class CollectionMemberPermissionsForm(forms.Form):
        """
        For a given model with CollectionMember behaviour,
        defines the permissions that are assigned to an entity
        (i.e. group or user) for a specific collection
        """
        collection = forms.ModelChoiceField(
            queryset=Collection.objects.all().prefetch_related('group_permissions')
        )
        permissions = PermissionMultipleChoiceField(
            queryset=permission_queryset,
            required=False,
            widget=forms.CheckboxSelectMultiple
        )

    GroupCollectionMemberPermissionFormSet = type(
        str('GroupCollectionMemberPermissionFormSet'),
        (BaseGroupCollectionMemberPermissionFormSet, ),
        {
            'permission_types': permission_types,
            'permission_queryset': permission_queryset,
            'default_prefix': default_prefix,
            'template': template,
        }
    )

    return forms.formset_factory(
        CollectionMemberPermissionsForm,
        formset=GroupCollectionMemberPermissionFormSet,
        extra=0,
        can_delete=True
    ) 
Example 23
Project: coldfront   Author: ubccr   File: views.py    License: GNU General Public License v3.0 4 votes vote down vote up
def post(self, request, *args, **kwargs):
        user_search_string = request.POST.get('q')
        search_by = request.POST.get('search_by')
        pk = self.kwargs.get('pk')

        project_obj = get_object_or_404(Project, pk=pk)

        users_to_exclude = [ele.user.username for ele in project_obj.projectuser_set.filter(
            status__name='Active')]

        cobmined_user_search_obj = CombinedUserSearch(
            user_search_string, search_by, users_to_exclude)

        context = cobmined_user_search_obj.search()

        matches = context.get('matches')
        for match in matches:
            match.update(
                {'role': ProjectUserRoleChoice.objects.get(name='User')})

        if matches:
            formset = formset_factory(ProjectAddUserForm, max_num=len(matches))
            formset = formset(initial=matches, prefix='userform')
            context['formset'] = formset
            context['user_search_string'] = user_search_string
            context['search_by'] = search_by

        if len(user_search_string.split()) > 1:
            users_already_in_project = []
            for ele in user_search_string.split():
                if ele in users_to_exclude:
                    users_already_in_project.append(ele)
            context['users_already_in_project'] = users_already_in_project

        # The following block of code is used to hide/show the allocation div in the form.
        if project_obj.allocation_set.filter(status__name__in=['Active', 'New', 'Renewal Requested']).exists():
            div_allocation_class = 'placeholder_div_class'
        else:
            div_allocation_class = 'd-none'
        context['div_allocation_class'] = div_allocation_class
        ###

        allocation_form = ProjectAddUsersToAllocationForm(
            request.user, project_obj.pk, prefix='allocationform')
        context['pk'] = pk
        context['allocation_form'] = allocation_form
        return render(request, self.template_name, context) 
Example 24
Project: coldfront   Author: ubccr   File: views.py    License: GNU General Public License v3.0 4 votes vote down vote up
def post(self, request, *args, **kwargs):
        pk = self.kwargs.get('pk')
        project_obj = get_object_or_404(Project, pk=pk)

        users_to_remove = self.get_users_to_remove(project_obj)

        formset = formset_factory(
            ProjectRemoveUserForm, max_num=len(users_to_remove))
        formset = formset(
            request.POST, initial=users_to_remove, prefix='userform')

        remove_users_count = 0

        if formset.is_valid():
            project_user_removed_status_choice = ProjectUserStatusChoice.objects.get(
                name='Removed')
            allocation_user_removed_status_choice = AllocationUserStatusChoice.objects.get(
                name='Removed')
            for form in formset:
                user_form_data = form.cleaned_data
                if user_form_data['selected']:

                    remove_users_count += 1

                    user_obj = User.objects.get(
                        username=user_form_data.get('username'))

                    if project_obj.pi == user_obj:
                        continue

                    project_user_obj = project_obj.projectuser_set.get(
                        user=user_obj)
                    project_user_obj.status = project_user_removed_status_choice
                    project_user_obj.save()

                    # get allocation to remove users from
                    allocations_to_remove_user_from = project_obj.allocation_set.filter(
                        status__name__in=['Active', 'New', 'Renewal Requested'])
                    for allocation in allocations_to_remove_user_from:
                        for allocation_user_obj in allocation.allocationuser_set.filter(user=user_obj, status__name__in=['Active', ]):
                            allocation_user_obj.status = allocation_user_removed_status_choice
                            allocation_user_obj.save()

                            allocation_remove_user.send(sender=self.__class__,
                                                        allocation_user_pk=allocation_user_obj.pk)

            messages.success(
                request, 'Removed {} users from project.'.format(remove_users_count))
        else:
            for error in formset.errors:
                messages.error(request, error)

        return HttpResponseRedirect(reverse('project-detail', kwargs={'pk': pk})) 
Example 25
Project: coldfront   Author: ubccr   File: views.py    License: GNU General Public License v3.0 4 votes vote down vote up
def post(self, request, *args, **kwargs):
        pubs = eval(request.POST.get('pubs'))
        project_pk = self.kwargs.get('project_pk')

        project_obj = get_object_or_404(Project, pk=project_pk)
        formset = formset_factory(PublicationResultForm, max_num=len(pubs))
        formset = formset(request.POST, initial=pubs, prefix='pubform')

        publications_added = 0
        publications_skipped = []
        if formset.is_valid():
            for form in formset:
                form_data = form.cleaned_data
                source_obj = PublicationSource.objects.get(
                    pk=form_data.get('source_pk'))
                publication_obj, created = Publication.objects.get_or_create(
                    project=project_obj,
                    title=form_data.get('title'),
                    author=form_data.get('author'),
                    year=form_data.get('year'),
                    journal=form_data.get('journal'),
                    unique_id=form_data.get('unique_id'),
                    source=source_obj
                )
                if created:
                    publications_added += 1
                else:
                    publications_skipped.append(form_data.get('unique_id'))

            msg = ''
            if publications_added:
                msg += 'Added {} publication{} to project.'.format(
                    publications_added, 's' if publications_added > 1 else '')
            if publications_skipped:
                msg += 'Skipped adding: {}'.format(
                    ', '.join(publications_skipped))

            messages.success(request, msg)
        else:
            for error in formset.errors:
                messages.error(request, error)

        return HttpResponseRedirect(reverse('project-detail', kwargs={'pk': project_pk})) 
Example 26
Project: coldfront   Author: ubccr   File: views.py    License: GNU General Public License v3.0 4 votes vote down vote up
def post(self, request, *args, **kwargs):
        pk = self.kwargs.get('pk')
        allocation_obj = get_object_or_404(Allocation, pk=pk)

        users_to_add = self.get_users_to_add(allocation_obj)

        formset = formset_factory(
            AllocationAddUserForm, max_num=len(users_to_add))
        formset = formset(request.POST, initial=users_to_add,
                          prefix='userform')

        users_added_count = 0

        if formset.is_valid():

            allocation_user_active_status_choice = AllocationUserStatusChoice.objects.get(
                name='Active')

            for form in formset:
                user_form_data = form.cleaned_data
                if user_form_data['selected']:

                    users_added_count += 1

                    user_obj = User.objects.get(
                        username=user_form_data.get('username'))

                    if allocation_obj.allocationuser_set.filter(user=user_obj).exists():
                        allocation_user_obj = allocation_obj.allocationuser_set.get(
                            user=user_obj)
                        allocation_user_obj.status = allocation_user_active_status_choice
                        allocation_user_obj.save()
                    else:
                        allocation_user_obj = AllocationUser.objects.create(
                            allocation=allocation_obj, user=user_obj, status=allocation_user_active_status_choice)

                    allocation_activate_user.send(sender=self.__class__,
                                                  allocation_user_pk=allocation_user_obj.pk)
            messages.success(
                request, 'Added {} users to allocation.'.format(users_added_count))
        else:
            for error in formset.errors:
                messages.error(request, error)

        return HttpResponseRedirect(reverse('allocation-detail', kwargs={'pk': pk})) 
Example 27
Project: nector   Author: clayball   File: views.py    License: GNU General Public License v3.0 4 votes vote down vote up
def status(request, sup_hosts=False, sup_ports=False, sup_events=False, sup_vulns=False, sup_malware=False, changing_db=False):
    installation_complete = False

    subnets_installed = os.path.isfile('subnets.txt')

    hosts_installed = Host.objects.all().exists()
    vulns_installed = Vulnerability.objects.all().exists()
    events_installed = Event.objects.all().exists()
    malware_installed = Malware.objects.all().exists()
    ports_installed = Host.objects.all().filter(ports__icontains='"').exists()

    if hosts_installed and vulns_installed and events_installed \
       and ports_installed and malware_installed:
        installation_complete = True

    context = {'subnets_installed' : subnets_installed,
               'hosts_installed'   : hosts_installed,
               'vulns_installed'   : vulns_installed,
               'events_installed'  : events_installed,
               'malware_installed' : malware_installed,
               'ports_installed'   : ports_installed,
               'installation_complete' : installation_complete,
               'sup_hosts'   : sup_hosts,
               'sup_ports'   : sup_ports,
               'sup_events'  : sup_events,
               'sup_vulns'   : sup_vulns,
               'sup_malware' : sup_malware,
               'changing_db' : changing_db,
               'db_type' : connection.vendor}

    if sup_events:
        context['events_form'] = formset_factory(EventForm)
        context['extra_forms'] = 1

    if sup_vulns:
        context['vulns_form'] = formset_factory(VulnForm)
        context['extra_forms'] = 1

    if sup_malware:
        context['mals_form'] = formset_factory(MalwareForm)
        context['extra_forms'] = 1

    return render(request, 'nector_home/status.html', context) 
Example 28
Project: iguana   Author: iguana-project   File: views.py    License: Creative Commons Attribution Share Alike 4.0 International 4 votes vote down vote up
def post(self, request):
        form = self.form_class(request.POST)
        MyEmailFormSet = formset_factory(EmailFormField, extra=0,
                                         max_num=self.max_number_of_invitables,
                                         min_num=1, validate_max=True, formset=EmailFormSet)

        # user wants to invite more people ('invite_more' is the name-tag of the submit button)
        # thanks to http://brantsteen.com/blog/django-adding-inline-formset-rows-without-javascript/
        # for this non-js solution
        if 'invite_more' in request.POST:
            # we copy the previous elements
            cp = request.POST.copy()
            number_of_people = int(cp['form-TOTAL_FORMS'])

            number_of_people += 1
            cp['form-TOTAL_FORMS'] = number_of_people
            additional_email = MyEmailFormSet(cp)
            return render(request, 'invite_users/invite_users.html', {'form': form, 'formset': additional_email,
                                                                      'platform': settings.PLATFORM})

        formset = MyEmailFormSet(request.POST)

        if form.is_valid() and formset.is_valid():
            inviting_user = request.user.get_username()
            additional_message = request.POST['additional_message']
            full_message = self.default_message+inviting_user+".\n\n"+additional_message
            invited_list = []

            to_header = []
            for f in formset:
                cleaned_data = f.cleaned_data
                target_email = cleaned_data.get('email')
                if target_email is not None:
                    invited_list.append(target_email)
                    if settings.EMAIL_RECIPIENT_IN_TO_HEADER:
                        to_header.append(target_email)

            # this is better than send_mail because bcc is possible
            email = EmailMessage(
                # subject
                _('You have been invited to ')+settings.PLATFORM,
                full_message,
                # TODO as soon as there is a parameter in the settings to provide the from field it shall be used here
                # to
                to=to_header,
                # bcc
                bcc=invited_list,
            )
            email.send()

            # list all notified email addresses in succesfully_invited
            request.session['invite_list'] = invited_list
            return HttpResponseRedirect('successfully_invited')

        return render(request, 'invite_users/invite_users.html', {'form': form, 'formset': formset,
                                                                  'platform': settings.PLATFORM})