Python django.db.utils.IntegrityError() Examples

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

Example 1
Project: figures   Author: appsembler   File: test_course_daily_metrics_model.py    License: MIT License 6 votes vote down vote up
def test_create_violates_unique(self, ):
        '''Test CourseDailyMetrics unique constraints
        First create a model instance, then try creating with the same
        date_for and course_id. It should raise IntegrityError
        '''

        rec = dict(
            site=self.site,
            date_for=datetime.date(2018, 2, 2),
            course_id='course-v1:SomeOrg+ABC01+2121',
            enrollment_count=11,
            active_learners_today=1,
            average_progress=0.5,
            average_days_to_complete=5,
            num_learners_completed=10
        )
        metrics = CourseDailyMetrics.objects.create(**rec)
        with pytest.raises(IntegrityError) as e_info:
            metrics = CourseDailyMetrics.objects.create(**rec)
            assert e_info.value.message.startswith('UNIQUE constraint failed') 
Example 2
Project: oxidizr   Author: pixlie   File: views.py    License: GNU General Public License v2.0 6 votes vote down vote up
def form_valid(self, form):
        base, created = BaseKeyword.objects.get_or_create(term=form.cleaned_data['term'])
        keyword = Keyword()
        keyword.base = base
        keyword.project = self.request.project
        try:
            keyword.save()
        except IntegrityError:
            # The unique_together constraint on Keyword model failed
            # TODO: Handle a more specific error, IntegrityError could be raised by things other than duplicate too
            messages.add_message(
                message=_('You already have that keyword for this project, so we did not add it again.'),
                level=messages.INFO,
                request=self.request,
                extra_tags='module-level'
            )
        return HttpResponseRedirect(self.get_success_url()) 
Example 3
Project: oxidizr   Author: pixlie   File: crawl.py    License: GNU General Public License v2.0 6 votes vote down vote up
def union(p, q):
    for url in p:
        parsed = urlparse(str(url))
        if parsed.netloc and parsed.netloc != 'www.webhostingtalk.com':
            url = 'http://%s/' % parsed.netloc
        if parsed.netloc and url not in q:
            print url
            if parsed.netloc != 'www.webhostingtalk.com':
                # Insert into Site
                try:
                    Website.objects.create(
                        url=url,
                        name=parsed.netloc,
                        last_crawled_at=datetime.datetime.utcnow().replace(tzinfo=pytz.utc)
                    )
                except IntegrityError:
                    println('%s - already existed in Site' % url)
            else:
                # We want to deep crawl webhosting talk
                q.append(url) 
Example 4
Project: oxidizr   Author: pixlie   File: crawl.py    License: GNU General Public License v2.0 6 votes vote down vote up
def extract_context(html, url):
    soup = BeautifulSoup(html)
    # Insert into Content (under this domain)
    texts = soup.findAll(text=True)
    try:
        Content.objects.create(
            url=url,
            title=soup.title.string,
            summary=helpers.strip_tags(" \n".join(filter(visible, texts)))[:4000],
            last_crawled_at=datetime.datetime.utcnow().replace(tzinfo=pytz.utc)
        )
    except IntegrityError:
        println('%s - already existed in Content' % url)
    soup.prettify()
    return [str(anchor['href'])
            for anchor in soup.findAll('a', attrs={'href': re.compile("^http://")}) if anchor['href']] 
Example 5
Project: donation-tracker   Author: GamesDoneQuick   File: api.py    License: Apache License 2.0 6 votes vote down vote up
def generic_api_view(view_func):
    def wrapped_view(request, *args, **kwargs):
        try:
            return view_func(request, *args, **kwargs)
        except PermissionDenied as e:
            return generic_error_json('Permission Denied', e, status=403)
        except IntegrityError as e:
            return generic_error_json('Integrity Error', e)
        except ValidationError as e:
            return generic_error_json(
                'Validation Error',
                e,
                pretty_exception='See message_dict and/or messages for details',
                additional_keys=('message_dict', 'messages', 'code', 'params'),
            )
        except (AttributeError, KeyError, FieldError, ValueError) as e:
            return generic_error_json('Malformed Parameters', e)
        except FieldDoesNotExist as e:
            return generic_error_json('Field does not exist', e)
        except ObjectDoesNotExist as e:
            return generic_error_json('Foreign Key relation could not be found', e)

    return wrapped_view 
