Python django.core.exceptions.ObjectDoesNotExist() Examples

The following are 30 code examples for showing how to use django.core.exceptions.ObjectDoesNotExist(). 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.core.exceptions , or try the search function .

Example 1
Project: pyconkr-2015   Author: pythonkr   File: views.py    License: MIT License 6 votes vote down vote up
def login_req(request, token):
    time_threshold = datetime.now() - timedelta(hours=1)

    try:
        token = EmailToken.objects.get(token=token,
                                       created__gte=time_threshold)
    except ObjectDoesNotExist:
        return render(request, 'login_notvalidtoken.html',
                      {'title': _('Not valid token')})
    email = token.email

    # Create user automatically by email as id, token as password
    try:
        user = User.objects.get(email=email)
    except ObjectDoesNotExist:
        user = User.objects.create_user(email, email, token)
        user.save()

    token.delete()

    # Set backend manually
    user.backend = 'django.contrib.auth.backends.ModelBackend'
    user_login(request, user)

    return redirect(reverse('index')) 
Example 2
Project: arches   Author: archesproject   File: resource.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def delete(self, request, resourceid=None):
        lang = request.GET.get("lang", settings.LANGUAGE_CODE)
        se = SearchEngineFactory().create()
        req = dict(request.GET)
        ids_to_delete = req["resourcexids[]"]
        root_resourceinstanceid = req["root_resourceinstanceid"]
        for resourcexid in ids_to_delete:
            try:
                ret = models.ResourceXResource.objects.get(pk=resourcexid).delete()
            except ObjectDoesNotExist:
                logger.exception(_("Unable to delete. Relationship does not exist"))
        start = request.GET.get("start", 0)
        se.es.indices.refresh(index=se._add_prefix("resource_relations"))
        resource = Resource.objects.get(pk=root_resourceinstanceid[0])
        page = 1 if request.GET.get("page") == "" else int(request.GET.get("page", 1))
        related_resources = resource.get_related_resources(lang=lang, start=start, limit=1000, page=page)
        ret = []

        if related_resources is not None:
            ret = self.paginate_related_resources(related_resources, page, request)

        return JSONResponse(ret, indent=4) 
Example 3
Project: arches   Author: archesproject   File: datatypes.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def validate(self, value, row_number=None, source="", node=None, nodeid=None):
        errors = []
        if value is not None:
            resourceXresourceIds = self.get_id_list(value)
            for resourceXresourceId in resourceXresourceIds:
                resourceid = resourceXresourceId["resourceId"]
                try:
                    models.ResourceInstance.objects.get(pk=resourceid)
                except ObjectDoesNotExist:
                    errors.append(
                        {
                            "type": "WARNING",
                            "message": f"The resource id: {resourceid} does not exist in the system. The data for this card will \
                                be available in the system once resource {resourceid} is loaded.",
                        }
                    )
        return errors 
Example 4
Project: StormOnline   Author: stormsha   File: editable.py    License: Apache License 2.0 6 votes vote down vote up
def _get_new_field_html(self, field_name):
        try:
            f, attr, value = lookup_field(field_name, self.org_obj, self)
        except (AttributeError, ObjectDoesNotExist):
            return EMPTY_CHANGELIST_VALUE
        else:
            allow_tags = False
            if f is None:
                allow_tags = getattr(attr, 'allow_tags', False)
                boolean = getattr(attr, 'boolean', False)
                if boolean:
                    allow_tags = True
                    text = boolean_icon(value)
                else:
                    text = smart_text(value)
            else:
                if isinstance(f.rel, models.ManyToOneRel):
                    field_val = getattr(self.org_obj, f.name)
                    if field_val is None:
                        text = EMPTY_CHANGELIST_VALUE
                    else:
                        text = field_val
                else:
                    text = display_for_field(value, f)
            return mark_safe(text) if allow_tags else conditional_escape(text) 
