Beispiel #1
0
def import_blocks(request):
    print request.FILES
    form = ImportBlocksForm(request.POST or None, request.FILES or None)
    if form.save():
        return HttpResponseRedirect('../')

    fieldsets = (
        Fieldset(form, fields=('edges', 'featnames', 'faces', 'place')),
        Fieldset(form, fields=('city', 'fix_cities', 'regenerate_intersections')),
        )

    return render(request, 'obadmin/block/import_blocks.html', {
        'fieldsets': fieldsets,
        'form': form,
    })
Beispiel #2
0
 def get_context_data(self, **kwargs):
     context = super(BaseAdminFormView, self).get_context_data(**kwargs)
     context['adminform'] = [
         Fieldset(context['form'],
                  fields=(x.name for x in context['form'].visible_fields()))
     ]
     return context
Beispiel #3
0
def pick_shapefile_layer(request):
    form = forms.PickShapefileLayerForm(request.POST or None)
    shapefile = request.GET.get('shapefile', False)
    if not shapefile:
        shapefile = request.POST.get('shapefile', False)
    if not shapefile:
        return HttpResponseRedirect('../upload-shapefile/')
    if form.save():
        return HttpResponseRedirect('../')
    if form.failure_msgs:
        for msg in form.failure_msgs:
            messages.error(request, msg)

    try:
        ds = DataSource(shapefile)
    except Exception as e:
        ds = None
        messages.error(request, "Error opening shapefile: %s" % e)
        logger.exception("Unhandled error opening shapefile:")

    fieldset = Fieldset(form, fields=('location_type', ))
    return render(
        request, 'obadmin/location/pick_shapefile_layer.html', {
            'shapefile': shapefile,
            'layers': ds,
            'location_types': LocationType.objects.all(),
            'fieldset': fieldset,
        })
Beispiel #4
0
 def get_context_data(self, **kwargs):
     context = super().get_context_data(**kwargs)
     context['fieldset'] = Fieldset(form=context['form'],
                                    name=None,
                                    readonly_fields=(),
                                    classes=('wide', ),
                                    fields=self.form_class.Meta.fields)
     return context
Beispiel #5
0
def import_zipcode_shapefiles(request):
    form = ImportZipcodeShapefilesForm(request.POST or None)
    if form.save():
        return HttpResponseRedirect('../')
    fieldset = Fieldset(form, fields=('state', 'zip_codes',))
    return render(request, 'obadmin/location/import_zip_shapefiles.html', {
      'fieldset': fieldset,
      'form': form,
    })
Beispiel #6
0
 def __iter__(self):
     for name, options in self.fieldsets:
         yield Fieldset(
             self.form,
             name,
             readonly_fields=self.readonly_fields,
             model_admin=self.model_admin,
             prepopulated_fields=self.prepopulated_fields,  # noqa
             **options
         )
Beispiel #7
0
def upload_shapefile(request):
    form = UploadShapefileForm(request.POST or None, request.FILES or None)
    if form.save():
        return HttpResponseRedirect('../pick-shapefile-layer/?shapefile=%s' % form.shp_path)

    fieldset = Fieldset(form, fields=('zipped_shapefile',))
    return render(request, 'obadmin/location/upload_shapefile.html', {
      'fieldset': fieldset,
      'form': form,
    })
Beispiel #8
0
def _my_fieldset_init(self, form, *args, **kwargs):
    readonly = kwargs.get('readonly_fields') or ()
    exclude = form._meta.exclude or ()
    kwargs['fields'] = filter(lambda _: not _ in exclude or _ in readonly,
                              kwargs.get('fields') or ())
    fieldsets = list(kwargs.pop('fieldsets', ()))
    old_fieldset_init(self, form, *args, **kwargs)
    self.fieldsets = fieldsets

    for i, (name, options) in enumerate(fieldsets):
        kw = {}
        kw.update(options)
        kw['name'] = name
        fieldsets[i] = Fieldset(form, **kw)
Beispiel #9
0
def pick_shapefile_layer(request):
    form = PickShapefileLayerForm(request.POST or None)
    shapefile = request.GET.get('shapefile', False)
    if not shapefile:
        shapefile = request.POST.get('shapefile', False)
    if not shapefile:
        return HttpResponseRedirect('../upload-shapefile/')
    if form.save():
        return HttpResponseRedirect('../')

    ds = DataSource(shapefile)
    fieldset = Fieldset(form, fields=('location_type',))
    return render(request, 'obadmin/location/pick_shapefile_layer.html', {
        'shapefile': shapefile,
        'layers': ds,
        'location_types': LocationType.objects.all(),
        'fieldset': fieldset,
    })
