Python django.utils.datastructures.MultiValueDictKeyError() Examples

The following are 9 code examples of django.utils.datastructures.MultiValueDictKeyError(). 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 also want to check out all available functions/classes of the module django.utils.datastructures , or try the search function .
Example #1
Source File: views.py    From djangosaml2idp with Apache License 2.0 7 votes vote down vote up
def store_params_in_session(request: HttpRequest) -> None:
    """ Gathers the SAML parameters from the HTTP request and store them in the session
    """
    if request.method == 'POST':
        # future TODO: parse also SOAP and PAOS format from POST
        passed_data = request.POST
        binding = BINDING_HTTP_POST
    else:
        passed_data = request.GET
        binding = BINDING_HTTP_REDIRECT

    try:
        saml_request = passed_data['SAMLRequest']
    except (KeyError, MultiValueDictKeyError) as e:
        raise ValidationError(_('not a valid SAMLRequest: {}').format(repr(e)))

    request.session['Binding'] = binding
    request.session['SAMLRequest'] = saml_request
    request.session['RelayState'] = passed_data.get('RelayState', '') 
Example #2
Source File: views.py    From djangosaml2idp with Apache License 2.0 7 votes vote down vote up
def store_params_in_session(request: HttpRequest) -> None:
    """ Gathers the SAML parameters from the HTTP request and store them in the session
    """
    if request.method == 'POST':
        # future TODO: parse also SOAP and PAOS format from POST
        passed_data = request.POST
        binding = BINDING_HTTP_POST
    else:
        passed_data = request.GET
        binding = BINDING_HTTP_REDIRECT

    try:
        saml_request = passed_data['SAMLRequest']
    except (KeyError, MultiValueDictKeyError) as e:
        raise ValidationError(_('not a valid SAMLRequest: {}').format(repr(e)))

    request.session['Binding'] = binding
    request.session['SAMLRequest'] = saml_request
    request.session['RelayState'] = passed_data.get('RelayState', '') 
Example #3
Source File: views.py    From betterself with MIT License 7 votes vote down vote up
def post(self, request):
        user = request.user
        data = request.data

        try:
            initial_data = {
                'rescuetime_api_key': data['rescuetime_api_key'],
                'start_date': data['start_date'],
                'end_date': data['end_date'],
            }
        except (MultiValueDictKeyError, KeyError) as exc:
            return Response('Missing POST parameters {}'.format(exc), status=400)

        serializer = RescueTimeAPIRequestSerializer(data=initial_data)
        serializer.is_valid(raise_exception=True)

        # send the job off to celery so it's an async task
        import_user_rescuetime_history_via_api.delay(user=user, **serializer.validated_data)

        return Response(status=202) 
Example #4
Source File: views.py    From betterself with MIT License 7 votes vote down vote up
def post(self, request):
        data = request.data
        user = request.user

        try:
            initial_data = {
                'start_date': data['start_date'],
                'end_date': data['end_date'],
            }
        except (MultiValueDictKeyError, KeyError) as exc:
            return Response('Missing POST parameters {}'.format(exc), status=400)

        serializer = FitbitAPIRequestSerializer(data=initial_data)
        serializer.is_valid(raise_exception=True)

        # send the job off to celery so it's an async task
        import_user_fitbit_history_via_api.delay(user=user, **serializer.validated_data)

        return Response(status=202) 
Example #5
Source File: __init__.py    From marsha with MIT License 6 votes vote down vote up
def __getattr__(self, name):
        """Look for attributes in the request's POST parameters as a last resort.

        Parameters
        ----------
        name : string
            The property to retrieve

        Returns
        -------
        any
            Value of this parameter in the request's POST parameters

        Raises
        ------
        AttributeError
            Raised if the attribute was not found in the request's POST parameters

        """
        try:
            return self.request.POST[name]
        except MultiValueDictKeyError:
            raise AttributeError(name) 
Example #6
Source File: views.py    From betterself with MIT License 6 votes vote down vote up
def get(self, request):
        try:
            window = int(request.query_params[LOOKBACK_PARAM_NAME])
        except MultiValueDictKeyError:
            # MultiValueDictKeyError happens when a key doesn't exist
            window = 1
        except ValueError:
            # ValueError if something entered for a window that couldn't be interpreted
            return Response(status=400)

        user = request.user

        sleep_activities = SleepLog.objects.filter(user=user)
        builder = SleepActivityDataframeBuilder(sleep_activities)

        sleep_aggregate = builder.get_sleep_history_series()
        sleep_average = sleep_aggregate.rolling(window=window, min_periods=1).mean()

        result = sleep_average.to_json(date_format='iso')
        result = json.loads(result)
        return Response(data=result) 