Example 6
Project: coursys   Author: sfu-fas   File: tests.py    License: GNU General Public License v3.0 6 votes vote down vote up
def test_FormGroups(self):
        groupName = "admins_test"
        u1 = Unit.objects.get(label="CMPT")
        u2 = Unit.objects.get(label="ENSC")
        # Test saving one form group
        fg = FormGroup(name=groupName, unit=u1)
        fg.save()
        self.assertEqual(fg.name, groupName)
        # now try adding another fromgroup in the same name with the same unit
        # should throw an db integrity exception
        fg2 = FormGroup(name=groupName, unit=u1)
        with self.assertRaises(IntegrityError):
            with django.db.transaction.atomic():
                fg2.save()
        # now add a formgroup with the same name into a different unit
        fg2 = FormGroup(name=groupName, unit=u2)
        fg2.save()
        self.assertEqual(fg2.name, groupName)
        self.assertEqual(fg2.unit, u2)
        # add some people to the fg
        p1 = Person.objects.get(userid="ggbaker")
        p2 = Person.objects.get(userid="dzhao")
        FormGroupMember(person=p1, formgroup=fg).save()
        FormGroupMember(person=p2, formgroup=fg).save()
        self.assertEqual(len(fg.members.all()), 2) 
Example 7
Project: arches   Author: archesproject   File: packages.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def add_mapbox_layer(
        self, layer_name=False, mapbox_json_path=False, layer_icon="fa fa-globe", is_basemap=False,
    ):
        if layer_name is not False and mapbox_json_path is not False:
            with open(mapbox_json_path) as data_file:
                data = json.load(data_file)
                with transaction.atomic():
                    for layer in data["layers"]:
                        if "source" in layer:
                            layer["source"] = layer["source"] + "-" + layer_name
                    for source_name, source_dict in data["sources"].items():
                        map_source = models.MapSource.objects.get_or_create(name=source_name + "-" + layer_name, source=source_dict)
                    map_layer = models.MapLayer(
                        name=layer_name, layerdefinitions=data["layers"], isoverlay=(not is_basemap), icon=layer_icon
                    )
                    try:
                        map_layer.save()
                    except IntegrityError as e:
                        print("Cannot save layer: {0} already exists".format(layer_name)) 
Example 8
Project: python-mysql-pool   Author: LuciferJack   File: base.py    License: MIT License 6 votes vote down vote up
def _execute_wrapper(self, method, query, args):
        """Wrapper around execute() and executemany()"""
        try:
            return method(query, args)
        except (PyMysqlPool.mysql.connector.ProgrammingError) as err:
            six.reraise(utils.ProgrammingError,
                        utils.ProgrammingError(err.msg), sys.exc_info()[2])
        except (PyMysqlPool.mysql.connector.IntegrityError) as err:
            six.reraise(utils.IntegrityError,
                        utils.IntegrityError(err.msg), sys.exc_info()[2])
        except PyMysqlPool.mysql.connector.OperationalError as err:
            # Map some error codes to IntegrityError, since they seem to be
            # misclassified and Django would prefer the more logical place.
            if err.args[0] in self.codes_for_integrityerror:
                six.reraise(utils.IntegrityError,
                            utils.IntegrityError(err.msg), sys.exc_info()[2])
            else:
                six.reraise(utils.DatabaseError,
                            utils.DatabaseError(err.msg), sys.exc_info()[2])
        except PyMysqlPool.mysql.connector.DatabaseError as err:
            six.reraise(utils.DatabaseError,
                        utils.DatabaseError(err.msg), sys.exc_info()[2]) 
Example 9
Project: GTDWeb   Author: lanbing510   File: base.py    License: GNU General Public License v2.0 6 votes vote down vote up
def _commit(self):
        if self.connection is not None:
            try:
                return self.connection.commit()
            except Database.DatabaseError as e:
                # cx_Oracle 5.0.4 raises a cx_Oracle.DatabaseError exception
                # with the following attributes and values:
                #  code = 2091
                #  message = 'ORA-02091: transaction rolled back
                #            'ORA-02291: integrity constraint (TEST_DJANGOTEST.SYS
                #               _C00102056) violated - parent key not found'
                # We convert that particular case to our IntegrityError exception
                x = e.args[0]
                if hasattr(x, 'code') and hasattr(x, 'message') \
                   and x.code == 2091 and 'ORA-02291' in x.message:
                    six.reraise(utils.IntegrityError, utils.IntegrityError(*tuple(e.args)), sys.exc_info()[2])
                raise

    # Oracle doesn't support releasing savepoints. But we fake them when query
    # logging is enabled to keep query counts consistent with other backends. 