Example 5
Project: GTDWeb   Author: lanbing510   File: helpers.py    License: GNU General Public License v2.0 6 votes vote down vote up
def contents(self):
        from django.contrib.admin.templatetags.admin_list import _boolean_icon
        from django.contrib.admin.views.main import EMPTY_CHANGELIST_VALUE
        field, obj, model_admin = self.field['field'], self.form.instance, self.model_admin
        try:
            f, attr, value = lookup_field(field, obj, model_admin)
        except (AttributeError, ValueError, ObjectDoesNotExist):
            result_repr = EMPTY_CHANGELIST_VALUE
        else:
            if f is None:
                boolean = getattr(attr, "boolean", False)
                if boolean:
                    result_repr = _boolean_icon(value)
                else:
                    result_repr = smart_text(value)
                    if getattr(attr, "allow_tags", False):
                        result_repr = mark_safe(result_repr)
                    else:
                        result_repr = linebreaksbr(result_repr)
            else:
                if isinstance(f.rel, ManyToManyRel) and value is not None:
                    result_repr = ", ".join(map(six.text_type, value.all()))
                else:
                    result_repr = display_for_field(value, f)
        return conditional_escape(result_repr) 
Example 6
Project: GTDWeb   Author: lanbing510   File: layermapping.py    License: GNU General Public License v2.0 6 votes vote down vote up
def verify_fk(self, feat, rel_model, rel_mapping):
        """
        Given an OGR Feature, the related model and its dictionary mapping,
        this routine will retrieve the related model for the ForeignKey
        mapping.
        """
        # TODO: It is expensive to retrieve a model for every record --
        #  explore if an efficient mechanism exists for caching related
        #  ForeignKey models.

        # Constructing and verifying the related model keyword arguments.
        fk_kwargs = {}
        for field_name, ogr_name in rel_mapping.items():
            fk_kwargs[field_name] = self.verify_ogr_field(feat[ogr_name], rel_model._meta.get_field(field_name))

        # Attempting to retrieve and return the related model.
        try:
            return rel_model.objects.using(self.using).get(**fk_kwargs)
        except ObjectDoesNotExist:
            raise MissingForeignKey(
                'No ForeignKey %s model found with keyword arguments: %s' %
                (rel_model.__name__, fk_kwargs)
            ) 
Example 7
Project: GTDWeb   Author: lanbing510   File: fields.py    License: GNU General Public License v2.0 6 votes vote down vote up
def __get__(self, instance, instance_type=None):
        if instance is None:
            return self

        try:
            return getattr(instance, self.cache_attr)
        except AttributeError:
            rel_obj = None

            # Make sure to use ContentType.objects.get_for_id() to ensure that
            # lookups are cached (see ticket #5570). This takes more code than
            # the naive ``getattr(instance, self.ct_field)``, but has better
            # performance when dealing with GFKs in loops and such.
            f = self.model._meta.get_field(self.ct_field)
            ct_id = getattr(instance, f.get_attname(), None)
            if ct_id is not None:
                ct = self.get_content_type(id=ct_id, using=instance._state.db)
                try:
                    rel_obj = ct.get_object_for_this_type(pk=getattr(instance, self.fk_field))
                except ObjectDoesNotExist:
                    pass
            setattr(instance, self.cache_attr, rel_obj)
            return rel_obj 
Example 8
Project: readux   Author: ecds   File: annotations.py    License: MIT License 6 votes vote down vote up
def get(self, request, *args, **kwargs):
        username = kwargs['username']
        try:
            owner = User.objects.get(username=username)
            if self.request.user == owner: 
                return JsonResponse(
                    json.loads(
                        serialize(
                            'user_annotation_list',
                            self.get_queryset(),
                            owners=[owner]
                        )
                    ),
                    safe=False
                )
            else:
                return JsonResponse(status=401, data={"Permission to see annotations not allowed for logged in user.": username})

        except ObjectDoesNotExist:
            # attempt to get annotations for non-existent user
            return JsonResponse(status=404, data={"User not found.": username})
        return JsonResponse(status=200, data={}) 