Example #7
Source File: __init__.py    From astrobin with GNU Affero General Public License v3.0 6 votes vote down vote up
def image_edit_save_license(request):
    try:
        image_id = request.POST['image_id']
    except MultiValueDictKeyError:
        raise Http404

    image = get_image_or_404(Image.objects_including_wip, image_id)
    if request.user != image.user and not request.user.is_superuser:
        return HttpResponseForbidden()

    form = ImageLicenseForm(data=request.POST, instance=image)
    if not form.is_valid():
        messages.error(request,
                       _("There was one or more errors processing the form. You may need to scroll down to see them."))
        return render(request, 'image/edit/license.html', {
            'form': form,
            'image': image
        })

    form.save()

    messages.success(request, _("Form saved. Thank you!"))
    return HttpResponseRedirect(image.get_absolute_url()) 
Example #8
Source File: __init__.py    From astrobin with GNU Affero General Public License v3.0 5 votes vote down vote up
def image_edit_save_watermark(request):
    try:
        image_id = request.POST['image_id']
    except MultiValueDictKeyError:
        raise Http404

    image = get_image_or_404(Image.objects_including_wip, image_id)
    if request.user != image.user and not request.user.is_superuser:
        return HttpResponseForbidden()

    form = ImageEditWatermarkForm(data=request.POST, instance=image)
    if not form.is_valid():
        messages.error(request,
                       _("There was one or more errors processing the form. You may need to scroll down to see them."))
        return render(request, 'image/edit/watermark.html', {
            'image': image,
            'form': form,
        })

    form.save()

    # Save defaults in profile
    profile = image.user.userprofile
    profile.default_watermark = form.cleaned_data['watermark']
    profile.default_watermark_text = form.cleaned_data['watermark_text']
    profile.default_watermark_position = form.cleaned_data['watermark_position']
    profile.default_watermark_size = form.cleaned_data['watermark_size']
    profile.default_watermark_opacity = form.cleaned_data['watermark_opacity']
    profile.save(keep_deleted=True)

    if in_upload_wizard(image, request):
        return HttpResponseRedirect(
            reverse('image_edit_basic', kwargs={'id': image.get_id()}) + "?upload")

    # Force new thumbnails
    image.thumbnail_invalidate()

    return HttpResponseRedirect(image.get_absolute_url()) 
Example #9
Source File: views.py    From iguana with Creative Commons Attribution Share Alike 4.0 International 4 votes vote down vote up
def post(self, request, *args, **kwargs):
        self.object = self.get_object()

        # set language key
        request.session[translation.LANGUAGE_SESSION_KEY] = request.POST['language']

        # if a new avatar image was set, save it as the 'old' one
        self.avatar_kwargs = {'old_avatar_name': self.object.avatar.name}

        # Changing the email address should not be possible without entering the correct password!!
        # Normally this is a check one want in the clean-methods of those forms, but there it is not possible to access
        # elements of other forms, so this is a dirty workaround.
        # TODO maybe it is possible to provide this error to the respective clean-functions
        username = self.kwargs.get('username')
        # this should make this situation TOCTOU-safe
        # in case it doesn't try to use select_for_update()
        with transaction.atomic():
            # NOTE: this has to be part of the atomic block!
            current_user = get_user_model().objects.get(username=username)
            old_email = current_user.email
            forms = request.POST
            new_email = forms['email']
            wrong_password = False

            if old_email != new_email:
                try:
                    provided_password = forms['old_password']
                except (TypeError, MultiValueDictKeyError):
                    provided_password = None

                if(provided_password is None or provided_password == "" or
                   authenticate(username=username, password=provided_password) is None):
                    wrong_password = True

        # NOTE: in this case we shall not call save (super)
        if wrong_password:
            messages.add_message(request, messages.ERROR,
                                 _('You can not change the email address without entering the correct password.' +
                                   'All changes have been discarded!'))
            # TODO copy elements? - this might be some pain because we have to split those elements on both forms
            return super(EditProfilePageView, self).get(request, *args, **kwargs)

        response = super(EditProfilePageView, self).post(request, *args, **kwargs)

        current_user = get_user_model().objects.get(username=username)

        if response.status_code == 200:
            messages.add_message(request, messages.ERROR,
                                 _('Something went wrong, one or more field credentials are not fulfilled'))
        else:
            messages.add_message(request, messages.SUCCESS, _('Profile successfully edited.'))
        return response