Beispiel #10
0
 def get_context_data(self, **kwargs):
     context = super().get_context_data(**kwargs)
     fields = [
         field for field in self.form_class.Meta.fields if field != 'user'
     ]
     readonly_fields = ()
     if context.get('view').request.user.is_anonymous:
         readonly_fields = ('is_shared', )
         context.get('form').instance.is_shared = True
     else:
         fields.remove('email')
     context['fieldset'] = Fieldset(
         form=context.get('form'),
         name=None,
         readonly_fields=readonly_fields,
         classes=('wide', ),
         fields=fields,
         model_admin=site.get_model_admin(Template))
     return context
Beispiel #11
0
def render_tab_fieldsets_inlines(context, entry):
    """
    Render the fieldsets and inlines for a tab.
    """
    template = "admin/includes/fieldset.html"
    admin_form = context['adminform']
    if 'request' not in context:
        raise ImproperlyConfigured(
            '"request" missing from context. Add django.core.context'
            '_processors.request to your'
            'TEMPLATE_CONTEXT_PROCESSORS')
    request = context['request']
    obj = context.get('original', None)
    # readonly_fields = admin_form.model_admin.get_readonly_fields(request, obj)
    if not admin_form.model_admin.has_change_permission(request, obj):
        readonly_fields = list(admin_form.form.all_fields.keys())
    else:
        readonly_fields = admin_form.model_admin.get_readonly_fields(request, obj)
    inline_matching = {}
    if "inline_admin_formsets" in context:
        inline_matching = dict((inline.opts.__class__.__name__, inline)
                               for inline in context["inline_admin_formsets"])

    if entry['type'] == 'fieldset':
        name = entry['name']
        f = Fieldset(
            admin_form.form,
            name,
            readonly_fields=readonly_fields,
            model_admin=admin_form.model_admin,
            **entry['config']
        )
        context["fieldset"] = f
        return render_to_string(template, context.flatten(), request=request)
    elif entry['type'] == 'inline':
        try:
            inline_admin_formset = inline_matching[entry["name"]]
            context["inline_admin_formset"] = inline_admin_formset
            return render_to_string(inline_admin_formset.opts.template,
                                    context.flatten(), request=request)
        except KeyError:  # The user does not have the permission
            pass
    return ''
Beispiel #12
0
    def test_absolute_url_tag(self, relative_url, is_regex, expect):
        """Check that the absolute url is correct.

        :param relative_url: a http-stub url
        :param is_regex: regex url flag
        :param expect: a expect absolute url
        """
        req = HttpRequest()
        req.META = {
            'SERVER_NAME': '127.0.0.1',
            'SERVER_PORT': '80',
        }
        form = HTTPStubAdmin(
            HTTPStub,
            AdminSite,
        ).get_form(req)(initial={
            'regex_path': is_regex
        })
        fieldset = Fieldset(form)
        url = stub_tags.absolute_url({'request': req}, relative_url, fieldset)
        assert url == expect
Beispiel #13
0
def import_newsitems(request):
    from ebdata.scrapers.general.spreadsheet.retrieval import get_default_unique_field_names
    form = forms.ImportNewsForm(
        request.POST or None,
        request.FILES or None,
        initial={'unique_fields': get_default_unique_field_names()})
    if form.save():
        # TODO: Capture logging output and put that in message too?
        msg = u'%d added. %d updated. %d skipped or unchanged.' % (
            form.added, form.updated, form.skipped)
        msg += u' See the server error log if you need more info.'
        messages.add_message(request, messages.INFO, msg)
        return HttpResponseRedirect('./')

    fieldsets = (Fieldset(form,
                          fields=('items_file', 'schema', 'mapping_file',
                                  'unique_fields')), )

    return render(request, 'obadmin/import_news.html', {
        'form': form,
        'fieldsets': fieldsets,
    })