Example 9
Project: safe-relay-service   Author: gnosis   File: test_safe_creation_service.py    License: MIT License 6 votes vote down vote up
def test_deploy_create2_safe_tx(self):
        random_safe_address = Account.create().address
        with self.assertRaises(ObjectDoesNotExist):
            self.safe_creation_service.deploy_create2_safe_tx(random_safe_address)

        owner_accounts = [Account.create() for _ in range(4)]
        owners = [owner_account.address for owner_account in owner_accounts]

        salt_nonce = 17051863
        threshold = 2
        payment_token = None
        safe_creation_2 = self.safe_creation_service.create2_safe_tx(salt_nonce, owners, threshold, payment_token)
        safe_address = safe_creation_2.safe_id
        self.assertFalse(self.ethereum_client.is_contract(safe_address))
        self.assertIsNone(safe_creation_2.tx_hash)
        with self.assertRaisesMessage(NotEnoughFundingForCreation, str(safe_creation_2.payment)):
            self.safe_creation_service.deploy_create2_safe_tx(safe_address)
        self.send_ether(safe_address, safe_creation_2.payment)
        new_safe_creation_2 = self.safe_creation_service.deploy_create2_safe_tx(safe_address)
        self.assertTrue(new_safe_creation_2.tx_hash)
        self.assertTrue(self.ethereum_client.is_contract(safe_address))

        # If already deployed it will return `SafeCreation2`
        another_safe_creation2 = self.safe_creation_service.deploy_create2_safe_tx(safe_address)
        self.assertEqual(another_safe_creation2, new_safe_creation_2) 
Example 10
Project: peering-manager   Author: respawner   File: testing.py    License: Apache License 2.0 6 votes vote down vote up
def test_delete_object(self):
            instance = self.model.objects.first()

            request = {
                "path": self._get_url("delete", instance),
                "data": {"confirm": True},
                "follow": False,  # Do not follow 302 redirects
            }

            # Attempt to make the request without required permissions
            self.assertStatus(self.client.post(**request), 403)

            # Assign the required permission and submit again
            self.add_permissions(
                f"{self.model._meta.app_label}.delete_{self.model._meta.model_name}"
            )
            response = self.client.post(**request)
            self.assertStatus(response, 302)

            with self.assertRaises(ObjectDoesNotExist):
                self.model.objects.get(pk=instance.pk) 
Example 11
Project: linkedevents   Author: City-of-Helsinki   File: kulke.py    License: MIT License 6 votes vote down vote up
def import_keywords(self):
        logger.info("Importing Kulke categories as keywords")
        categories = self.parse_kulke_categories()
        for kid, value in categories.items():
            try:
                # if the keyword exists, update the name if needed
                word = Keyword.objects.get(id=make_kulke_id(kid))
                if word.name != value['text']:
                    word.name = value['text']
                    word.save()
                if word.publisher_id != self.organization.id:
                    word.publisher = self.organization
                    word.save()
            except ObjectDoesNotExist:
                # if the keyword does not exist, save it for future use
                Keyword.objects.create(
                    id=make_kulke_id(kid),
                    name=value['text'],
                    data_source=self.data_source,
                    publisher=self.organization
                ) 
Example 12
Project: silverstrike   Author: agstrike   File: createtestdata.py    License: MIT License 6 votes vote down vote up
def handle(self, *args, **options):
        if options['prune']:
            self._prune()
        self._initialize()
        today = date.today()
        try:
            start_date = Transaction.objects.filter(
                date__lte=today).latest('date').date.replace(day=1)
        except ObjectDoesNotExist:
            start_date = date(2016, 1, 1)

        while start_date < today:
            self._create_monthly(start_date.year, start_date.month)
            start_date += relativedelta(months=+1)
        Transaction.objects.bulk_create(self.transactions)
        Split.objects.bulk_create(self.splits) 
Example 13
Project: bioforum   Author: reBiocoder   File: helpers.py    License: MIT License 6 votes vote down vote up
def contents(self):
        from django.contrib.admin.templatetags.admin_list import _boolean_icon
        field, obj, model_admin = self.field['field'], self.form.instance, self.model_admin
        try:
            f, attr, value = lookup_field(field, obj, model_admin)
        except (AttributeError, ValueError, ObjectDoesNotExist):
            result_repr = self.empty_value_display
        else:
            if f is None:
                boolean = getattr(attr, "boolean", False)
                if boolean:
                    result_repr = _boolean_icon(value)
                else:
                    if hasattr(value, "__html__"):
                        result_repr = value
                    else:
                        result_repr = linebreaksbr(value)
            else:
                if isinstance(f.remote_field, ManyToManyRel) and value is not None:
                    result_repr = ", ".join(map(str, value.all()))
                else:
                    result_repr = display_for_field(value, f, self.empty_value_display)
                result_repr = linebreaksbr(result_repr)
        return conditional_escape(result_repr) 
