Example #1
0
def handle_pust_request(request, organisation_name=None):
    user = request.user

    organisation = None
    if organisation_name:
        organisation = get_object_or_404(Organisation, slug=organisation_name)

    query_data = getattr(request, request.method)  # QueryDict

    is_idgo_partner = query_data.pop('is_idgo_partner', ['False'])
    if is_idgo_partner and is_idgo_partner[-1] in ['True', 'true', '1', 1]:
        is_idgo_partner = True
    else:
        is_idgo_partner = False

    # Slug/Name
    slug = query_data.pop('name', organisation and [organisation.slug])
    if slug:
        query_data.__setitem__('slug', slug[-1])

    # `legal_name` est obligatoire
    legal_name = query_data.pop('legal_name', organisation
                                and [organisation.legal_name])
    if legal_name:
        query_data.__setitem__('legal_name', legal_name[-1])

    form = Form(query_data,
                request.FILES,
                instance=organisation,
                include={'user': user})
    if not form.is_valid():
        raise GenericException(details=form._errors)

    data = form.cleaned_data
    kvp = dict((item, form.cleaned_data[item])
               for item in form.Meta.organisation_fields)

    try:
        with transaction.atomic():
            if organisation_name:
                for item in form.Meta.fields:
                    if item in data:
                        setattr(organisation, item, data[item])
                setattr(organisation, 'is_crige_partner', is_idgo_partner)
                organisation.save()
            else:
                kvp['is_active'] = True
                organisation = Organisation.objects.create(**kvp)
                AccountActions.objects.create(
                    action='created_organisation_through_api',
                    organisation=organisation,
                    profile=user.profile,
                    closed=timezone.now())
    except ValidationError as e:
        return GenericException(details=e.__str__())

    return organisation
Example #2
0
def handle_pust_request(request, organisation_name=None):
    user = request.user

    organisation = None
    if organisation_name:
        organisation = get_object_or_404(Organisation, slug=organisation_name)

    data = getattr(request, request.method).dict()
    data_form = {
        'legal_name': data.get('legal_name'),
        'description': data.get('description'),
        'organisation_type': data.get('type'),
        'address': data.get('address'),
        'postcode': data.get('postcode'),
        'city': data.get('city'),
        'phone': data.get('phone'),
        'email': data.get('email'),
        'license': data.get('license'),
        'jurisdiction': data.get('jurisdiction'),
    }

    form = Form(data_form,
                request.FILES,
                instance=organisation,
                include={'user': user})
    if not form.is_valid():
        raise GenericException(details=form._errors)

    data = form.cleaned_data
    kvp = dict((item, form.cleaned_data[item])
               for item in form.Meta.organisation_fields)

    try:
        with transaction.atomic():
            if organisation_name:
                for item in form.Meta.fields:
                    if item in data_form:
                        setattr(organisation, item, data_form[item])
                organisation.save()
            else:
                kvp['is_active'] = True
                organisation = Organisation.objects.create(**kvp)
                AccountActions.objects.create(
                    action='created_organisation_through_api',
                    organisation=organisation,
                    profile=user.profile,
                    closed=timezone.now())
    except ValidationError as e:
        return GenericException(details=e.__str__())

    return organisation
Example #3
0
def member_unsubscribe_process(request, profile, organisation):
    if profile.organisation != organisation:
        raise GenericException()
    if profile.organisation.is_crige_partner:
        profile.crige_membership = False
    profile.organisation = None
    profile.membership = False
    profile.save()