Example 10
Project: GTDWeb   Author: lanbing510   File: base.py    License: GNU General Public License v2.0 6 votes vote down vote up
def executemany(self, query, params=None):
        if not params:
            # No params given, nothing to do
            return None
        # uniform treatment for sequences and iterables
        params_iter = iter(params)
        query, firstparams = self._fix_for_params(query, next(params_iter))
        # we build a list of formatted params; as we're going to traverse it
        # more than once, we can't make it lazy by using a generator
        formatted = [firstparams] + [self._format_params(p) for p in params_iter]
        self._guess_input_sizes(formatted)
        try:
            return self.cursor.executemany(query,
                                [self._param_generator(p) for p in formatted])
        except Database.DatabaseError as e:
            # cx_Oracle <= 4.4.0 wrongly raises a DatabaseError for ORA-01400.
            if hasattr(e.args[0], 'code') and e.args[0].code == 1400 and not isinstance(e, IntegrityError):
                six.reraise(utils.IntegrityError, utils.IntegrityError(*tuple(e.args)), sys.exc_info()[2])
            raise 
Example 11
Project: marsha   Author: openfun   File: test_models_deletion.py    License: MIT License 6 votes vote down vote up
def _test_uniqueness_ignores_deleted(
        self, factory: Type[DjangoModelFactory], **kwargs
    ):
        """Ensure uniqueness doesn't take deleted instances into account.

        Parameters
        ----------
        factory: Type[DjangoModelFactory]
            The factory to use to create/delete some objects
        kwargs:
            Arguments to pass to the given `factory`.

        """
        obj1 = factory(**kwargs)

        # force a soft deletion (useful for through models configured with ``HARD_DELETE``)
        obj1.delete(force_policy=SOFT_DELETE_CASCADE)
        self.assertIsSoftDeleted(obj1)

        # we can create it again
        factory(**kwargs)

        # when exists non-deleted, cannot create another one
        with self.assertRaises(IntegrityError):
            factory(**kwargs) 
Example 12
Project: marsha   Author: openfun   File: test_models_video.py    License: MIT License 6 votes vote down vote up
def test_models_video_fields_lti_id_unique(self):
        """Videos should be unique for a given duo lti_id/playlist (see LTI specification)."""
        video = VideoFactory()

        # A video with a different lti_id and the same playlist can still be created
        VideoFactory(playlist=video.playlist)

        # A video for a different playlist and the same lti_id can still be created
        VideoFactory(lti_id=video.lti_id)

        # Trying to create a video with the same duo lti_id/playlist should raise a
        # database error
        with self.assertRaises(IntegrityError):
            with transaction.atomic():
                VideoFactory(lti_id=video.lti_id, playlist=video.playlist)

        # Soft deleted videos should not count for unicity
        video.delete(force_policy=SOFT_DELETE_CASCADE)
        VideoFactory(lti_id=video.lti_id, playlist=video.playlist) 
Example 13
Project: marsha   Author: openfun   File: test_models_playlist.py    License: MIT License 6 votes vote down vote up
def test_models_playlist_fields_lti_id_unique(self):
        """Playlists should be unique for a given duo: lti_id/playlist."""
        playlist = PlaylistFactory()

        # A playlist with a different lti_id and the same consumer site can still be created
        PlaylistFactory(consumer_site=playlist.consumer_site)

        # A playlist for a different consumer site and the same lti_id can still be created
        PlaylistFactory(lti_id=playlist.lti_id)

        # Trying to create a playlist with the same duo lti_id/consumer site should raise a
        # database error
        with self.assertRaises(IntegrityError):
            with transaction.atomic():
                PlaylistFactory(
                    lti_id=playlist.lti_id, consumer_site=playlist.consumer_site
                )

        # Soft deleted playlists should not count for unicity
        playlist.delete(force_policy=SOFT_DELETE_CASCADE)
        PlaylistFactory(lti_id=playlist.lti_id, consumer_site=playlist.consumer_site) 
Example 14
Project: koku   Author: project-koku   File: middleware.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def create_customer(account):
        """Create a customer.
        Args:
            account (str): The account identifier
        Returns:
            (Customer) The created customer
        """
        try:
            with transaction.atomic():
                schema_name = create_schema_name(account)
                customer = Customer(account_id=account, schema_name=schema_name)
                customer.save()
                tenant = Tenant(schema_name=schema_name)
                tenant.save()
                UNIQUE_ACCOUNT_COUNTER.inc()
                LOG.info("Created new customer from account_id %s.", account)
        except IntegrityError:
            customer = Customer.objects.filter(account_id=account).get()

        return customer 