Example 14
Project: bioforum   Author: reBiocoder   File: layermapping.py    License: MIT License 6 votes vote down vote up
def verify_fk(self, feat, rel_model, rel_mapping):
        """
        Given an OGR Feature, the related model and its dictionary mapping,
        retrieve the related model for the ForeignKey mapping.
        """
        # TODO: It is expensive to retrieve a model for every record --
        #  explore if an efficient mechanism exists for caching related
        #  ForeignKey models.

        # Constructing and verifying the related model keyword arguments.
        fk_kwargs = {}
        for field_name, ogr_name in rel_mapping.items():
            fk_kwargs[field_name] = self.verify_ogr_field(feat[ogr_name], rel_model._meta.get_field(field_name))

        # Attempting to retrieve and return the related model.
        try:
            return rel_model.objects.using(self.using).get(**fk_kwargs)
        except ObjectDoesNotExist:
            raise MissingForeignKey(
                'No ForeignKey %s model found with keyword arguments: %s' %
                (rel_model.__name__, fk_kwargs)
            ) 
Example 15
Project: black-widow   Author: offensive-hub   File: abstract_job_view.py    License: GNU General Public License v3.0 6 votes vote down vote up
def _get_job(self, request, redirect_url: str):
        """
        Show the requested job
        :type request: django.core.handlers.wsgi.WSGIRequest
        :param redirect_url: The url to redirect the request in case of errors
        :return: django.http.HttpResponse
        """
        request_params: dict = request.GET.dict()

        try:
            job_id = int(request_params.get('id'))
        except (ValueError, TypeError) as e:
            Log.error(str(e))
            return redirect(redirect_url)

        Log.info("Showing job #" + str(job_id))

        try:
            job = self.model_class.objects.get(id=job_id)
        except ObjectDoesNotExist:
            return redirect(redirect_url)

        return render(request, self.template_name, {
            'job': job
        }) 
Example 16
Project: fermentrack   Author: thorrak   File: views.py    License: MIT License 6 votes vote down vote up
def external_push_delete(request, push_target_id):
    # TODO - Add user permissioning
    # if not request.user.has_perm('app.add_device'):
    #     messages.error(request, 'Your account is not permissioned to add devices. Please contact an admin')
    #     return redirect("/")

    try:
        push_target = GenericPushTarget.objects.get(id=push_target_id)
    except ObjectDoesNotExist:
        messages.error(request, "External push target {} does not exist".format(push_target_id))
        return redirect('external_push_list')

    message = 'Push target {} has been deleted'.format(push_target.name)
    push_target.delete()
    messages.success(request, message)

    return redirect('external_push_list') 
Example 17
Project: fermentrack   Author: thorrak   File: views.py    License: MIT License 6 votes vote down vote up
def external_push_brewers_friend_view(request, push_target_id):
    # TODO - Add user permissioning
    # if not request.user.has_perm('app.add_device'):
    #     messages.error(request, 'Your account is not permissioned to add devices. Please contact an admin')
    #     return redirect("/")

    try:
        push_target = BrewersFriendPushTarget.objects.get(id=push_target_id)
    except ObjectDoesNotExist:
        messages.error(request, "Brewers's Friend push target {} does not exist".format(push_target_id))
        return redirect('external_push_list')

    if request.POST:
        form = forms.BrewersFriendPushTargetModelForm(request.POST, instance=push_target)
        if form.is_valid():
            updated_push_target = form.save()
            messages.success(request, 'Updated push target')
            return redirect('external_push_list')

        messages.error(request, 'Unable to update push target')

    form = forms.BrewersFriendPushTargetModelForm(instance=push_target)

    return render(request, template_name='external_push/brewers_friend_push_target_view.html',
                  context={'push_target': push_target, 'form': form}) 