Example #4
0
def handle_pust_request(request, dataset_name, resource_id=None):
    # title -> name
    # description -> description
    # language -> lang
    # format -> format_type.pk
    # type -> data_type raw|annexe|service
    # restricted_level -> public|registered|only_allowed_users|same_organization|any_organization
    # restricted_list -> list of: user.username|organisation.slug
    # up_file -> {File}
    user = request.user
    dataset = get_object_or_404_extended(
        Dataset, user, include={'slug': dataset_name})
    resource = None
    if resource_id:
        resource = get_object_or_404(Resource, ckan_id=resource_id)

    query_data = getattr(request, request.method)  # QueryDict

    # `title` est obligatoire
    title = query_data.pop('title', resource and [resource.title])
    if title:
        query_data.__setitem__('title', title[-1])

    # `lang` est obligatoire
    lang = query_data.pop('language', query_data.pop('lang', resource and [resource.lang]))
    if lang:
        query_data.__setitem__('lang', lang[-1])

    # `data_type` est obligatoire
    data_type = query_data.pop('data_type', query_data.pop('type', resource and [resource.data_type]))
    if data_type:
        query_data.__setitem__('data_type', data_type[-1])

    restricted_list = query_data.pop('restricted_list', [])
    profiles_allowed = None
    organisations_allowed = None

    restricted_level = query_data.pop('restricted_level', resource and [resource.restricted_level] or ['public'])
    if restricted_level[-1] == 'only_allowed_users':
        profiles_allowed = User.objects.filter(username__in=restricted_list)
        query_data.__setitem__('profiles_allowed', [instance.pk for instance in profiles_allowed])
    elif restricted_level[-1] in ('same_organization', 'any_organization'):
        organisations_allowed = Organisation.objects.filter(slug__in=restricted_list)
        query_data.__setitem__('organisations_allowed', [instance.pk for instance in organisations_allowed])
    query_data.__setitem__('restricted_level', restricted_level[-1])

    format_type_slug = query_data.pop('format_type', query_data.pop('format', None))
    if format_type_slug:
        try:
            resource_format = ResourceFormats.objects.get(slug=format_type_slug[-1])
        except ResourceFormats.DoesNotExist as e:
            raise GenericException(details=e.__str__())
        query_data.__setitem__('format_type', resource_format.pk)

    form = Form(query_data, request.FILES, instance=resource, dataset=dataset, user=user)
    if not form.is_valid():
        raise GenericException(details=form._errors)

    data = form.cleaned_data
    kvp = {
        'dataset': dataset,
        'title': data['title'],
        'description': data['description'],
        'lang': data['lang'],
        'data_type': data['data_type'],
        'format_type': data['format_type'],
        # 'last_update': data['last_update'],
        'restricted_level': data['restricted_level'],
        'up_file': data['up_file'],
        'dl_url': data['dl_url'],
        # 'synchronisation': data['synchronisation'],
        # 'sync_frequency': data['sync_frequency'],
        'referenced_url': data['referenced_url'],
        # 'ftp_file': data['ftp_file'],
        'crs': data['crs'],
        'encoding': data.get('encoding') or None,
        'extractable': data['extractable'],
        'ogc_services': data['ogc_services'],
        'geo_restriction': data['geo_restriction'],
        }

    profiles_allowed = None
    organisations_allowed = None
    if data['restricted_level'] == 'only_allowed_users':
        profiles_allowed = data['profiles_allowed']
    if data['restricted_level'] == 'same_organization':
        organisations_allowed = [form._dataset.organisation]
    if data['restricted_level'] == 'any_organization':
        organisations_allowed = data['organisations_allowed']

    memory_up_file = request.FILES.get('up_file')
    file_extras = memory_up_file and {
        'mimetype': memory_up_file.content_type,
        'resource_type': memory_up_file.name,
        'size': memory_up_file.size} or None

    try:
        with transaction.atomic():
            save_opts = {
                'current_user': user,
                'file_extras': file_extras,
                'synchronize': True}
            if resource:
                for k, v in kvp.items():
                    setattr(resource, k, v)
            else:
                resource = Resource.default.create(save_opts=save_opts, **kvp)
            if organisations_allowed:
                resource.organisations_allowed = organisations_allowed
            if profiles_allowed:
                resource.profiles_allowed = profiles_allowed
                save_opts['synchronize'] = True
                save_opts['file_extras'] = None  # IMPORTANT
            resource.save(**save_opts)
    except ValidationError as e:
        if e.code == 'crs':
            form.add_error(e.code, '')
            form.add_error('__all__', e.message)
        elif e.code == 'encoding':
            form.add_error(e.code, '')
            form.add_error('__all__', e.message)
        else:
            form.add_error(e.code, e.message)
    except CkanBaseError as e:
        form.add_error('__all__', e.__str__())
    else:
        if resource_id:
            send_resource_update_mail(user, resource)
        else:
            send_resource_creation_mail(user, resource)
        return resource
    raise GenericException(details=form._errors)