Beispiel #14
0
def render_fieldsets_for_admincol(context, admin_col):
    """
    Render the fieldsets and inlines of a col.
    """
    out = ""
    admin_form = context['adminform']
    if not 'request' in context:
        raise ImproperlyConfigured(
            '"request" missing from context. Add django.core.context_processors.request to your TEMPLATE_CONTEXT_PROCESSORS'
        )
    request = context['request']
    obj = context.get('original', None)
    fieldsets = admin_col.get_elements(request, obj, include_inlines=True)
    readonly_fields = admin_form.model_admin.get_readonly_fields(request, obj)
    template = "admin/includes/fieldset.html"
    # Make a dict matching to retrieve inline_admin_formsets
    # {"inline class name": inline_formset_instance}
    inline_matching = dict((inline.opts.__class__.__name__, inline)
                           for inline in context["inline_admin_formsets"])
    for name, options in fieldsets:
        if "fields" in options:
            f = Fieldset(admin_form.form,
                         name,
                         readonly_fields=readonly_fields,
                         model_admin=admin_form.model_admin,
                         **options)
            context["fieldset"] = f
            out += render_to_string(template, context)
        elif "inline" in options:
            try:
                inline_admin_formset = inline_matching[options["inline"]]
                context["inline_admin_formset"] = inline_admin_formset
                out += render_to_string(inline_admin_formset.opts.template,
                                        context)
            except KeyError:  # The user does not have the permission
                pass
    return out
Beispiel #15
0
def notify(modeladmin, request, queryset):
    if not request.user.is_staff:
        raise PermissionDenied

    notification = models.OneTimeNotification
    model = queryset.model
    protocols = set()
    opts = modeladmin.model._meta

    if model in registry.objects:
        registration = registry.objects[model].registration
        # we don't want to have to evaluate this too many times
        query_list = list(queryset)

        if isinstance(registration, registry._ModelRegistration):
            for obj in query_list:
                for contact in obj.get_contacts_for_notification(notification):
                    protocols.add(contact.protocol)
        else:
            protocols = set(registration.get_supported_protocols())

        # now filter protocols to make sure there's an appropriate backend
        all_backends = tuple(
            b for p in protocols for b in registry.backends.by_protocol(p)
        )
        backends = tuple(b for b in all_backends if b.ALLOW_MANUAL_SENDING)
    else:
        all_backends = ()
        backends = ()
        protocols = ()
        query_list = []

    if not backends:
        form = NotifyForm(backends, {})
        if all_backends:
            error = "The {} model has contacts, but they don’t support manual sending."
        elif protocols:
            error = "The {} model has contacts, but they don’t have enabled backends."
        else:
            error = "The {} model is not registered or missing contact methods."
        form.full_clean()
        form.add_error("backend", error.format(model._meta.verbose_name))
    elif request.POST.get("post"):
        form = NotifyForm(backends, request.POST)
    else:
        form = NotifyForm(backends)
    context = {
        "title": _("Notify"),
        "opts": opts,
        "form": form,
        "action_checkbox_name": ACTION_CHECKBOX_NAME,
        "queryset": query_list,
        "fieldset": Fieldset(
            form, fields=("backend", "from_address", "subject", "content")
        ),
    }

    if request.POST.get("post") == "yes":
        if form.is_valid():
            # okay, now we issue the notification
            backend = registry.backends.by_id(form.cleaned_data["backend"])
            contacts = [
                c
                for cs in (
                    registration.get_contacts(obj, backend.PROTOCOL, notification)
                    for obj in query_list
                )
                for c in cs
            ]
            result = notification.send(
                backend.ID,
                contacts,
                form.cleaned_data["from_address"],
                form.cleaned_data["subject"],
                form.cleaned_data["content"],
            )
            if result is None:
                msg = gettext("Notification sent successfully.")
                django.contrib.messages.success(request, msg, fail_silently=True)
            else:
                msg = gettext("Error sending notification (%s).") % result
                django.contrib.messages.error(request, msg, fail_silently=True)
            return django.http.HttpResponseRedirect(
                reverse(
                    "%s:%s_%s_changelist"
                    % (modeladmin.admin_site.name, opts.app_label, opts.model_name)
                )
            )

    return TemplateResponse(request, "django_vox/notify.html", context)