Example 18
Project: fermentrack   Author: thorrak   File: views.py    License: MIT License 6 votes vote down vote up
def external_push_brewers_friend_delete(request, push_target_id):
    # TODO - Add user permissioning
    # if not request.user.has_perm('app.add_device'):
    #     messages.error(request, 'Your account is not permissioned to add devices. Please contact an admin')
    #     return redirect("/")

    try:
        push_target = BrewersFriendPushTarget.objects.get(id=push_target_id)
    except ObjectDoesNotExist:
        messages.error(request, "Brewers's Friend push target {} does not exist".format(push_target_id))
        return redirect('external_push_list')

    message = "Brewers's Friend push target {} has been deleted".format(push_target_id)
    push_target.delete()
    messages.success(request, message)

    return redirect('external_push_list') 
Example 19
Project: fermentrack   Author: thorrak   File: views.py    License: MIT License 6 votes vote down vote up
def external_push_brewfather_view(request, push_target_id):
    # TODO - Add user permissioning
    # if not request.user.has_perm('app.add_device'):
    #     messages.error(request, 'Your account is not permissioned to add devices. Please contact an admin')
    #     return redirect("/")

    try:
        push_target = BrewfatherPushTarget.objects.get(id=push_target_id)
    except ObjectDoesNotExist:
        messages.error(request, "Brewfather push target {} does not exist".format(push_target_id))
        return redirect('external_push_list')

    if request.POST:
        form = forms.BrewfatherPushTargetModelForm(request.POST, instance=push_target)
        if form.is_valid():
            updated_push_target = form.save()
            messages.success(request, 'Updated push target')
            return redirect('external_push_list')

        messages.error(request, 'Unable to update push target')

    form = forms.BrewfatherPushTargetModelForm(instance=push_target)

    return render(request, template_name='external_push/brewfather_push_target_view.html',
                  context={'push_target': push_target, 'form': form}) 
Example 20
Project: fermentrack   Author: thorrak   File: views.py    License: MIT License 6 votes vote down vote up
def external_push_thingspeak_view(request, push_target_id):
    # TODO - Add user permissioning
    # if not request.user.has_perm('app.add_device'):
    #     messages.error(request, 'Your account is not permissioned to add devices. Please contact an admin')
    #     return redirect("/")

    try:
        push_target = ThingSpeakPushTarget.objects.get(id=push_target_id)
    except ObjectDoesNotExist:
        messages.error(request, "ThingSpeak push target {} does not exist".format(push_target_id))
        return redirect('external_push_list')

    if request.POST:
        form = forms.ThingSpeakPushTargetModelForm(request.POST, instance=push_target)
        if form.is_valid():
            updated_push_target = form.save()
            messages.success(request, 'Updated push target')
            return redirect('external_push_list')

        messages.error(request, 'Unable to update push target')

    form = forms.ThingSpeakPushTargetModelForm(instance=push_target)

    return render(request, template_name='external_push/thingspeak_push_target_view.html',
                  context={'push_target': push_target, 'form': form}) 
Example 21
Project: fermentrack   Author: thorrak   File: views.py    License: MIT License 6 votes vote down vote up
def external_push_thingspeak_delete(request, push_target_id):
    # TODO - Add user permissioning
    # if not request.user.has_perm('app.add_device'):
    #     messages.error(request, 'Your account is not permissioned to add devices. Please contact an admin')
    #     return redirect("/")

    try:
        push_target = ThingSpeakPushTarget.objects.get(id=push_target_id)
    except ObjectDoesNotExist:
        messages.error(request, "ThingSpeak push target {} does not exist".format(push_target_id))
        return redirect('external_push_list')

    message = "ThingSpeak push target {} has been deleted".format(push_target_id)
    push_target.delete()
    messages.success(request, message)

    return redirect('external_push_list') 
Example 22
Project: fermentrack   Author: thorrak   File: views.py    License: MIT License 6 votes vote down vote up
def external_push_grainfather_view(request, push_target_id):
    # TODO - Add user permissioning
    # if not request.user.has_perm('app.add_device'):
    #     messages.error(request, 'Your account is not permissioned to add devices. Please contact an admin')
    #     return redirect("/")

    try:
        push_target = GrainfatherPushTarget.objects.get(id=push_target_id)
    except ObjectDoesNotExist:
        messages.error(request, "Grainfather push target {} does not exist".format(push_target_id))
        return redirect('external_push_list')

    if request.POST:
        form = forms.GrainfatherPushTargetModelForm(request.POST, instance=push_target)
        if form.is_valid():
            updated_push_target = form.save()
            messages.success(request, 'Updated push target')
            return redirect('external_push_list')

        messages.error(request, 'Unable to update push target')

    form = forms.GrainfatherPushTargetModelForm(instance=push_target)

    return render(request, template_name='external_push/grainfather_push_target_view.html',
                  context={'push_target': push_target, 'form': form}) 