Example #5
0
def handle_pust_request(request, dataset_name=None):
    # name -> slug
    # published -> private
    user = request.user
    dataset = None
    if dataset_name:
        for instance in handler_get_request(request):
            if instance.slug == dataset_name:
                dataset = instance
                break
        if not instance:
            raise Http404()

    # TODO: Vérifier les droits

    data = getattr(request, request.method).dict()

    organisation_slug = data.get('organisation')
    if organisation_slug:
        try:
            organisation = Organisation.objects.get(slug=organisation_slug)
        except Organisation.DoesNotExist as e:
            raise GenericException(details=e.__str__())
    elif dataset:
        organisation = dataset.organisation
    else:
        organisation = None

    license_slug = data.get('license')
    if data.get('license'):
        try:
            license = License.objects.get(slug=license_slug)
        except License.DoesNotExist as e:
            raise GenericException(details=e.__str__())
    elif dataset:
        license = dataset.license
    else:
        license = None

    data_form = {
        'title': data.get('title', dataset and dataset.title),
        'slug': data.get('name', slugify(data.get('title'))),
        'description': data.get('description'),
        # 'thumbnail' -> request.FILES
        'keywords': data.get('keywords'),
        'categories': data.get('categories'),
        'date_creation': data.get('date_creation'),
        'date_modification': data.get('date_modification'),
        'date_publication': data.get('date_publication'),
        'update_frequency': data.get('update_frequency'),
        # 'geocover'
        'granularity': data.get('granularity', 'indefinie'),
        'organisation': organisation.pk,
        'license': license.pk,
        'support': data.get('support', True),
        'data_type': data.get('type'),
        'owner_name': data.get('owner_name'),
        'owner_email': data.get('owner_email'),
        'broadcaster_name': data.get('broadcaster_name'),
        'broadcaster_email': data.get('broadcaster_email'),
        'published': not data.get('private', False),
    }

    pk = dataset and dataset.pk or None
    include = {'user': user, 'id': pk, 'identification': pk and True or False}
    form = Form(data_form, request.FILES, instance=dataset, include=include)
    if not form.is_valid():
        raise GenericException(details=form._errors)

    data = form.cleaned_data
    kvp = {
        'title': data['title'],
        'slug': data['slug'],
        'description': data['description'],
        'thumbnail': data['thumbnail'],
        # keywords
        # categories
        'date_creation': data['date_creation'],
        'date_modification': data['date_modification'],
        'date_publication': data['date_publication'],
        'update_frequency': data['update_frequency'],
        'geocover': data['geocover'],
        'granularity': data['granularity'],
        'organisation': data['organisation'],
        'license': data['license'],
        'support': data['support'],
        # data_type
        'owner_email': data['owner_email'],
        'owner_name': data['owner_name'],
        'broadcaster_name': data['broadcaster_name'],
        'broadcaster_email': data['broadcaster_email'],
        'published': data['published'],
    }

    try:
        with transaction.atomic():
            if dataset:
                for k, v in kvp.items():
                    setattr(dataset, k, v)
            else:
                kvp['editor'] = user
                save_opts = {'current_user': user, 'synchronize': False}
                dataset = Dataset.default.create(save_opts=save_opts, **kvp)

            dataset.categories.set(data.get('categories', []), clear=True)
            keywords = data.get('keywords')
            if keywords:
                dataset.keywords.clear()
                for k in keywords:
                    dataset.keywords.add(k)
            dataset.data_type.set(data.get('data_type', []), clear=True)
            dataset.save(current_user=user, synchronize=True)
    except ValidationError as e:
        form.add_error('__all__', e.__str__())
    except CkanBaseError as e:
        form.add_error('__all__', e.__str__())
    else:
        if dataset_name:
            send_dataset_update_mail(user, dataset)
        else:
            send_dataset_creation_mail(user, dataset)
        return dataset
    raise GenericException(details=form.__str__())