Example 15
Project: koku   Author: project-koku   File: middleware.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def create_user(username, email, customer, request):
        """Create a user for a customer.
        Args:
            username (str): The username
            email (str): The email for the user
            customer (Customer): The customer the user is associated with
            request (object): The incoming request
        Returns:
            (User) The created user
        """
        new_user = None
        try:
            with transaction.atomic():
                user_data = {"username": username, "email": email}
                context = {"request": request, "customer": customer}
                serializer = UserSerializer(data=user_data, context=context)
                if serializer.is_valid(raise_exception=True):
                    new_user = serializer.save()

                UNIQUE_USER_COUNTER.labels(account=customer.account_id, user=username).inc()
                LOG.info("Created new user %s for customer(account_id %s).", username, customer.account_id)
        except (IntegrityError, ValidationError):
            new_user = User.objects.get(username=username)
        return new_user 
Example 16
Project: linkedevents   Author: City-of-Helsinki   File: 0074_create_light_admin_group.py    License: MIT License 6 votes vote down vote up
def create_light_admin_group():
    try:
        # If "Light Admins" already exists, migration causes
        # django.db.transaction.TransactionManagementError
        # without transaction.atomic().
        with transaction.atomic():
            light_admin_group = Group.objects.create(name='Light Admins')
    except IntegrityError:
        print('\nGroup with name "Light Admins" already exists. Skipping creation.')
        return
    try:
        regular_users_perm = Permission.objects.get(codename='change_organization_regular_users')
        view_user = Permission.objects.get(codename='view_user')
    except Permission.DoesNotExist:
        print('\nMissing permissions. Skipping creation.')
        return
    light_admin_group.permissions.set([regular_users_perm, view_user]) 
Example 17
Project: linkedevents   Author: City-of-Helsinki   File: api.py    License: MIT License 6 votes vote down vote up
def create(self, validated_data):
        if 'data_source' not in validated_data:
            validated_data['data_source'] = self.data_source
        # data source has already been validated
        if 'publisher' not in validated_data:
            validated_data['publisher'] = self.publisher
        # publisher has already been validated
        validated_data['created_by'] = self.user
        validated_data['last_modified_by'] = self.user
        try:
            instance = super().create(validated_data)
        except IntegrityError as error:
            if 'duplicate' and 'pkey' in str(error):
                raise serializers.ValidationError({'id': _("An object with given id already exists.")})
            else:
                raise error
        return instance 
Example 18
Project: django-test-migrations   Author: wemake-services   File: test_pytest_plugin_direct.py    License: MIT License 6 votes vote down vote up
def test_pytest_plugin0003(migrator):
    """Ensures that the third migration works."""
    old_state = migrator.apply_initial_migration(
        ('main_app', '0003_update_is_clean'),
    )
    SomeItem = old_state.apps.get_model('main_app', 'SomeItem')
    SomeItem.objects.create(string_field='a')  # default is still there

    assert SomeItem.objects.count() == 1
    assert SomeItem.objects.filter(is_clean=True).count() == 1

    new_state = migrator.apply_tested_migration(
        ('main_app', '0004_auto_20191119_2125'),
    )
    SomeItem = new_state.apps.get_model('main_app', 'SomeItem')

    with pytest.raises(IntegrityError):
        SomeItem.objects.create(string_field='b')  # no default anymore 
Example 19
Project: bioforum   Author: reBiocoder   File: base.py    License: MIT License 6 votes vote down vote up
def _commit(self):
        if self.connection is not None:
            try:
                return self.connection.commit()
            except Database.DatabaseError as e:
                # cx_Oracle raises a cx_Oracle.DatabaseError exception
                # with the following attributes and values:
                #  code = 2091
                #  message = 'ORA-02091: transaction rolled back
                #            'ORA-02291: integrity constraint (TEST_DJANGOTEST.SYS
                #               _C00102056) violated - parent key not found'
                # We convert that particular case to our IntegrityError exception
                x = e.args[0]
                if hasattr(x, 'code') and hasattr(x, 'message') \
                   and x.code == 2091 and 'ORA-02291' in x.message:
                    raise utils.IntegrityError(*tuple(e.args))
                raise

    # Oracle doesn't support releasing savepoints. But we fake them when query
    # logging is enabled to keep query counts consistent with other backends. 