Beispiel #16
0
    def get_context_data(self, request, object_id, **kwargs):
        if not request.user.is_staff:
            raise PermissionDenied("Not logged in")

        template = get_object_or_404(Template, pk=object_id)
        form_kwargs = {
            'project': template,
            'initial': {
                'project_id': template.id,
                'node_type': 'M',
            }
        }

        if request.method == 'POST':
            form = NodeAddForm(request.POST, **form_kwargs)
            if form.is_valid():
                node = get_gns3_node(template.gns3_id,
                                     form.cleaned_data['gns3_id'])

                if form.cleaned_data['node_type'] == 'W':
                    instance = WorkNode(
                        project=template,
                        gns3_id=form.cleaned_data['gns3_id'],
                        name=node['name'],
                        mac_address=node['properties']['mac_address'])
                elif form.cleaned_data['node_type'] == 'M':
                    instance = MonitorNode(
                        project=template,
                        gns3_id=form.cleaned_data['gns3_id'],
                        name=node['name'],
                        mac_address=node['properties']['mac_address'])
                elif form.cleaned_data['node_type'] == 'I':
                    instance = IRRNode(
                        project=template,
                        gns3_id=form.cleaned_data['gns3_id'],
                        name=node['name'],
                        mac_address=node['properties']['mac_address'])
                else:
                    raise Http404

                instance.save()
                if request.POST.get('_addanother'):
                    return {
                        'redirect':
                        reverse('admin:node_add',
                                kwargs={'object_id': template.id}),
                    }
                else:
                    return {
                        'redirect':
                        reverse('admin:lab_template_change',
                                kwargs={'object_id': template.id}),
                    }
        else:
            form = NodeAddForm(**form_kwargs)

        fieldsets = [Fieldset(form, fields=form.fields.keys())]

        # Prepare the network drawing and hyperlinks
        drawing_context = ProjectDiagram(template).get_data(show_state=False)
        available_nodes = dict(form.fields['gns3_id'].choices)
        for node in drawing_context['nodes']:
            if node['node_id'] in available_nodes:
                node['link'] = mark_safe(
                    "javascript:document.getElementById('id_gns3_id').value='"
                    + escapejs(node['node_id']) + "'")
            else:
                node['disabled'] = True

        drawing = render_to_string(
            template_name=DrawingView.template_name,
            context=drawing_context,
        )

        context = {
            **admin.site.each_context(request),
            'title':
            _('Add node to {template.name}').format(template=template),
            'lab_app_name':
            LabConfig.verbose_name,
            'template_name_plural':
            Template._meta.verbose_name_plural,
            'template':
            template,
            'adminform':
            fieldsets,
            'drawing':
            drawing,
            'show_save_and_add_another':
            len(available_nodes) > 1,
        }

        return context
Beispiel #17
0
    def get_context_data(self, request, object_id=None, **kwargs):
        if not request.user.is_staff:
            raise PermissionDenied("Not logged in")

        if object_id:
            template = get_object_or_404(Template, pk=object_id)
            default_time_limit = template.default_time_limit
            title = _('Add student to {template.name}').format(
                template=template)
        else:
            template = None
            default_time_limit = None
            title = _('Add student')

        form_kwargs = {
            'initial': {
                'template': template,
                'time_limit': default_time_limit,
            }
        }

        if request.method == 'POST':
            form = StudentAddForm(request.POST, **form_kwargs)

            if form.is_valid():
                # Clean up template name
                name = form.cleaned_data['template'].name
                if name.lower().startswith('template'):
                    name = name[8:]
                name = name.strip(':_- ')

                # Add student name to project name
                project_name = name + ' for ' + (
                    form.cleaned_data['student'].get_full_name()
                    or form.cleaned_data['student'].username)

                # Clone the template
                form.cleaned_data['template'].clone(
                    name=project_name,
                    student=form.cleaned_data['student'],
                    time_limit=form.cleaned_data['time_limit'])

                if template:
                    if request.POST.get('_addanother'):
                        return {
                            'redirect':
                            reverse('admin:student_add',
                                    kwargs={'object_id': template.id}),
                        }
                    else:
                        return {
                            'redirect':
                            reverse('admin:lab_template_changelist'),
                        }
                else:
                    if request.POST.get('_addanother'):
                        return {
                            'redirect': reverse('admin:lab_exercise_add'),
                        }
                    else:
                        return {
                            'redirect':
                            reverse('admin:lab_exercise_changelist'),
                        }

        else:
            form = StudentAddForm(**form_kwargs)

        fieldsets = [Fieldset(form, fields=form.fields.keys())]

        context = {
            **admin.site.each_context(request),
            'title': title,
            'lab_app_name': LabConfig.verbose_name,
            'template_name_plural': Template._meta.verbose_name_plural,
            'exercise_name_plural': Exercise._meta.verbose_name_plural,
            'template': template,
            'templates': Template.objects.all(),
            'adminform': fieldsets,
            'show_save_and_add_another': True,
        }

        return context
Beispiel #18
0
 def __iter__(self):
     for name, options in self.get_optionsets():
         yield Fieldset(self,
                        name,
                        readonly_fields=self.readonly_fields,
                        **options)
Beispiel #19
0
 def set_legend(self, text):
     self.helper.layout = Fieldset(text, *self.field_names)