Example #6
0
def handle_pust_request(request, dataset_name=None):
    # name -> slug
    # type -> data_type
    # categories/category -> categories
    # private -> published

    user = request.user
    dataset = None
    if dataset_name:
        for instance in handler_get_request(request):
            if instance.slug == dataset_name:
                dataset = instance
                break
        if not instance:
            raise Http404()

    query_data = getattr(request, request.method)  # QueryDict

    # Forcer l'éditeur (attention privilège d'admin)
    editor = None
    if user.profile.is_admin:
        editor = query_data.pop('editor', None)
        if editor:
            try:
                editor = User.objects.get(username=editor[-1])
            except User.DoesNotExist as e:
                raise GenericException(details={'editor': e.__str__()})

    # slug/name
    slug = query_data.pop('name', dataset and [dataset.slug])
    if slug:
        query_data.__setitem__('slug', slug[-1])

    # `title` est obligatoire
    title = query_data.pop('title', dataset and [dataset.title])
    if title:
        query_data.__setitem__('title', title[-1])

    # `organisation`
    organisation_slug = query_data.pop('organisation', None)
    if organisation_slug:
        try:
            organisation = Organisation.objects.get(slug=organisation_slug[-1])
        except Organisation.DoesNotExist as e:
            raise GenericException(details=e.__str__())
    elif dataset:
        organisation = dataset.organisation
    else:
        organisation = None
    if organisation:
        query_data.__setitem__('organisation', organisation.pk)

    # `licence`
    license_slug = query_data.pop('license', None)
    if license_slug:
        try:
            license = License.objects.get(slug=license_slug[-1])
        except License.DoesNotExist as e:
            raise GenericException(details=e.__str__())
    elif dataset:
        license = dataset.license
    else:
        license = None
    if license:
        query_data.__setitem__('license', license.pk)

    # `categories`
    category_slugs = query_data.pop('categories',
                                    query_data.pop('category', None))
    if category_slugs:
        try:
            categories = Category.objects.filter(slug__in=category_slugs)
        except Category.DoesNotExist as e:
            raise GenericException(details=e.__str__())
    elif dataset:
        categories = dataset.categories.all()
    else:
        categories = None
    if categories:
        query_data.setlist('categories',
                           [instance.pk for instance in categories])

    # `data_type`
    data_type_slugs = query_data.pop(
        'types', query_data.pop('type', query_data.pop('data_type', None)))
    if data_type_slugs:
        try:
            data_type = DataType.objects.filter(slug__in=data_type_slugs)
        except DataType.DoesNotExist as e:
            raise GenericException(details=e.__str__())
    elif dataset:
        data_type = dataset.data_type.all()
    else:
        data_type = None
    if data_type:
        query_data.setlist('data_type',
                           [instance.pk for instance in data_type])

    # `keywords`
    keyword_tags = query_data.pop('keywords', query_data.pop('keyword', None))
    if keyword_tags:
        query_data.__setitem__('keywords', ','.join(keyword_tags))

    # `published` or `private`
    published = query_data.pop('published', None)
    private = query_data.pop('private', None)
    if (published and published[-1].lower() in ('on', 'true',)) or \
            (private and private[-1].lower() in ('off', 'false',)):
        query_data.__setitem__('published', True)
    elif (published and published[-1].lower() in ('off', 'false',)) or \
            (private and private[-1].lower() in ('on', 'true',)):
        query_data.__setitem__('published', False)

    pk = dataset and dataset.pk or None
    include = {
        'user': editor or user,
        'id': pk,
        'identification': pk and True or False
    }

    # TODO: Extent
    extent = query_data.pop('extent', None)

    form = Form(query_data, request.FILES, instance=dataset, include=include)
    if not form.is_valid():
        raise GenericException(details=form._errors)

    data = form.cleaned_data
    kvp = {
        'title': data['title'],
        'slug': data['slug'],
        'description': data['description'],
        'thumbnail': data['thumbnail'],
        # keywords
        # categories
        'date_creation': data['date_creation'],
        'date_modification': data['date_modification'],
        'date_publication': data['date_publication'],
        'update_frequency': data['update_frequency'],
        'geocover': data['geocover'],
        'granularity': data['granularity'],
        'organisation': data['organisation'],
        'license': data['license'],
        'support': data['support'],
        # data_type
        'owner_email': data['owner_email'],
        'owner_name': data['owner_name'],
        'broadcaster_name': data['broadcaster_name'],
        'broadcaster_email': data['broadcaster_email'],
        'published': data['published'],
    }

    try:
        with transaction.atomic():
            if dataset:
                for k, v in kvp.items():
                    setattr(dataset, k, v)
            else:
                kvp['editor'] = editor or user
                save_opts = {'current_user': user, 'synchronize': False}
                dataset = Dataset.default.create(save_opts=save_opts, **kvp)
            # categories
            categories = Category.objects.filter(pk__in=data.get('categories'))
            dataset.categories.set(categories, clear=True)
            # data_type
            data_type = DataType.objects.filter(pk__in=data.get('data_type'))
            dataset.data_type.set(data_type, clear=True)
            # keywords
            keywords = data.get('keywords')
            if keywords:
                dataset.keywords.clear()
                for k in keywords:
                    dataset.keywords.add(k)
            dataset.save(current_user=user, synchronize=True)
    except ValidationError as e:
        form.add_error('__all__', e.__str__())
    except CkanBaseError as e:
        form.add_error('__all__', e.__str__())
    else:
        if dataset_name:
            send_dataset_update_mail(user, dataset)
        else:
            send_dataset_creation_mail(user, dataset)
        return dataset
    raise GenericException(details=form.__str__())
