Python django.db.IntegrityError() Examples
The following are 30
code examples of django.db.IntegrityError().
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.db
, or try the search function
.
Example #1
Source File: views.py From certificate-generator-server-archive with GNU General Public License v3.0 | 7 votes |
def create(self, request, *args, **kwargs): serializer = self.serializer_class(data=request.data) jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER try: if serializer.is_valid(raise_exception=True): student = serializer.create(request.data) jwt_token = { 'token': jwt_encode_handler(jwt_payload_handler(student.user)) } return Response(jwt_token, status=status.HTTP_201_CREATED) except IntegrityError: serializer.error_messages = { 'Error': 'Student with that username already exists!'} return Response(serializer.error_messages, status=status.HTTP_400_BAD_REQUEST)
Example #2
Source File: models.py From readux with MIT License | 6 votes |
def set_span_element(sender, instance, **kwargs): if (instance.resource_type in (sender.OCR,)) or (instance.oa_annotation['annotatedBy']['name'] == "ocr"): try: instance.oa_annotation['annotatedBy'] = {'name': 'ocr'} instance.owner = User.objects.get_or_create(username='ocr', name='OCR')[0] character_count = len(instance.content) # 1.6 is a "magic number" that seems to work pretty well ¯\_(ツ)_/¯ font_size = instance.h / 1.6 # Assuming a character's width is half the height. This was my first guess. # This should give us how long all the characters will be. string_width = (font_size / 2) * character_count # And this is what we're short. space_to_fill = instance.w - string_width # Divide up the space to fill and space the letters. letter_spacing = space_to_fill / character_count # Percent of letter spacing of overall width. # This is used by OpenSeadragon. OSD will update the letter spacing relative to # the width of the overlayed element when someone zooms in and out. relative_letter_spacing = letter_spacing / instance.w instance.content = "<span id='{pk}' data-letter-spacing='{p}'>{content}</span>".format(pk=instance.pk, content=instance.content, p=str(relative_letter_spacing)) instance.style = ".anno-{c}: {{ height: {h}px; width: {w}px; font-size: {f}px; }}".format(c=(instance.pk), h=str(instance.h), w=str(instance.w), f=str(font_size)) # TODO Is this actually how this should be handeled? If not, remove the import of `IntegrityError` except (ValueError, ZeroDivisionError, IntegrityError) as error: instance.content = '' logger.warning("WARNING: {e}".format(e=error))
Example #3
Source File: tests.py From prospector with GNU General Public License v3.0 | 6 votes |
def test_emptyfield(self): m = self._get_mailinglist() p = self._get_participant() values = { 'author': p, 'timestamp': datetime.datetime.utcnow(), 'subject': '', 'message_id': 'abc' } for key in values: kwargs = values.copy() kwargs[key] = None sid = transaction.savepoint() with self.assertRaises(ValueError if key == 'author' else IntegrityError): # ForeignKeys throw a ValueError instead of IntegrityError. Post.objects.create(**kwargs) transaction.savepoint_rollback(sid)
Example #4
Source File: models.py From coursys with GNU General Public License v3.0 | 6 votes |
def create_reminder_on(self, date, start_date, end_date): if start_date > date or date > end_date: # not timely, so ignore return if self.reminder_type == 'ROLE': roles = Role.objects_fresh.filter(unit=self.unit, role=self.role).select_related('person') recipients = [r.person for r in roles] elif self.reminder_type in ['PERS', 'INST']: recipients = [self.person] else: raise ValueError() for recip in recipients: ident = '%s_%s_%s' % (self.slug, recip.userid_or_emplid(), date.isoformat()) # ident length: slug (50) + userid/emplid (9) + ISO date (10) + _ (2) <= 71 rm = ReminderMessage(reminder=self, sent=False, date=date, person=recip, ident=ident) with transaction.atomic(): try: rm.save() except IntegrityError: # already been created because we got IntegrityError on rm.ident pass
Example #5
Source File: db.py From bioforum with MIT License | 6 votes |
def save(self, must_create=False): """ Save the current session data to the database. If 'must_create' is True, raise a database error if the saving operation doesn't create a new entry (as opposed to possibly updating an existing entry). """ if self.session_key is None: return self.create() data = self._get_session(no_load=must_create) obj = self.create_model_instance(data) using = router.db_for_write(self.model, instance=obj) try: with transaction.atomic(using=using): obj.save(force_insert=must_create, force_update=not must_create, using=using) except IntegrityError: if must_create: raise CreateError raise except DatabaseError: if not must_create: raise UpdateError raise
Example #6
Source File: base.py From resolwe with Apache License 2.0 | 6 votes |
def save(self, *args, **kwargs): """Save the model.""" name_max_len = self._meta.get_field("name").max_length if len(self.name) > name_max_len: self.name = self.name[: (name_max_len - 3)] + "..." for _ in range(MAX_SLUG_RETRIES): try: # Attempt to save the model. It may fail due to slug conflict. with transaction.atomic(): super().save(*args, **kwargs) break except IntegrityError as error: # Retry in case of slug conflicts. if "{}_slug".format(self._meta.db_table) in error.args[0]: self.slug = None continue raise else: raise IntegrityError( "Maximum number of retries exceeded during slug generation" )
Example #7
Source File: view.py From koku with GNU Affero General Public License v3.0 | 6 votes |
def destroy(self, request, *args, **kwargs): """Delete a source.""" source = self.get_object() manager = ProviderBuilder(request.user.identity_header.get("encoded")) for _ in range(5): try: manager.destroy_provider(source.koku_uuid) except IntegrityError as error: LOG.warning(f"Retrying Source delete due to error: {error}") except Exception as error: # catch everything else. return immediately msg = f"Source removal resulted in UNKNOWN error: {type(error).__name__}: {error}" LOG.error(msg) return Response(msg, status=500) else: return super().destroy(request, *args, **kwargs) LOG.error("Failed to remove Source") return Response("Failed to remove Source", status=500)
Example #8
Source File: views.py From zulip with Apache License 2.0 | 6 votes |
def register_remote_push_device(request: HttpRequest, entity: Union[UserProfile, RemoteZulipServer], user_id: int=REQ(validator=check_int), token: str=REQ(), token_kind: int=REQ(validator=check_int), ios_app_id: Optional[str]=None) -> HttpResponse: server = validate_bouncer_token_request(entity, token, token_kind) try: with transaction.atomic(): RemotePushDeviceToken.objects.create( user_id=user_id, server=server, kind=token_kind, token=token, ios_app_id=ios_app_id, # last_updated is to be renamed to date_created. last_updated=timezone.now()) except IntegrityError: pass return json_success()
Example #9
Source File: add_user.py From substra-backend with Apache License 2.0 | 6 votes |
def handle(self, *args, **options): username = options['username'] password = options['password'] try: validate_password(password, self.UserModel(username=username)) except ValidationError as err: self.stderr.write('\n'.join(err.messages)) else: try: self.UserModel.objects.create_user(username=username, password=password) except IntegrityError as e: self.stderr.write(f'User already exists: {str(e)}') else: self.stdout.write(f"password: {password}")
Example #10
Source File: test_field.py From django-livefield with MIT License | 6 votes |
def test_allows_uniqueness_with_many_dead(self): first = Person(name='collision') first.save() second = Person(name='collision') # Uniqueness constraint should prevent a second live object with the # same name. with transaction.atomic(): self.assertRaises(IntegrityError, second.save) # Should be able to have several dead objects with same name first.live = False first.save() # Now we can save and delete second second.save() second.live = False second.save() third = Person(name='collision') third.save() self.assertEqual(Person.all_objects.count(), 3) # Resurrecting one of the dead dupes should violate uniqueness first.live = True with transaction.atomic(): self.assertRaises(IntegrityError, first.save)
Example #11
Source File: custom_profile_fields.py From zulip with Apache License 2.0 | 6 votes |
def update_realm_custom_profile_field(request: HttpRequest, user_profile: UserProfile, field_id: int, name: str=REQ(default=''), hint: str=REQ(default=''), field_data: ProfileFieldData=REQ(default={}, converter=ujson.loads), ) -> HttpResponse: realm = user_profile.realm try: field = CustomProfileField.objects.get(realm=realm, id=field_id) except CustomProfileField.DoesNotExist: return json_error(_('Field id {id} not found.').format(id=field_id)) if field.field_type == CustomProfileField.EXTERNAL_ACCOUNT: if is_default_external_field(field.field_type, ujson.loads(field.field_data)): return json_error(_("Default custom field cannot be updated.")) validate_custom_profile_field(name, hint, field.field_type, field_data) try: try_update_realm_custom_profile_field(realm, field, name, hint=hint, field_data=field_data) except IntegrityError: return json_error(_('A field with that label already exists.')) return json_success()
Example #12
Source File: transaction.py From django-cachalot with BSD 3-Clause "New" or "Revised" License | 6 votes |
def test_deferred_error(self): """ Checks that an error occurring during the end of a transaction has no impact on future queries. """ with connection.cursor() as cursor: cursor.execute( 'CREATE TABLE example (' 'id int UNIQUE DEFERRABLE INITIALLY DEFERRED);') with self.assertRaises(IntegrityError): with transaction.atomic(): with self.assertNumQueries(1): list(Test.objects.all()) cursor.execute( 'INSERT INTO example VALUES (1), (1);' '-- ' + Test._meta.db_table) # Should invalidate Test. with self.assertNumQueries(1): list(Test.objects.all())
Example #13
Source File: import_assessor_fields.py From cornerwise with MIT License | 6 votes |
def do_main(path="/data/assessor_data.csv"): with open(path) as csvfile: reader = csv.DictReader(csvfile) for row in reader: loc_id = row["LOC_ID"] try: parcel = Parcel.objects.filter(loc_id=loc_id)[0] for field, value in row.items(): handler = known_field_handler.get(field) if handler: handler(parcel, value) else: attribute = Attribute(parcel=parcel, name=field, value=value) attribute.save() except IntegrityError as err: pass except IndexError as err: # No such Parcel exists logger.warn("No parcel exists with loc_id '%s'", loc_id)
Example #14
Source File: db.py From GTDWeb with GNU General Public License v2.0 | 6 votes |
def save(self, must_create=False): """ Saves the current session data to the database. If 'must_create' is True, a database error will be raised if the saving operation doesn't create a *new* entry (as opposed to possibly updating an existing entry). """ if self.session_key is None: return self.create() obj = Session( session_key=self._get_or_create_session_key(), session_data=self.encode(self._get_session(no_load=must_create)), expire_date=self.get_expiry_date() ) using = router.db_for_write(Session, instance=obj) try: with transaction.atomic(using=using): obj.save(force_insert=must_create, using=using) except IntegrityError: if must_create: raise CreateError raise
Example #15
Source File: tests.py From prospector with GNU General Public License v3.0 | 5 votes |
def test_emptyfield(self): sid = transaction.savepoint() with self.assertRaises(IntegrityError): MailingList.objects.create(posting_address='test@example.com', archive_url=None) transaction.savepoint_rollback(sid) with self.assertRaises(IntegrityError): MailingList.objects.create(posting_address=None, archive_url='http://example.com')
Example #16
Source File: tests.py From prospector with GNU General Public License v3.0 | 5 votes |
def test_duplicate(self): msgid = 'abc' post1 = self._get_post(msgid) post2 = self._get_post('def') self.assertNotEqual(post1.id, post2.id) with self.assertRaises(IntegrityError): self._get_post(msgid)
Example #17
Source File: push_notifications.py From zulip with Apache License 2.0 | 5 votes |
def add_push_device_token(user_profile: UserProfile, token_str: str, kind: int, ios_app_id: Optional[str]=None) -> None: logger.info("Registering push device: %d %r %d %r", user_profile.id, token_str, kind, ios_app_id) # Regardless of whether we're using the push notifications # bouncer, we want to store a PushDeviceToken record locally. # These can be used to discern whether the user has any mobile # devices configured, and is also where we will store encryption # keys for mobile push notifications. try: with transaction.atomic(): PushDeviceToken.objects.create( user_id=user_profile.id, kind=kind, token=token_str, ios_app_id=ios_app_id, # last_updated is to be renamed to date_created. last_updated=timezone_now()) except IntegrityError: pass # If we're sending things to the push notification bouncer # register this user with them here if uses_notification_bouncer(): post_data = { 'server_uuid': settings.ZULIP_ORG_ID, 'user_id': user_profile.id, 'token': token_str, 'token_kind': kind, } if kind == PushDeviceToken.APNS: post_data['ios_app_id'] = ios_app_id logger.info("Sending new push device to bouncer: %r", post_data) # Calls zilencer.views.register_remote_push_device send_to_push_bouncer('POST', 'push/register', post_data)
Example #18
Source File: tests.py From prospector with GNU General Public License v3.0 | 5 votes |
def test_duplicate(self): p = Purpose.objects.create(name='user') with self.assertRaises(IntegrityError): Purpose.objects.create(name='user')
Example #19
Source File: tests.py From prospector with GNU General Public License v3.0 | 5 votes |
def test_duplicate(self): posting_address = 'test@example.com' archive_url = 'http://example.com' m = MailingList.objects.create(posting_address=posting_address, archive_url=archive_url) with self.assertRaises(IntegrityError): MailingList.objects.create(posting_address=posting_address, archive_url='http://other.example.com')
Example #20
Source File: message_edit.py From zulip with Apache License 2.0 | 5 votes |
def delete_message_backend(request: HttpRequest, user_profile: UserProfile, message_id: int=REQ(converter=to_non_negative_int, path_only=True)) -> HttpResponse: message, ignored_user_message = access_message(user_profile, message_id) validate_can_delete_message(user_profile, message) try: do_delete_messages(user_profile.realm, [message]) except (Message.DoesNotExist, IntegrityError): raise JsonableError(_("Message already deleted")) return json_success()
Example #21
Source File: tests.py From django_migration_testcase with MIT License | 5 votes |
def test_second_model_name_is_unique(self): model_before = self.get_model_before('MySecondModel') model_before.objects.create(name='foo') model_before.objects.create(name='foo') with self.assertRaises(IntegrityError): self.run_migration()
Example #22
Source File: test_models.py From karrot-backend with GNU Affero General Public License v3.0 | 5 votes |
def test_create_two_feedback_for_same_activity_as_same_user_fails(self): Feedback.objects.create(given_by=self.user, about=self.activity) with self.assertRaises(IntegrityError): Feedback.objects.create(given_by=self.user, about=self.activity)
Example #23
Source File: test_model.py From karrot-backend with GNU Affero General Public License v3.0 | 5 votes |
def test_create_group_with_same_name_fails(self): Group.objects.create(name='abcdef') with self.assertRaises(IntegrityError): Group.objects.create(name='abcdef')
Example #24
Source File: views.py From Pytition with BSD 3-Clause "New" or "Revised" License | 5 votes |
def add_new_slug(request, petition_id): pytitionuser = get_session_user(request) try: petition = petition_from_id(petition_id) except: messages.error(request, _("This petition does not exist (anymore?).")) return redirect("user_dashboard") if request.method == "POST": slugtexts = request.POST.getlist('slugtext', '') if slugtexts == '' or slugtexts == []: messages.error(request, _("You entered an empty slug text")) else: if petition.is_allowed_to_edit(pytitionuser): for slugtext in slugtexts: try: petition.add_slug(slugtext) petition.save() messages.success(request, _("Successful addition of the slug '{}'!".format(slugtext))) except IntegrityError: messages.error(request, _("The slug '{}' already exists!".format(slugtext))) except ValidationError as v: for message in v.messages: messages.error(request, message) else: messages.error(request, _("You don't have the permission to modify petitions")) return redirect(reverse("edit_petition", args=[petition_id]) + "#tab_social_network_form") else: return redirect("user_dashboard") # /<int:petition_id>/del_slug # Remove a slug from a petition
Example #25
Source File: models.py From anytask with MIT License | 5 votes |
def generate_invite(generated_by, group, size=7): invite = Invite() invite.generated_by = generated_by invite.group = group key = Invite._id_generator(size) for _ in xrange(1000): try: if Invite.objects.filter(key=key).count(): key = Invite._id_generator(size) else: invite.key = key invite.save() return invite except IntegrityError: return Invite.generate_invite(generated_by, group, size)
Example #26
Source File: test_project.py From kobo-predict with BSD 2-Clause "Simplified" License | 5 votes |
def test_add_form_to_project(self): organization = self._create_organization("modilabs", self.user) project_name = "demo" project = self._create_project(organization, project_name, self.user) self._publish_transportation_form() count = ProjectXForm.objects.count() project_xform = tools.add_xform_to_project( self.xform, project, self.user) self.assertEqual(ProjectXForm.objects.count(), count + 1) self.assertIsInstance(project_xform, ProjectXForm) with self.assertRaises(IntegrityError): tools.add_xform_to_project( self.xform, project, self.user)
Example #27
Source File: kafka_listener.py From koku with GNU Affero General Public License v3.0 | 5 votes |
def listen_for_messages(msg, consumer, application_source_id): # noqa: C901 """ Listen for Platform-Sources kafka messages. Args: consumer (Consumer): Kafka consumer object application_source_id (Integer): Cost Management's current Application Source ID. Used for kafka message filtering. Returns: None """ try: try: msg = get_sources_msg_data(msg, application_source_id) offset = msg.get("offset") partition = msg.get("partition") except SourcesMessageError: return if msg: LOG.info(f"Processing message offset: {offset} partition: {partition}") topic_partition = TopicPartition(topic=Config.SOURCES_TOPIC, partition=partition, offset=offset) LOG.info(f"Cost Management Message to process: {str(msg)}") try: with transaction.atomic(): process_message(application_source_id, msg) consumer.commit() except (IntegrityError, InterfaceError, OperationalError) as err: connection.close() LOG.error(f"{type(err).__name__}: {err}") rewind_consumer_to_retry(consumer, topic_partition) except SourcesHTTPClientError as err: LOG.error(err) rewind_consumer_to_retry(consumer, topic_partition) except SourceNotFoundError: LOG.warning(f"Source not found in platform sources. Skipping msg: {msg}") consumer.commit() except KafkaError as error: LOG.error(f"[listen_for_messages] Kafka error encountered: {type(error).__name__}: {error}", exc_info=True) except Exception as error: LOG.error(f"[listen_for_messages] UNKNOWN error encountered: {type(error).__name__}: {error}", exc_info=True)
Example #28
Source File: tests.py From django_migration_testcase with MIT License | 5 votes |
def test_second_model_name_is_unique(self): model_before = self.get_model_before('MySecondModel') model_before.objects.create(name='foo') model_before.objects.create(name='foo') with self.assertRaises(IntegrityError): self.run_migration()
Example #29
Source File: product.py From Servo with BSD 2-Clause "Simplified" License | 5 votes |
def edit_category(request, slug=None, parent_slug=None): form = CategoryForm() category = ProductCategory() if slug is not None: category = get_object_or_404(ProductCategory, slug=slug) form = CategoryForm(instance=category) if parent_slug is not None: parent = get_object_or_404(ProductCategory, slug=parent_slug) form = CategoryForm(initial={'parent': parent.pk}) if request.method == "POST": form = CategoryForm(request.POST, instance=category) if form.is_valid(): try: category = form.save() except IntegrityError: error = _(u'Category %s already exists') % category.title messages.error(request, error) return redirect(list_products) messages.success(request, _(u"Category %s saved") % category.title) return redirect(category) else: messages.error(request, form.errors) return redirect(list_products) return render(request, "products/category_form.html", locals())
Example #30
Source File: tests.py From django_migration_testcase with MIT License | 5 votes |
def tearDown(self): self.assertTrue(self.get_model_before('MySecondModel').objects.all().exists()) with self.assertRaises(IntegrityError): # tearDown fails since migrations runs again with the data super(TeardownCanFail, self).tearDown() self.get_model_before('MySecondModel').objects.all().delete() super(TeardownCanFail, self).tearDown()