Example 23
Project: fermentrack   Author: thorrak   File: views.py    License: MIT License 6 votes vote down vote up
def external_push_grainfather_delete(request, push_target_id):
    # TODO - Add user permissioning
    # if not request.user.has_perm('app.add_device'):
    #     messages.error(request, 'Your account is not permissioned to add devices. Please contact an admin')
    #     return redirect("/")

    try:
        push_target = GrainfatherPushTarget.objects.get(id=push_target_id)
    except ObjectDoesNotExist:
        messages.error(request, "Grainfather push target {} does not exist".format(push_target_id))
        return redirect('external_push_list')

    message = "Grainfather push target {} has been deleted".format(push_target_id)
    push_target.delete()
    messages.success(request, message)

    return redirect('external_push_list') 
Example 24
Project: fermentrack   Author: thorrak   File: views.py    License: MIT License 6 votes vote down vote up
def gravity_log_delete(request, log_id):
    # TODO - Add user permissioning
    # if not request.user.has_perm('app.add_beer'):
    #     messages.error(request, 'Your account is not permissioned to add beers. Please contact an admin')
    #     return redirect("/")

    try:
        log_obj = GravityLog.objects.get(id=log_id)

        if log_obj.device:
            if log_obj.device.active_log == log_obj:
                # If the log is currently being logged to, we don't want to trigger a delete
                messages.error(request, u'Requested log is currently in use - Stop logging on device and reattempt')
                return redirect('gravity_log_list')

        log_obj.delete()
        messages.success(request, u'Log "{}" was deleted'.format(log_obj.name))
    except:
        # TODO - Rewrite this to make it more specific (ObjectDoesNotExist error, for example)
        messages.error(request, u'Unable to delete log with ID {}'.format(log_id))
    return redirect('gravity_log_list') 
Example 25
Project: indras_net   Author: gcallah   File: prop_args2.py    License: GNU General Public License v3.0 5 votes vote down vote up
def set_props_from_db(self):
        try:
            params = ABMModel.objects.get(name=self.model_nm).params.all()
            for param in params:
                atype = param.atype
                typed_default_val = self._type_val_if_possible(param.default_val,
                                                               param.atype)
                self.props[param.prop_name] = Prop(val=typed_default_val,
                                                   question=param.question,
                                                   atype=atype,
                                                   default_val=typed_default_val,
                                                   lowval=param.lowval,
                                                   hival=param.hival)
        except ObjectDoesNotExist:
            print("ABMModel not found in db: " + self.model_nm) 
Example 26
Project: django-click   Author: GaretJax   File: params.py    License: MIT License 5 votes vote down vote up
def convert(self, value, param, ctx):
        if value is None:  # NOCOV
            return super(ModelInstance, self).convert(value, param, ctx)
        try:
            return self.qs.get(**{self.lookup: value})
        except ObjectDoesNotExist:
            pass
        # call `fail` outside of exception context to avoid nested exception
        # handling on Python 3
        msg = "could not find {s.name} with {s.lookup}={value}".format(
            s=self, value=value
        )
        self.fail(msg, param, ctx) 
Example 27
Project: django-notifs   Author: danidee10   File: views.py    License: MIT License 5 votes vote down vote up
def post(self, request, *args, **kwargs):
        """Generate the notification."""
        data = loads(request.body)
        message = data['message']

        # Create/retrieve the user
        User = get_user_model()

        try:
            user = User.objects.get(username='demouser')
        except ObjectDoesNotExist:
            user = User.objects.create_user(
                username='demouser', email='example@gmail.com',
                password='mypassword'
            )

        # notification
        args = {
            'source': user, 'source_display_name': user.get_full_name(),
            'recipient': user, 'category': 'Quote', 'action': 'Sent',
            'obj': user.id,
            'short_description': 'You a message: {}'.format(message),
            'url': 'http://example.com', 'channels': ('websocket',)
        }
        notify.send(sender=self.__class__, **args)

        response = JsonResponse({'message': 'Notification generated'})

        self.add_access_control_headers(response)

        return response 