Example #7
0
def handle_pust_request(request, username=None):

    user = None
    if username:
        user = get_object_or_404(User, username=username)

    query_data = getattr(request, request.method)  # QueryDict

    # `first_name` est obligatoire
    first_name = query_data.pop('first_name', user and [user.first_name])
    if first_name:
        query_data.__setitem__('first_name', first_name[-1])

    # `last_name` est obligatoire
    last_name = query_data.pop('last_name', user and [user.last_name])
    if last_name:
        query_data.__setitem__('last_name', last_name[-1])

    # `email` est obligatoire
    email = query_data.pop('email', user and [user.email])
    if email:
        query_data.__setitem__('email', email[-1])

    # organisation
    organisation_slug = query_data.pop('organisation', None)
    if organisation_slug:
        try:
            organisation = Organisation.objects.get(slug=organisation_slug[-1])
        except Organisation.DoesNotExist as e:
            raise GenericException(details=e.__str__())
    elif user and user.profile:
        organisation = user.profile.organisation
    else:
        organisation = None
    if organisation:
        query_data.__setitem__('organisation', organisation.pk)

    password = query_data.pop('password', None)
    if password:
        query_data.__setitem__('password1', password[-1])
        query_data.__setitem__('password2', password[-1])

    if user:
        form = UpdateAccountForm(query_data, instance=user)
    else:
        form = SignUpForm(query_data, unlock_terms=True)
    if not form.is_valid():
        raise GenericException(details=form._errors)
    try:
        with transaction.atomic():
            if user:
                phone = form.cleaned_data.pop('phone', None)
                for k, v in form.cleaned_data.items():
                    if k == 'password':
                        # user.set_password(v)
                        pass
                    else:
                        setattr(user, k, v)
                user.save()
                if phone:
                    user.profile.phone = phone
                    user.profile.save
                CkanHandler.update_user(user)
            else:
                user = User.objects.create_user(**form.cleaned_user_data)
                profile_data = {**form.cleaned_profile_data, **{'user': user, 'is_active': True}}
                Profile.objects.create(**profile_data)
                CkanHandler.add_user(user, form.cleaned_user_data['password'], state='active')
    except (ValidationError, CkanBaseError) as e:
        raise GenericException(details=e.__str__())

    if organisation:
        user.profile.membership = True
        user.profile.save(update_fields=['membership'])

    # contribute
    contribute_for = None
    contribute_for_slugs = query_data.pop('contribute', [])
    if contribute_for_slugs:
        try:
            contribute_for = Organisation.objects.filter(slug__in=contribute_for_slugs)
        except Organisation.DoesNotExist as e:
            raise GenericException(details=e.__str__())

    # referent
    referent_for = None
    referent_for_slugs = query_data.pop('referent', None)
    if referent_for_slugs:
        try:
            referent_for = Organisation.objects.filter(slug__in=referent_for_slugs)
        except Organisation.DoesNotExist as e:
            raise GenericException(details=e.__str__())

    if contribute_for:
        for organisation in contribute_for:
            try:
                LiaisonsContributeurs.objects.get_or_create(
                    profile=user.profile, organisation=organisation,
                    defaults={'validated_on': timezone.now()}
                )
            except IntegrityError:
                pass
            else:
                AccountActions.objects.get_or_create(
                    action='confirm_contribution', organisation=organisation,
                    profile=user.profile, defaults={'closed': timezone.now()}
                )

    if referent_for:
        for organisation in referent_for:
            try:
                LiaisonsReferents.objects.get_or_create(
                    profile=user.profile, organisation=organisation,
                    defaults={'validated_on': timezone.now()})
            except IntegrityError:
                pass
            else:
                AccountActions.objects.get_or_create(
                    action='confirm_referent', organisation=organisation,
                    profile=user.profile, defaults={'closed': timezone.now()}
                )

    return user