Example 20
Project: waliki   Author: mgaitan   File: models.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def from_path(cls, path, markup=None):
        filename, ext = os.path.splitext(path)
        if markup and isinstance(markup, string_types):
            markup = _markups.find_markup_class_by_name(markup)
        else:
            markup = _markups.find_markup_class_by_extension(ext)
        page = Page(path=path, slug=get_slug(filename), markup=markup.name)
        page.title = page._get_part('get_document_title')

        while True:
            try:
                page.save()
                break
            except IntegrityError:
                page.slug += '-'
        return page 
Example 21
Project: plugin.video.netflix   Author: CastagnaIT   File: base.py    License: MIT License 6 votes vote down vote up
def _execute_wrapper(self, method, query, args):
        """Wrapper around execute() and executemany()"""
        try:
            return method(query, args)
        except (mysql.connector.ProgrammingError) as err:
            six.reraise(utils.ProgrammingError,
                        utils.ProgrammingError(err.msg), sys.exc_info()[2])
        except (mysql.connector.IntegrityError) as err:
            six.reraise(utils.IntegrityError,
                        utils.IntegrityError(err.msg), sys.exc_info()[2])
        except mysql.connector.OperationalError as err:
            # Map some error codes to IntegrityError, since they seem to be
            # misclassified and Django would prefer the more logical place.
            if err.args[0] in self.codes_for_integrityerror:
                six.reraise(utils.IntegrityError,
                            utils.IntegrityError(err.msg), sys.exc_info()[2])
            else:
                six.reraise(utils.DatabaseError,
                            utils.DatabaseError(err.msg), sys.exc_info()[2])
        except mysql.connector.DatabaseError as err:
            six.reraise(utils.DatabaseError,
                        utils.DatabaseError(err.msg), sys.exc_info()[2]) 
Example 22
Project: notto   Author: renatoliveira   File: tests.py    License: MIT License 6 votes vote down vote up
def test_do_not_create_duplicates(self):
        """
        Tests that the database is enforcing the unique constraint on
        "url_title".
        """
        form_data = {
            'content': 'some text'
        }
        self.client.post('/n/foo', form_data)
        self.assertEqual(1, len(Note.objects.all()))
        duplicate = Note(
            content='more text',
            url_title='foo'
        )
        try:
            with transaction.atomic():
                duplicate.save()
            self.fail('Shouldn\'t have allowed creation of this note.')
        except IntegrityError:
            pass
        self.assertEqual(1, len(Note.objects.all())) 
Example 23
Project: django-tenants   Author: django-tenants   File: clone_tenant.py    License: MIT License 6 votes vote down vote up
def store_tenant(self, clone_schema_from, clone_tenant_fields, **fields):

        connection.set_schema_to_public()
        try:
            if clone_tenant_fields:
                tenant = get_tenant_model().objects.get(schema_name=clone_schema_from)
                tenant.pk = None
                tenant.schema_name = fields['schema_name']
            else:
                tenant = get_tenant_model()(**fields)
            tenant.auto_create_schema = False
            tenant.save()
            clone_schema = CloneSchema()
            clone_schema.clone_schema(clone_schema_from, tenant.schema_name, set_connection=False)
            return tenant
        except exceptions.ValidationError as e:
            self.stderr.write("Error: %s" % '; '.join(e.messages))
            return None
        except IntegrityError as e:
            self.stderr.write("Error: " + str(e))
            return None 
Example 24
Project: zulip   Author: zulip   File: 0037_disallow_null_string_id.py    License: Apache License 2.0 6 votes vote down vote up
def set_string_id_using_domain(apps: StateApps, schema_editor: DatabaseSchemaEditor) -> None:
    Realm = apps.get_model('zerver', 'Realm')
    for realm in Realm.objects.all():
        if not realm.string_id:
            prefix = realm.domain.split('.')[0]
            try:
                realm.string_id = prefix
                realm.save(update_fields=["string_id"])
                continue
            except IntegrityError:
                pass
            for i in range(1, 100):
                try:
                    realm.string_id = prefix + str(i)
                    realm.save(update_fields=["string_id"])
                    continue
                except IntegrityError:
                    pass
            raise RuntimeError(f"Unable to find a good string_id for realm {realm}") 