Example 28
Project: gazetteer   Author: LibraryOfCongress   File: views.py    License: MIT License 5 votes vote down vote up
def add_relation(request):
    feature1 = request.GET.get("feature1", None)
    feature2 = request.GET.get("feature2", None)
    relation = request.GET.get("relation", None)
    if feature1 == None or feature2 == None or relation == None:
        return render_to_json_response({'error': 'bad request'})

    if not request.user.is_staff:
        return render_to_json_response({'error': 'insufficient permissions error. try logging in again? are you staff / admin?'})

    feature1 = get_object_or_404_json(Feature, pk=feature1)
    feature2 = get_object_or_404_json(Feature, pk=feature2)
    verb = rel_obj = None
    try:
        rel_obj = Relationship.objects.get(feature1=feature1, feature2=feature2)
        verb = "deleted"
    except ObjectDoesNotExist:
        rel_obj = Relationship(feature1=feature1, feature2=feature2, relationship_type=relation)
        verb = "created"
    if relation == "":
        if verb == "deleted":
            rel_obj.delete()
            if relation == "conflates":
                feature2.is_primary = True
                feature2.save()
        else:
             return render_to_json_response({'error': 'relation is already deleted'})
    else:
        rel_obj.save()
        if relation == "conflates":
            feature2.is_primary = False
            feature2.save()
    return render_to_json_response({'success': 'relation %s successfully.' % verb}) 
Example 29
Project: donation-tracker   Author: GamesDoneQuick   File: user.py    License: Apache License 2.0 5 votes vote down vote up
def user_prize(request, prize):
    try:
        prize = models.Prize.objects.get(pk=prize)
    except ObjectDoesNotExist:
        raise Http404
    if (
        request.user != prize.handler
        and request.user != prize.event.prizecoordinator
        and not request.user.is_superuser
    ):
        return HttpResponse('You are not authorized to view this resource', 403)
    acceptedWinners = (
        prize.get_prize_winners().filter(Q(acceptcount__gte=1)).select_related('winner')
    )
    pendingWinners = (
        prize.get_prize_winners()
        .filter(Q(pendingcount__gte=1))
        .select_related('winner')
    )
    formset = None
    if request.method == 'POST':
        if acceptedWinners.exists():
            formset = forms.PrizeShippingFormSet(
                data=request.POST, queryset=acceptedWinners
            )
            savedForm = find_saved_form(request.POST, len(formset.forms), 'form-saved-')
            formset.extra = 0
            if savedForm is not None:
                targetForm = formset.forms[savedForm]
                if targetForm.is_valid():
                    targetForm.save()
                    targetForm.saved = True
    else:
        if acceptedWinners.exists():
            formset = forms.PrizeShippingFormSet(queryset=acceptedWinners)
            formset.extra = 0
    return views_common.tracker_response(
        request,
        'tracker/contributor_prize.html',
        dict(prize=prize, formset=formset, pendingWinners=pendingWinners),
    ) 
Example 30
Project: donation-tracker   Author: GamesDoneQuick   File: user.py    License: Apache License 2.0 5 votes vote down vote up
def prize_winner(request, prize_win):
    authCode = request.GET.get('auth_code', None)
    try:
        prizeWin = models.PrizeWinner.objects.get(
            pk=prize_win, auth_code__iexact=authCode
        )
    except ObjectDoesNotExist:
        raise Http404
    if request.method == 'POST':
        form = forms.PrizeAcceptanceWithAddressForm(
            instance={'address': prizeWin.winner, 'prizeaccept': prizeWin,},
            data=request.POST,
        )
        if form.is_valid():
            form.save()
        else:
            # this is a special case where we need to reset the model instance
            # for the page to work
            prizeWin = models.PrizeWinner.objects.get(id=prizeWin.id)
    else:
        form = forms.PrizeAcceptanceWithAddressForm(
            instance={'address': prizeWin.winner, 'prizeaccept': prizeWin,}
        )

    return views_common.tracker_response(
        request,
        'tracker/prize_winner.html',
        dict(form=form, prize=prizeWin.prize, prizeWin=prizeWin),
    )