Example #8
0
def handle_pust_request(request, dataset_name, resource_id=None):
    # title -> name
    # description -> description
    # language -> lang
    # format -> format_type.pk
    # type -> data_type raw|annexe|service
    # restricted_level -> public|registered|only_allowed_users|same_organization|any_organization
    # restricted_list -> list of: user.username|organisation.slug
    # up_file -> {File}
    user = request.user
    dataset = get_object_or_404_extended(Dataset,
                                         user,
                                         include={'slug': dataset_name})
    resource = None
    if resource_id:
        resource = get_object_or_404(Resource, ckan_id=resource_id)

    # TODO: Vérifier les droits

    data = getattr(request, request.method).dict()

    restricted_list = data.get('restricted_list', [])
    profiles_allowed = None
    organisations_allowed = None

    restricted_level = data.get('restricted_level')
    if restricted_level == 'only_allowed_users':
        profiles_allowed = User.objects.filter(username__in=restricted_list)
    elif restricted_level in ('same_organization', 'any_organization'):
        organisations_allowed = Organisation.objects.filter(
            slug__in=restricted_list)

    data_form = {
        'title': data.get('title'),
        'description': data.get('description'),
        'lang': data.get('language', 'french'),
        'format_type': data.get('format'),
        'data_type': data.get('type'),
        'restricted_level': restricted_level,
        'profiles_allowed': profiles_allowed,
        'organisations_allowed': organisations_allowed,
        # 'up_file': '',
        # 'dl_url': '',
        # 'synchronisation': '',
        # 'sync_frequency': '',
        # 'referenced_url': '',
        # 'ftp_file': '',
        'crs': data.get('crs', None),
        'encoding': data.get('encoding', None),
        # 'extractable': data.get('extractable'),
        # 'ogc_services': data.get('ogc_services'),
        # 'geo_restriction': data.get('geo_restriction'),
        # 'last_update': data.get('last_update'),
    }

    form = Form(data_form,
                request.FILES,
                instance=resource,
                dataset=dataset,
                user=user)
    if not form.is_valid():
        raise GenericException(details=form._errors)

    data = form.cleaned_data
    kvp = {
        'dataset': dataset,
        'title': data['title'],
        'description': data['description'],
        'lang': data['lang'],
        'data_type': data['data_type'],
        'format_type': data['format_type'],
        'last_update': data['last_update'],
        'restricted_level': data['restricted_level'],
        'up_file': data['up_file'],
        # 'dl_url': data['dl_url'],
        # 'synchronisation': data['synchronisation'],
        # 'sync_frequency': data['sync_frequency'],
        # 'referenced_url': data['referenced_url'],
        # 'ftp_file': data['ftp_file'],
        'crs': data['crs'],
        'encoding': data.get('encoding') or None,
        'extractable': data['extractable'],
        'ogc_services': data['ogc_services'],
        'geo_restriction': data['geo_restriction'],
    }

    profiles_allowed = None
    organisations_allowed = None
    if data['restricted_level'] == 'only_allowed_users':
        profiles_allowed = data['profiles_allowed']
    if data['restricted_level'] == 'same_organization':
        organisations_allowed = [form._dataset.organisation]
    if data['restricted_level'] == 'any_organization':
        organisations_allowed = data['organisations_allowed']

    memory_up_file = request.FILES.get('up_file')
    file_extras = memory_up_file and {
        'mimetype': memory_up_file.content_type,
        'resource_type': memory_up_file.name,
        'size': memory_up_file.size
    } or None

    try:
        with transaction.atomic():
            save_opts = {
                'current_user': user,
                'file_extras': file_extras,
                'synchronize': True
            }
            if not id:
                resource = Resource.default.create(save_opts=save_opts, **kvp)
            else:
                resource = Resource.objects.get(pk=id)
                for k, v in kvp.items():
                    setattr(resource, k, v)
            if organisations_allowed:
                resource.organisations_allowed = organisations_allowed
            if profiles_allowed:
                resource.profiles_allowed = profiles_allowed
                save_opts['synchronize'] = True
                save_opts['file_extras'] = None  # IMPORTANT
                resource.save(**save_opts)
    except ValidationError as e:
        if e.code == 'crs':
            form.add_error(e.code, '')
            form.add_error('__all__', e.message)
        elif e.code == 'encoding':
            form.add_error(e.code, '')
            form.add_error('__all__', e.message)
        else:
            form.add_error(e.code, e.message)
    except CkanBaseError as e:
        form.add_error('__all__', e.__str__())
    else:
        if resource_id:
            send_resource_update_mail(user, resource)
        else:
            send_resource_creation_mail(user, resource)
        return resource
    raise GenericException(details=form._errors)