Example 25
Project: django-db-mailer   Author: LPgenerator   File: __init__.py    License: GNU General Public License v2.0 6 votes vote down vote up
def initial_signals():
    from django.db.utils import DatabaseError, IntegrityError

    for cmd in ['schemamigration', 'migrate',
                'test', 'createsuperuser', 'makemigrations',
                'collectstatic', 'compilemessages']:
        if cmd in sys.argv:
            break
    else:
        try:
            from dbmail.signals import initial_signals as init_signals

            init_signals()
        except (ImportError, DatabaseError, IntegrityError):
            pass


##
# Compatibility section
## 
Example 26
Project: volontulo   Author: CodeForPoznan   File: api.py    License: MIT License 6 votes vote down vote up
def register_view(request):
    """REST API register view."""
    if request.user.is_authenticated():
        return Response(status=status.HTTP_400_BAD_REQUEST)

    email = request.data.get('email')
    password = request.data.get('password')
    try:
        user = User.objects.create_user(
            username=email,
            email=email,
            password=password,
            is_active=False,
        )
        user.save()
    except IntegrityError:
        return Response(status=status.HTTP_201_CREATED)

    profile = UserProfile(user=user)
    ctx = {'token': profile.uuid}
    profile.save()
    send_mail(request, 'registration', [user.email], context=ctx)

    return Response(status=status.HTTP_201_CREATED) 
Example 27
Project: volontulo   Author: CodeForPoznan   File: create_admin.py    License: MIT License 6 votes vote down vote up
def handle(self, *args, **options):
        """Create Volontulo admin."""
        try:
            user = User.objects.create_user(
                username=options['username'],
                email=options['username'],
                password=options['password'],
                is_superuser=options['django_admin'],
                is_staff=options['django_admin'],
                is_active=True,
            )
        except IntegrityError:
            self.stdout.write(self.style.ERROR('User already exists'))
        else:
            user.save()
            UserProfile(
                user=user,
                is_administrator=True,
            ).save()
            self.stdout.write(self.style.SUCCESS('User successfully created')) 
Example 28
Project: elmer   Author: thetruefuss   File: populate_database.py    License: MIT License 6 votes vote down vote up
def create_boards():
    """Create boards & make SUPERUSER the admin of all boards."""
    admin = User.objects.get(username=SUPERUSER_USERNAME)
    total_entries = TOTAL_BOARDS
    for number in range(total_entries):
        try:
            percentage = calculate_percentage(number, total_entries)
            show_progress_bar(percentage, create_boards.__name__)
            title = generate_dummy_text(BOARDS_TITLE_LENGTH)
            description = title * random.randint(1, 10)
            board = Board.objects.create(
                title=title,
                description=description
            )
            board.save()
            board.admins.add(admin)
            board.subscribers.add(admin)
        except IntegrityError as e:
            print(e)
    task_done_message(total_entries, create_boards.__name__) 
Example 29
Project: elmer   Author: thetruefuss   File: populate_database.py    License: MIT License 6 votes vote down vote up
def create_users():
    """Create users."""
    total_entries = TOTAL_USERS
    for number in range(total_entries):
        try:
            percentage = calculate_percentage(number, total_entries)
            show_progress_bar(percentage, create_users.__name__)
            username = "".join(random.choice(CHARS) for i in range(10))
            email = username + "@example.com"
            user = User.objects.create_user(
                username=username,
                email=email,
                password=USERS_PASSWORD
            )
            user.save()
        except IntegrityError as e:
            print(e)
    task_done_message(total_entries, create_users.__name__) 
Example 30
Project: elmer   Author: thetruefuss   File: populate_database.py    License: MIT License 6 votes vote down vote up
def create_subjects():
    """Create subjects with different author & board."""
    total_entries = TOTAL_SUBJECTS
    for number in range(total_entries):
        try:
            percentage = calculate_percentage(number, total_entries)
            show_progress_bar(percentage, create_subjects.__name__)
            title = generate_dummy_text(SUBJECTS_TITLE_LENGTH)
            body = title * random.randint(1, 10)
            author = User.objects.get(id=random.randint(1, TOTAL_USERS))
            board = Board.objects.get(id=random.randint(1, TOTAL_BOARDS))
            subject = Subject.objects.create(
                title=title,
                body=body,
                author=author,
                board=board
            )
            subject.save()
            subject.points.add(author)
        except IntegrityError as e:
            print(e)
    task_done_message(total_entries, create_subjects.__name__)