Example #9
0
def handle_pust_request(request, username=None):

    user = None
    if username:
        user = get_object_or_404(User, username=username)

    data = getattr(request, request.method).dict()

    organisation = data.get('organisation')
    if organisation:
        try:
            organisation = Organisation.objects.get(slug=organisation).pk
        except Organisation.DoesNotExist:
            details = {'organisation': ["L'organisation n'existe pas."]}
            raise GenericException(details=details)

    data_form = {
        'username': data.get('username'),
        'first_name': data.get('first_name'),
        'last_name': data.get('last_name'),
        'email': data.get('email'),
        'phone': data.get('phone'),
        'organisation': organisation,
        'password1': data.get('password'),
        'password2': data.get('password'),
    }

    if username:
        form = UpdateAccountForm(data_form, instance=user)
    else:
        form = SignUpForm(data_form, unlock_terms=True)
    if not form.is_valid():
        raise GenericException(details=form._errors)
    try:
        with transaction.atomic():
            if username:
                phone = form.cleaned_data.pop('phone', None)
                for k, v in form.cleaned_data.items():
                    setattr(user, k, v)
                user.save()
                if phone:
                    user.profile.phone = phone
                    user.profile.save
                CkanHandler.update_user(user)
            else:
                user = User.objects.create_user(**form.cleaned_user_data)
                profile_data = {
                    **form.cleaned_profile_data,
                    **{
                        'user': user,
                        'is_active': True
                    }
                }
                Profile.objects.create(**profile_data)
                CkanHandler.add_user(user,
                                     form.cleaned_user_data['password'],
                                     state='active')
    except (ValidationError, CkanBaseError) as e:
        raise GenericException(details=e.__str__())

    return user