Beispiel #1
0
class Migration(migrations.Migration):

    dependencies = [("elections", "0003_election_fk")]

    operations = [
        migrations.AlterField(
            model_name="ballotmeasurecontest",
            name="created_at",
            field=models.DateTimeField(
                auto_now_add=True, help_text="The date and time of creation."),
        ),
        migrations.AlterField(
            model_name="ballotmeasurecontest",
            name="extras",
            field=django.contrib.postgres.fields.jsonb.JSONField(
                blank=True,
                default=dict,
                help_text=
                "A key-value store for storing arbitrary information not covered elsewhere.",
            ),
        ),
        migrations.AlterField(
            model_name="ballotmeasurecontest",
            name="updated_at",
            field=models.DateTimeField(
                auto_now=True,
                help_text="The date and time of the last update."),
        ),
        migrations.AlterField(
            model_name="ballotmeasurecontestidentifier",
            name="identifier",
            field=models.CharField(
                help_text=
                "A unique identifier developed by an upstream or third party source.",
                max_length=300,
            ),
        ),
        migrations.AlterField(
            model_name="ballotmeasurecontestidentifier",
            name="scheme",
            field=models.CharField(
                help_text=
                "The name of the service that created the identifier.",
                max_length=300,
            ),
        ),
        migrations.AlterField(
            model_name="ballotmeasurecontestsource",
            name="note",
            field=models.CharField(
                blank=True,
                help_text="A short, optional note related to an object.",
                max_length=300,
            ),
        ),
        migrations.AlterField(
            model_name="ballotmeasurecontestsource",
            name="url",
            field=models.URLField(
                help_text="A hyperlink related to an object.",
                max_length=2000),
        ),
        migrations.AlterField(
            model_name="candidacy",
            name="created_at",
            field=models.DateTimeField(
                auto_now_add=True, help_text="The date and time of creation."),
        ),
        migrations.AlterField(
            model_name="candidacy",
            name="extras",
            field=django.contrib.postgres.fields.jsonb.JSONField(
                blank=True,
                default=dict,
                help_text=
                "A key-value store for storing arbitrary information not covered elsewhere.",
            ),
        ),
        migrations.AlterField(
            model_name="candidacy",
            name="updated_at",
            field=models.DateTimeField(
                auto_now=True,
                help_text="The date and time of the last update."),
        ),
        migrations.AlterField(
            model_name="candidacysource",
            name="note",
            field=models.CharField(
                blank=True,
                help_text="A short, optional note related to an object.",
                max_length=300,
            ),
        ),
        migrations.AlterField(
            model_name="candidacysource",
            name="url",
            field=models.URLField(
                help_text="A hyperlink related to an object.",
                max_length=2000),
        ),
        migrations.AlterField(
            model_name="candidatecontest",
            name="created_at",
            field=models.DateTimeField(
                auto_now_add=True, help_text="The date and time of creation."),
        ),
        migrations.AlterField(
            model_name="candidatecontest",
            name="extras",
            field=django.contrib.postgres.fields.jsonb.JSONField(
                blank=True,
                default=dict,
                help_text=
                "A key-value store for storing arbitrary information not covered elsewhere.",
            ),
        ),
        migrations.AlterField(
            model_name="candidatecontest",
            name="updated_at",
            field=models.DateTimeField(
                auto_now=True,
                help_text="The date and time of the last update."),
        ),
        migrations.AlterField(
            model_name="candidatecontestidentifier",
            name="identifier",
            field=models.CharField(
                help_text=
                "A unique identifier developed by an upstream or third party source.",
                max_length=300,
            ),
        ),
        migrations.AlterField(
            model_name="candidatecontestidentifier",
            name="scheme",
            field=models.CharField(
                help_text=
                "The name of the service that created the identifier.",
                max_length=300,
            ),
        ),
        migrations.AlterField(
            model_name="candidatecontestsource",
            name="note",
            field=models.CharField(
                blank=True,
                help_text="A short, optional note related to an object.",
                max_length=300,
            ),
        ),
        migrations.AlterField(
            model_name="candidatecontestsource",
            name="url",
            field=models.URLField(
                help_text="A hyperlink related to an object.",
                max_length=2000),
        ),
        migrations.AlterField(
            model_name="election",
            name="created_at",
            field=models.DateTimeField(
                auto_now_add=True, help_text="The date and time of creation."),
        ),
        migrations.AlterField(
            model_name="election",
            name="extras",
            field=django.contrib.postgres.fields.jsonb.JSONField(
                blank=True,
                default=dict,
                help_text=
                "A key-value store for storing arbitrary information not covered elsewhere.",
            ),
        ),
        migrations.AlterField(
            model_name="election",
            name="updated_at",
            field=models.DateTimeField(
                auto_now=True,
                help_text="The date and time of the last update."),
        ),
        migrations.AlterField(
            model_name="electionidentifier",
            name="election",
            field=models.ForeignKey(
                help_text=
                "Reference to the Election identified by this alternative identifier.",
                on_delete=django.db.models.deletion.CASCADE,
                related_name="identifiers",
                to="elections.Election",
            ),
        ),
        migrations.AlterField(
            model_name="electionidentifier",
            name="identifier",
            field=models.CharField(
                help_text=
                "A unique identifier developed by an upstream or third party source.",
                max_length=300,
            ),
        ),
        migrations.AlterField(
            model_name="electionidentifier",
            name="scheme",
            field=models.CharField(
                help_text=
                "The name of the service that created the identifier.",
                max_length=300,
            ),
        ),
        migrations.AlterField(
            model_name="electionsource",
            name="election",
            field=models.ForeignKey(
                help_text="Reference to the Election this source verifies.",
                on_delete=django.db.models.deletion.CASCADE,
                related_name="sources",
                to="elections.Election",
            ),
        ),
        migrations.AlterField(
            model_name="electionsource",
            name="note",
            field=models.CharField(
                blank=True,
                help_text="A short, optional note related to an object.",
                max_length=300,
            ),
        ),
        migrations.AlterField(
            model_name="electionsource",
            name="url",
            field=models.URLField(
                help_text="A hyperlink related to an object.",
                max_length=2000),
        ),
        migrations.AlterField(
            model_name="partycontest",
            name="created_at",
            field=models.DateTimeField(
                auto_now_add=True, help_text="The date and time of creation."),
        ),
        migrations.AlterField(
            model_name="partycontest",
            name="extras",
            field=django.contrib.postgres.fields.jsonb.JSONField(
                blank=True,
                default=dict,
                help_text=
                "A key-value store for storing arbitrary information not covered elsewhere.",
            ),
        ),
        migrations.AlterField(
            model_name="partycontest",
            name="updated_at",
            field=models.DateTimeField(
                auto_now=True,
                help_text="The date and time of the last update."),
        ),
        migrations.AlterField(
            model_name="partycontestidentifier",
            name="identifier",
            field=models.CharField(
                help_text=
                "A unique identifier developed by an upstream or third party source.",
                max_length=300,
            ),
        ),
        migrations.AlterField(
            model_name="partycontestidentifier",
            name="scheme",
            field=models.CharField(
                help_text=
                "The name of the service that created the identifier.",
                max_length=300,
            ),
        ),
        migrations.AlterField(
            model_name="partycontestsource",
            name="note",
            field=models.CharField(
                blank=True,
                help_text="A short, optional note related to an object.",
                max_length=300,
            ),
        ),
        migrations.AlterField(
            model_name="partycontestsource",
            name="url",
            field=models.URLField(
                help_text="A hyperlink related to an object.",
                max_length=2000),
        ),
        migrations.AlterField(
            model_name="retentioncontest",
            name="created_at",
            field=models.DateTimeField(
                auto_now_add=True, help_text="The date and time of creation."),
        ),
        migrations.AlterField(
            model_name="retentioncontest",
            name="extras",
            field=django.contrib.postgres.fields.jsonb.JSONField(
                blank=True,
                default=dict,
                help_text=
                "A key-value store for storing arbitrary information not covered elsewhere.",
            ),
        ),
        migrations.AlterField(
            model_name="retentioncontest",
            name="updated_at",
            field=models.DateTimeField(
                auto_now=True,
                help_text="The date and time of the last update."),
        ),
        migrations.AlterField(
            model_name="retentioncontestidentifier",
            name="identifier",
            field=models.CharField(
                help_text=
                "A unique identifier developed by an upstream or third party source.",
                max_length=300,
            ),
        ),
        migrations.AlterField(
            model_name="retentioncontestidentifier",
            name="scheme",
            field=models.CharField(
                help_text=
                "The name of the service that created the identifier.",
                max_length=300,
            ),
        ),
        migrations.AlterField(
            model_name="retentioncontestsource",
            name="note",
            field=models.CharField(
                blank=True,
                help_text="A short, optional note related to an object.",
                max_length=300,
            ),
        ),
        migrations.AlterField(
            model_name="retentioncontestsource",
            name="url",
            field=models.URLField(
                help_text="A hyperlink related to an object.",
                max_length=2000),
        ),
    ]
class Migration(migrations.Migration):

    initial = True

    dependencies = [
        migrations.swappable_dependency(settings.AUTH_USER_MODEL),
    ]

    operations = [
        migrations.CreateModel(
            name='Inbox',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('slug', models.SlugField()),
                ('created', models.DateTimeField(auto_now_add=True)),
            ],
        ),
        migrations.CreateModel(
            name='UserPhoto',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('photo', models.URLField()),
                ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='userphoto_user', to=settings.AUTH_USER_MODEL)),
            ],
        ),
        migrations.CreateModel(
            name='Setting',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('maximum_distance', models.IntegerField()),
                ('gender', models.CharField(max_length=256)),
                ('age_range', models.IntegerField()),
                ('show_me_on_searches', models.BooleanField()),
                ('new_matches_notification', models.BooleanField()),
                ('message_notification', models.BooleanField()),
                ('message_likes_notification', models.BooleanField()),
                ('super_like_notification', models.BooleanField()),
                ('in_app_vibrations', models.BooleanField()),
                ('user', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='setting_user', to=settings.AUTH_USER_MODEL)),
            ],
        ),
        migrations.CreateModel(
            name='Profile',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('bio', models.TextField()),
                ('school', models.TextField()),
                ('date_of_birth', models.DateField()),
                ('created', models.DateField(auto_now_add=True)),
                ('modified', models.DateField(auto_now=True)),
                ('user', models.OneToOneField(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='profile_user', to=settings.AUTH_USER_MODEL)),
            ],
        ),
        migrations.CreateModel(
            name='Match',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('created', models.DateTimeField(auto_now_add=True)),
                ('owner', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='match_owner', to=settings.AUTH_USER_MODEL)),
                ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='match_user', to=settings.AUTH_USER_MODEL)),
            ],
        ),
        migrations.CreateModel(
            name='Like',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('super_liked', models.BooleanField()),
                ('owner', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='like_owner', to=settings.AUTH_USER_MODEL)),
                ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='like_user', to=settings.AUTH_USER_MODEL)),
            ],
        ),
        migrations.CreateModel(
            name='Dislike',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('owner', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='dislike_owner', to=settings.AUTH_USER_MODEL)),
                ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='dislike_user', to=settings.AUTH_USER_MODEL)),
            ],
        ),
    ]
class Migration(migrations.Migration):

    initial = True

    dependencies = [
        migrations.swappable_dependency(settings.AUTH_USER_MODEL),
    ]

    operations = [
        migrations.CreateModel(
            name='Profile',
            fields=[
                ('id',
                 models.AutoField(auto_created=True,
                                  primary_key=True,
                                  serialize=False,
                                  verbose_name='ID')),
                ('mobile_number', models.CharField(max_length=20)),
                ('pin', models.CharField(max_length=100)),
                ('photo', models.URLField()),
                ('status', models.CharField(max_length=50)),
                ('birthdate', models.DateField()),
                ('gender', models.CharField(max_length=1)),
                ('timestamp_created', models.DateTimeField(auto_now_add=True)),
                ('last_updated', models.DateTimeField(auto_now=True)),
                ('last_login', models.DateTimeField()),
                ('user',
                 models.OneToOneField(
                     on_delete=django.db.models.deletion.CASCADE,
                     related_name='profile_user',
                     to=settings.AUTH_USER_MODEL)),
            ],
        ),
        migrations.CreateModel(
            name='VerificationCode',
            fields=[
                ('id',
                 models.AutoField(auto_created=True,
                                  primary_key=True,
                                  serialize=False,
                                  verbose_name='ID')),
                ('code', models.CharField(max_length=255)),
                ('is_verified', models.BooleanField()),
                ('timestamp_created', models.DateTimeField(auto_now_add=True)),
                ('timestamp_verified', models.DateTimeField()),
                ('sent_to',
                 models.ForeignKey(on_delete=django.db.models.deletion.CASCADE,
                                   related_name='verificationcode_sent_to',
                                   to='chat_user_profile.Profile')),
            ],
        ),
        migrations.CreateModel(
            name='Contact',
            fields=[
                ('id',
                 models.AutoField(auto_created=True,
                                  primary_key=True,
                                  serialize=False,
                                  verbose_name='ID')),
                ('is_blocked', models.BooleanField()),
                ('is_favorite', models.BooleanField()),
                ('timestamp_created', models.DateTimeField(auto_now_add=True)),
                ('added_by',
                 models.ForeignKey(on_delete=django.db.models.deletion.CASCADE,
                                   related_name='contact_added_by',
                                   to=settings.AUTH_USER_MODEL)),
                ('added_profile',
                 models.ForeignKey(on_delete=django.db.models.deletion.CASCADE,
                                   related_name='contact_added_profile',
                                   to='chat_user_profile.Profile')),
            ],
        ),
    ]
Beispiel #4
0
class Migration(migrations.Migration):

    initial = True

    dependencies = [
        ('contenttypes', '0002_remove_content_type_name'),
        migrations.swappable_dependency(settings.AUTH_USER_MODEL),
    ]

    operations = [
        migrations.CreateModel(
            name='AppCategory',
            fields=[
                ('id',
                 models.AutoField(auto_created=True,
                                  primary_key=True,
                                  serialize=False,
                                  verbose_name='ID')),
                ('name', models.CharField(max_length=100)),
            ],
        ),
        migrations.CreateModel(
            name='AppVersion',
            fields=[
                ('id',
                 models.AutoField(auto_created=True,
                                  primary_key=True,
                                  serialize=False,
                                  verbose_name='ID')),
                ('version_number',
                 models.CharField(max_length=10,
                                  validators=[
                                      django.core.validators.RegexValidator(
                                          '[a-zA-Z0-9\\.]*')
                                  ])),
                ('created_time', models.DateTimeField(auto_now_add=True)),
                ('approve_status',
                 models.CharField(choices=[('new', 'new'),
                                           ('approved', 'approved'),
                                           ('rejected', 'rejected')],
                                  default='new',
                                  max_length=10)),
                ('approved_time', models.DateTimeField(blank=True, null=True)),
                ('active_status',
                 models.CharField(choices=[('active', 'active'),
                                           ('inactive', 'inactive')],
                                  default='inactive',
                                  max_length=10)),
                ('approved_by',
                 models.ForeignKey(blank=True,
                                   null=True,
                                   on_delete=django.db.models.deletion.CASCADE,
                                   to=settings.AUTH_USER_MODEL)),
            ],
        ),
        migrations.CreateModel(
            name='Comment',
            fields=[
                ('id',
                 models.AutoField(auto_created=True,
                                  primary_key=True,
                                  serialize=False,
                                  verbose_name='ID')),
                ('content', models.TextField()),
                ('created_time', models.DateTimeField(auto_now_add=True)),
                ('approve_status',
                 models.CharField(choices=[('new', 'new'),
                                           ('approved', 'approved'),
                                           ('rejected', 'rejected')],
                                  default='new',
                                  max_length=10)),
            ],
        ),
        migrations.CreateModel(
            name='Download',
            fields=[
                ('id',
                 models.AutoField(auto_created=True,
                                  primary_key=True,
                                  serialize=False,
                                  verbose_name='ID')),
                ('download_time', models.DateTimeField(auto_now_add=True)),
                ('os', models.CharField(max_length=100)),
                ('mobile', models.CharField(max_length=100)),
            ],
        ),
        migrations.CreateModel(
            name='Evaluation',
            fields=[
                ('id',
                 models.AutoField(auto_created=True,
                                  primary_key=True,
                                  serialize=False,
                                  verbose_name='ID')),
                ('content', models.TextField()),
                ('rate', models.PositiveSmallIntegerField()),
                ('created_time', models.DateTimeField(auto_now_add=True)),
                ('approve_status',
                 models.CharField(choices=[('new', 'new'),
                                           ('approved', 'approved'),
                                           ('rejected', 'rejected')],
                                  default='new',
                                  max_length=10)),
            ],
        ),
        migrations.CreateModel(
            name='Image',
            fields=[
                ('id',
                 models.AutoField(auto_created=True,
                                  primary_key=True,
                                  serialize=False,
                                  verbose_name='ID')),
                ('object_id', models.PositiveIntegerField(null=True)),
                ('picture',
                 models.ImageField(blank=True,
                                   upload_to='pictures/%Y/%m/%d/')),
                ('test', models.CharField(blank=True,
                                          max_length=100,
                                          null=True)),
                ('content_type',
                 models.ForeignKey(null=True,
                                   on_delete=django.db.models.deletion.CASCADE,
                                   to='contenttypes.ContentType')),
            ],
        ),
        migrations.CreateModel(
            name='MobileApp',
            fields=[
                ('id',
                 models.AutoField(auto_created=True,
                                  primary_key=True,
                                  serialize=False,
                                  verbose_name='ID')),
                ('name',
                 models.CharField(db_index=True, max_length=100, unique=True)),
                ('description', models.TextField()),
                ('video_url', models.URLField(null=True)),
                ('upload_date', models.DateTimeField(auto_now_add=True)),
                ('avg_rate',
                 models.DecimalField(decimal_places=1, max_digits=2,
                                     null=True)),
                ('comment_count', models.PositiveIntegerField(null=True)),
                ('download_count', models.PositiveIntegerField(null=True)),
                ('slug', models.SlugField(blank=True, null=True, unique=True)),
                ('category',
                 models.ForeignKey(on_delete=django.db.models.deletion.CASCADE,
                                   to='management.AppCategory')),
            ],
        ),
        migrations.CreateModel(
            name='Profile',
            fields=[
                ('id',
                 models.AutoField(auto_created=True,
                                  primary_key=True,
                                  serialize=False,
                                  verbose_name='ID')),
                ('name', models.CharField(blank=True, max_length=50)),
                ('gender',
                 models.CharField(choices=[('male', '男'), ('female', '女')],
                                  default='male',
                                  max_length=10)),
                ('date_of_birth', models.DateField(blank=True, null=True)),
                ('avatar',
                 models.ImageField(blank=True, upload_to='avatar/%Y/%m/%d/')),
                ('wechatid',
                 models.CharField(blank=True, db_index=True, max_length=100)),
                ('weiboid',
                 models.CharField(blank=True, db_index=True, max_length=100)),
                ('qqid',
                 models.CharField(blank=True, db_index=True, max_length=100)),
                ('slug', models.SlugField(unique=True)),
                ('user',
                 models.OneToOneField(
                     on_delete=django.db.models.deletion.CASCADE,
                     to=settings.AUTH_USER_MODEL)),
            ],
        ),
        migrations.CreateModel(
            name='Tag',
            fields=[
                ('id',
                 models.AutoField(auto_created=True,
                                  primary_key=True,
                                  serialize=False,
                                  verbose_name='ID')),
                ('name', models.CharField(max_length=100)),
            ],
        ),
        migrations.AddField(
            model_name='mobileapp',
            name='tags',
            field=models.ManyToManyField(to='management.Tag'),
        ),
        migrations.AddField(
            model_name='mobileapp',
            name='upload_by',
            field=models.ForeignKey(
                on_delete=django.db.models.deletion.CASCADE,
                to=settings.AUTH_USER_MODEL),
        ),
        migrations.AddField(
            model_name='evaluation',
            name='app',
            field=models.ForeignKey(
                on_delete=django.db.models.deletion.CASCADE,
                to='management.MobileApp'),
        ),
        migrations.AddField(
            model_name='evaluation',
            name='approved_by',
            field=models.ForeignKey(
                null=True,
                on_delete=django.db.models.deletion.CASCADE,
                related_name='checkedEvaluations',
                to=settings.AUTH_USER_MODEL),
        ),
        migrations.AddField(
            model_name='evaluation',
            name='created_by',
            field=models.ForeignKey(
                on_delete=django.db.models.deletion.CASCADE,
                related_name='createdEvaluations',
                to=settings.AUTH_USER_MODEL),
        ),
        migrations.AddField(
            model_name='download',
            name='app',
            field=models.ForeignKey(
                null=True,
                on_delete=django.db.models.deletion.CASCADE,
                to='management.MobileApp'),
        ),
        migrations.AddField(
            model_name='comment',
            name='app',
            field=models.ForeignKey(
                on_delete=django.db.models.deletion.CASCADE,
                to='management.MobileApp'),
        ),
        migrations.AddField(
            model_name='comment',
            name='approved_by',
            field=models.ForeignKey(
                null=True,
                on_delete=django.db.models.deletion.CASCADE,
                related_name='checkedComments',
                to=settings.AUTH_USER_MODEL),
        ),
        migrations.AddField(
            model_name='comment',
            name='created_by',
            field=models.ForeignKey(
                on_delete=django.db.models.deletion.CASCADE,
                related_name='createdComments',
                to=settings.AUTH_USER_MODEL),
        ),
        migrations.AddField(
            model_name='comment',
            name='evluation',
            field=models.ForeignKey(
                on_delete=django.db.models.deletion.CASCADE,
                to='management.Evaluation'),
        ),
        migrations.AddField(
            model_name='appversion',
            name='mobile_app',
            field=models.ForeignKey(
                null=True,
                on_delete=django.db.models.deletion.CASCADE,
                to='management.MobileApp'),
        ),
    ]
Beispiel #5
0
class Migration(migrations.Migration):

    initial = True

    dependencies = [
        ('menu', '0001_initial'),
    ]

    operations = [
        migrations.CreateModel(
            name='Brand',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('name', models.CharField(max_length=20)),
            ],
            options={
                'db_table': 'brands',
            },
        ),
        migrations.CreateModel(
            name='OptionColor',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('name', models.CharField(max_length=20)),
            ],
            options={
                'db_table': 'option_colors',
            },
        ),
        migrations.CreateModel(
            name='OptionSize',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('name', models.CharField(max_length=20, null=True)),
            ],
            options={
                'db_table': 'option_sizes',
            },
        ),
        migrations.CreateModel(
            name='Package',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('name', models.CharField(max_length=30)),
            ],
            options={
                'db_table': 'packages',
            },
        ),
        migrations.CreateModel(
            name='Product',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('name', models.CharField(max_length=30)),
                ('information', models.CharField(max_length=200)),
                ('information_image', models.URLField(max_length=256, null=True)),
                ('brand', models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to='product.brand')),
                ('package', models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to='product.package')),
            ],
            options={
                'db_table': 'products',
            },
        ),
        migrations.CreateModel(
            name='Sale',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('name', models.CharField(max_length=20)),
            ],
            options={
                'db_table': 'sales',
            },
        ),
        migrations.CreateModel(
            name='ProductImage',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('url', models.URLField(max_length=256)),
                ('product', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='product.product')),
            ],
            options={
                'db_table': 'product_images',
            },
        ),
        migrations.AddField(
            model_name='product',
            name='sale',
            field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to='product.sale'),
        ),
        migrations.AddField(
            model_name='product',
            name='sub_category',
            field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='menu.subcategory'),
        ),
        migrations.CreateModel(
            name='Option',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('price', models.FloatField()),
                ('option_color', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='product.optioncolor')),
                ('option_size', models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to='product.optionsize')),
                ('product', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='product.product')),
            ],
            options={
                'db_table': 'options',
            },
        ),
    ]
Beispiel #6
0
class Migration(migrations.Migration):

    initial = True

    dependencies = [
        migrations.swappable_dependency(settings.AUTH_USER_MODEL),
    ]

    operations = [
        migrations.CreateModel(
            name='Link',
            fields=[
                ('id',
                 models.AutoField(auto_created=True,
                                  primary_key=True,
                                  serialize=False,
                                  verbose_name='ID')),
                ('title',
                 models.CharField(max_length=50, verbose_name='\u6807\u9898')),
                ('href', models.URLField(verbose_name='\u94fe\u63a5')),
                ('status',
                 models.PositiveIntegerField(choices=[(1, '\u6b63\u5e38'),
                                                      (2, '\u5220\u9664')],
                                             default=1,
                                             verbose_name='\u72b6\u6001')),
                ('weight',
                 models.PositiveIntegerField(
                     choices=[(1, 1), (2, 2), (3, 3), (4, 4), (5, 5)],
                     default=1,
                     help_text=
                     '\u6743\u91cd\u8d8a\u9ad8\u663e\u793a\u7684\u8d8a\u9760\u524d',
                     verbose_name='\u6743\u91cd')),
                ('created_time',
                 models.DateTimeField(
                     auto_now_add=True,
                     verbose_name='\u521b\u5efa\u65f6\u95f4')),
                ('owner',
                 models.ForeignKey(on_delete=django.db.models.deletion.CASCADE,
                                   to=settings.AUTH_USER_MODEL,
                                   verbose_name='\u4f5c\u8005')),
            ],
            options={
                'verbose_name': '\u53cb\u94fe',
                'verbose_name_plural': '\u53cb\u94fe',
            },
        ),
        migrations.CreateModel(
            name='SiderBar',
            fields=[
                ('id',
                 models.AutoField(auto_created=True,
                                  primary_key=True,
                                  serialize=False,
                                  verbose_name='ID')),
                ('title',
                 models.CharField(max_length=50, verbose_name='\u6807\u9898')),
                ('display_type',
                 models.PositiveIntegerField(
                     choices=[(1, 'HTML'), (2, '\u6700\u65b0\u6587\u7ae0'),
                              (3, '\u6700\u70ed\u6587\u7ae0'),
                              (4, '\u6700\u8fd1\u8bc4\u8bba')],
                     default=1,
                     verbose_name='\u5c55\u793a\u7c7b\u578b')),
                ('content',
                 models.CharField(
                     blank=True,
                     help_text=
                     '\u5982\u679c\u8bbe\u7f6e\u7684\u7c7b\u578b\u4e0d\u662fHTML\u7c7b\u578b\uff0c\u53ef\u4e3a\u7a7a',
                     max_length=500,
                     verbose_name='\u5185\u5bb9')),
                ('created_time',
                 models.DateTimeField(
                     auto_now_add=True,
                     verbose_name='\u521b\u5efa\u65f6\u95f4')),
                ('owner',
                 models.ForeignKey(on_delete=django.db.models.deletion.CASCADE,
                                   to=settings.AUTH_USER_MODEL,
                                   verbose_name='\u4f5c\u8005')),
            ],
            options={
                'verbose_name': '\u4fa7\u8fb9\u680f',
                'verbose_name_plural': '\u4fa7\u8fb9\u680f',
            },
        ),
    ]
class Migration(migrations.Migration):

    dependencies = [
        migrations.swappable_dependency(settings.AUTH_USER_MODEL),
        ('main', '0003_auto_20200307_0339'),
    ]

    operations = [
        migrations.AddField(
            model_name='map',
            name='create_date',
            field=models.DateTimeField(auto_now_add=True, null=True),
        ),
        migrations.AddField(
            model_name='map',
            name='owner',
            field=models.ForeignKey(
                default=1,
                on_delete=django.db.models.deletion.CASCADE,
                related_name='maps',
                to=settings.AUTH_USER_MODEL),
            preserve_default=False,
        ),
        migrations.AddField(
            model_name='project',
            name='create_date',
            field=models.DateTimeField(auto_now_add=True, null=True),
        ),
        migrations.AddField(
            model_name='project',
            name='uri',
            field=models.URLField(blank=True, null=True),
        ),
        migrations.CreateModel(
            name='ProjectUser',
            fields=[
                ('id',
                 models.AutoField(auto_created=True,
                                  primary_key=True,
                                  serialize=False,
                                  verbose_name='ID')),
                ('role',
                 models.CharField(choices=[('creator', 'Creator'),
                                           ('owner', 'Owner'),
                                           ('member', 'Team Member')],
                                  max_length=20)),
                ('project',
                 models.ForeignKey(default=-1,
                                   on_delete=django.db.models.deletion.CASCADE,
                                   related_name='projects',
                                   to='main.Project')),
                ('user',
                 models.ForeignKey(default=-1,
                                   on_delete=django.db.models.deletion.CASCADE,
                                   related_name='users',
                                   to=settings.AUTH_USER_MODEL)),
            ],
            options={
                'db_table': 'project_user',
                'managed': True,
            },
        ),
    ]
Beispiel #8
0
class Project(models.Model):
    """ A project, like a lab, is a somewhat vague concept that is still useful to describe
    scientific work.  Typically a project is the work of a single lab or a small group of
    closely collaborating labs.  Some projects will be focused around a particular organ.
    Others will be focused on technologies or on different states of the same cell type.
    Very often a successful project will be associated with a publication, or a record in
    one of the public gene expression or sequencing databases.
    """
    short_name = models.CharField(max_length=80)
    wrangling_status = models.ForeignKey(WranglingStatus, blank=True, null=True, default=None, on_delete=models.SET_NULL)
    comments = models.CharField(max_length=255, blank=True)
    status = models.ForeignKey(ProjectStatus, blank=True, null=True, default=None, on_delete=models.SET_NULL, related_name="state_reached")
    stars = models.IntegerField(blank=True,validators=[MinValueValidator(1),MaxValueValidator(5)], default=3)
    tags = models.ManyToManyField(Tag, blank=True)
    ticket_link = models.URLField(blank=True, null=True)
    primary_wrangler = models.ForeignKey(Wrangler, blank=True, null=True, default=None, on_delete=models.SET_NULL, related_name="wrangler1");
    secondary_wrangler = models.ForeignKey(Wrangler, blank=True, null=True, default=None, on_delete=models.SET_NULL, related_name="secondary_wrangler");
    contacts = models.ManyToManyField(Contributor, blank=True, related_name="projcontacts")
    first_contact_date = models.DateField(blank=True, null=True, default=None)
    last_contact_date = models.DateField(blank=True, null=True, default=None)
    questionnaire_comments = models.CharField(max_length=255, blank=True)
    questionnaire_date = models.DateField(blank=True, null=True, default=None)
    tAndC_comments = models.CharField("T&C", max_length=255, blank=True)
    tAndC_date = models.DateField("T&C date", blank=True, null=True, default=None)
    sheet_template = models.FileField(upload_to="uploads/project", blank=True, null=True, default=None)
    sheet_template_date = models.DateField(blank=True, null=True, default=None)
    sheet_from_lab = models.FileField(upload_to="uploads/project", blank=True, null=True, default=None)
    google_sheet_url  = models.URLField(blank=True, null=True, default=None)
    sheet_from_lab_date = models.DateField(blank=True, null=True, default=None)
    back_to_lab = models.FileField(upload_to="uploads/project", blank=True, null=True, default=None)
    back_to_lab_date = models.DateField(blank=True, null=True, default=None)
    lab_review_comments = models.CharField(max_length=255, blank=True)
    lab_review_date = models.DateField(blank=True, null=True, default=None)
    sheet_submitted = models.FileField(upload_to="uploads/project", blank=True, null=True, default=None)
    sheet_validated_date = models.DateField(blank=True, null=True, default=None)
    file_bucket = models.CharField('File bucket', max_length=255,blank=True, default="")
    staging_area_date = models.DateField(blank=True, null=True, default=None)
    submit_date = models.DateField(blank=True, null=True, default=None)
    submit_comments = models.CharField(max_length=255, blank=True)
    title = models.CharField(max_length=120)
    description = models.TextField()
    labs = models.ManyToManyField(Lab, blank=True)
    organ = models.ManyToManyField(Organ, blank=True)
    organ_part = models.ManyToManyField(OrganPart, blank=True)
    disease = models.ManyToManyField(Disease, blank=True)
    sample_type = models.ManyToManyField(SampleType, blank=True)
    preservation_method = models.ManyToManyField(PreservationMethod, blank=True)
    privacy = models.ForeignKey(Privacy, blank=True, null=True, default=None, on_delete=models.SET_NULL)
    project_source = models.ForeignKey(ProjectSourceType, blank=True, null=True, default=None, on_delete=models.SET_NULL)
    source_url = models.CharField(max_length=200, blank=True)
    cdna_library_prep = models.ManyToManyField(CdnaLibraryPrep, blank=True, verbose_name=' cDNA library prep')
    cells_expected = models.IntegerField(blank=True, default=0)
    publications = models.ManyToManyField(Publication, blank=True)
    contributors = models.ManyToManyField(Contributor)
    species = models.ManyToManyField(Species, blank=True)
    grants = models.ManyToManyField("Grant", blank=True, through="grant_funded_projects")
    google_drive_url = models.URLField(blank=True)
    urls = models.ManyToManyField(Url, blank=True)
    geo_series = models.CharField(max_length=10, blank=True, null=True, default=None)
    dbGap_accession = models.CharField(max_length=50, blank=True, null=True, default=None)
    array_express_accession = models.CharField(max_length=20, blank=True, null=True, default=None)
    ena_accession = models.CharField(max_length=10, blank=True, null=True, default=None)
    sra_accession = models.CharField(max_length=15, blank=True, null=True, default=None)
    ncbi_bioproject_accession = models.CharField(max_length=50, blank=True, null=True, default=None)
    cirm_accession = models.CharField(max_length=20, blank=True, null=True, default=None)
    ega_study_accesion = models.CharField(max_length=20, blank=True, null=True, default=None)

    def __str__(self):
       return self.short_name
class Migration(migrations.Migration):

    initial = True

    dependencies = [
    ]

    operations = [
        migrations.CreateModel(
            name='Genre',
            fields=[
                ('genre', models.CharField(max_length=20, primary_key=True, serialize=False)),
            ],
        ),
        migrations.CreateModel(
            name='JobApplication',
            fields=[
                ('company_name', models.CharField(default='guest', max_length=40)),
                ('details', models.CharField(default='guest', max_length=10000)),
                ('user_name', models.CharField(default='guest', max_length=20)),
                ('application_text', models.CharField(max_length=100000, primary_key=True, serialize=False)),
                ('email_user', models.EmailField(default='*****@*****.**', max_length=254)),
                ('pay_expected', models.IntegerField(default=0)),
                ('status', models.BooleanField(default=False)),
            ],
        ),
        migrations.CreateModel(
            name='JobDetails',
            fields=[
                ('company_name', models.CharField(max_length=20)),
                ('genre', models.CharField(max_length=20)),
                ('details', models.CharField(max_length=100000, primary_key=True, serialize=False)),
                ('pay', models.IntegerField(default=0)),
                ('deadline', models.IntegerField()),
                ('pub_date', models.DateTimeField(verbose_name='date published')),
            ],
        ),
        migrations.CreateModel(
            name='JobProvider',
            fields=[
                ('company_name', models.CharField(max_length=20, primary_key=True, serialize=False)),
                ('first_name', models.CharField(max_length=20)),
                ('last_name', models.CharField(max_length=20)),
                ('email_id', models.EmailField(max_length=254)),
                ('password', models.CharField(max_length=20)),
                ('address', models.TextField()),
                ('contact_number', models.IntegerField()),
            ],
        ),
        migrations.CreateModel(
            name='JobsCompleted',
            fields=[
                ('company_name', models.CharField(default='guest', max_length=40)),
                ('user_name', models.CharField(default='guest', max_length=20)),
                ('pay_given', models.IntegerField(default=0)),
                ('details', models.CharField(default='abcd', max_length=100000, primary_key=True, serialize=False)),
                ('date_accepted', models.DateTimeField(verbose_name='date accepted')),
                ('deadline', models.IntegerField(default=0)),
            ],
        ),
        migrations.CreateModel(
            name='JobSeeker',
            fields=[
                ('user_name', models.CharField(max_length=20, primary_key=True, serialize=False)),
                ('first_name', models.CharField(max_length=20)),
                ('last_name', models.CharField(max_length=20)),
                ('email_id', models.EmailField(max_length=254)),
                ('password', models.CharField(max_length=20)),
                ('address', models.TextField()),
                ('contact_number', models.IntegerField()),
            ],
        ),
        migrations.CreateModel(
            name='UserDetails',
            fields=[
                ('user_name', models.CharField(max_length=20, primary_key=True, serialize=False)),
                ('first_name', models.CharField(max_length=20)),
                ('last_name', models.CharField(max_length=20)),
                ('email_id', models.EmailField(max_length=254)),
                ('address', models.TextField()),
                ('contact_number', models.IntegerField(default=0)),
                ('img', models.ImageField(blank=True, default='media/default.png', height_field='height_field', null=True, upload_to='media/', width_field='width_field')),
                ('website_linked', models.URLField(default='No Website Linked')),
                ('height_field', models.IntegerField(default=100, null=True)),
                ('width_field', models.IntegerField(default=100, null=True)),
                ('user_introduction', models.CharField(default='No Introduction Added', max_length=20000)),
            ],
        ),
    ]
class Event(
        ExportModelOperationsMixin("event"),
        BaseAPIResource,
        LocationMixin,
        ImageMixin,
        DescriptionMixin,
        ContactMixin,
):
    """
    Model that represents an event
    """

    objects = EventManager()

    name = models.CharField(_("nom"),
                            max_length=255,
                            blank=False,
                            help_text=_("Le nom de l'événement"))

    VISIBILITY_ADMIN = "A"
    VISIBILITY_ORGANIZER = "O"
    VISIBILITY_PUBLIC = "P"
    VISIBILITY_CHOICES = (
        (VISIBILITY_ADMIN, "Caché"),
        (VISIBILITY_ORGANIZER, "Visible par les organisateurs"),
        (VISIBILITY_PUBLIC, "Public"),
    )

    visibility = models.CharField(
        "Visibilité",
        max_length=1,
        choices=VISIBILITY_CHOICES,
        default=VISIBILITY_PUBLIC,
    )

    subtype = models.ForeignKey(
        "EventSubtype",
        verbose_name="Sous-type",
        related_name="events",
        on_delete=models.PROTECT,
        default=get_default_subtype,
    )

    tags = models.ManyToManyField("EventTag",
                                  related_name="events",
                                  blank=True)

    start_time = CustomDateTimeField(_("date et heure de début"), blank=False)
    end_time = CustomDateTimeField(_("date et heure de fin"), blank=False)
    timezone = models.CharField(
        "Fuseau horaire",
        max_length=255,
        choices=((name, name) for name in pytz.all_timezones),
        default=timezone.get_default_timezone().zone,
        blank=False,
        null=False,
    )

    max_participants = models.IntegerField("Nombre maximum de participants",
                                           blank=True,
                                           null=True)
    allow_guests = models.BooleanField(
        "Autoriser les participant⋅e⋅s à inscrire des invité⋅e⋅s",
        default=False)
    facebook = FacebookEventField("Événement correspondant sur Facebook",
                                  blank=True)

    attendees = models.ManyToManyField("people.Person",
                                       related_name="events",
                                       through="RSVP")

    organizers = models.ManyToManyField("people.Person",
                                        related_name="organized_events",
                                        through="OrganizerConfig")
    organizers_groups = models.ManyToManyField(
        "groups.SupportGroup",
        related_name="organized_events",
        through="OrganizerConfig",
    )

    report_image = StdImageField(
        verbose_name=_("image de couverture"),
        blank=True,
        variations={
            "thumbnail": (400, 250),
            "banner": (1200, 400)
        },
        upload_to=report_image_path,
        help_text=_(
            "Cette image apparaîtra en tête de votre compte-rendu, et dans les partages que vous ferez du"
            " compte-rendu sur les réseaux sociaux."),
    )

    report_content = DescriptionField(
        verbose_name=_("compte-rendu de l'événement"),
        blank=True,
        allowed_tags="allowed_tags",
        help_text=
        _("Ajoutez un compte-rendu de votre événement. N'hésitez pas à inclure des photos."
          ),
    )

    report_summary_sent = models.BooleanField(
        "Le mail de compte-rendu a été envoyé", default=False)

    subscription_form = models.OneToOneField("people.PersonForm",
                                             null=True,
                                             blank=True,
                                             on_delete=models.PROTECT)
    payment_parameters = JSONField(
        verbose_name=_("Paramètres de paiement"),
        null=True,
        blank=True,
        help_text=EVENT_PAYMENT_PARAMETERS_DOCUMENTATION,
    )

    scanner_event = models.IntegerField(
        "L'ID de l'événement sur le logiciel de tickets",
        blank=True,
        null=True)
    scanner_category = models.IntegerField(
        "La catégorie que doivent avoir les tickets sur scanner",
        blank=True,
        null=True)

    enable_jitsi = models.BooleanField("Activer la visio-conférence",
                                       default=False)

    participation_template = models.TextField(
        _("Template pour la page de participation"), blank=True, null=True)

    do_not_list = models.BooleanField(
        "Ne pas lister l'événement",
        default=False,
        help_text=
        "L'événement n'apparaîtra pas sur la carte, ni sur le calendrier "
        "et ne sera pas cherchable via la recherche interne ou les moteurs de recherche.",
    )

    meta = JSONField(
        _("Informations supplémentaires."),
        default=dict,
        blank=True,
        encoder=CustomJSONEncoder,
    )

    FOR_USERS_ALL = "A"
    FOR_USERS_INSOUMIS = "I"
    FOR_USERS_2022 = "2"
    FOR_USERS_CHOICES = (
        (FOR_USERS_ALL, "Tous les utilisateurs"),
        (FOR_USERS_INSOUMIS, "Les insoumis⋅es"),
        (FOR_USERS_2022, "Les signataires « Nous Sommes Pour ! »"),
    )

    for_users = models.CharField(
        "Utilisateur⋅ices de la plateforme concerné⋅es par l'événement",
        default=FOR_USERS_ALL,
        max_length=1,
        blank=False,
        choices=FOR_USERS_CHOICES,
    )

    online_url = models.URLField(
        "Url de visio-conférence",
        default="",
        blank=True,
    )

    suggestion_segment = models.ForeignKey(
        to="mailing.Segment",
        verbose_name="Segment de suggestion",
        on_delete=models.SET_NULL,
        related_name="suggested_events",
        related_query_name="suggested_event",
        null=True,
        blank=True,
        help_text=("Segment des personnes auquel cet événement sera suggéré."),
    )

    class Meta:
        verbose_name = _("événement")
        verbose_name_plural = _("événements")
        ordering = ("-start_time", "-end_time")
        permissions = (
            # DEPRECIATED: every_event was set up as a potential solution to Rest Framework django permissions
            # Permission class default behaviour of requiring both global permissions and object permissions before
            # allowing users. Was not used in the end.s
            ("every_event", _("Peut éditer tous les événements")),
            ("view_hidden_event", _("Peut voir les événements non publiés")),
        )
        indexes = (
            models.Index(fields=["start_time", "end_time"],
                         name="events_datetime_index"),
            models.Index(fields=["end_time"], name="events_end_time_index"),
            models.Index(fields=["start_time", "end_time", "id"],
                         name="events_datetime_id_index"),
        )

    def __str__(self):
        return f"{self.name} ({self.get_display_date()})"

    def __repr__(self):
        return f"{self.__class__.__name__}(id={str(self.pk)!r}, name={self.name!r})"

    def to_ics(self, text_only_description=False):
        event_url = front_url("view_event", args=[self.pk], auto_login=False)
        organizer = Organizer(email=self.contact_email,
                              common_name=self.contact_name)
        if text_only_description:
            description = textify(self.description) + " " + event_url
        else:
            description = self.description + f"<p>{event_url}</p>"

        return ics.Event(
            name=self.name,
            begin=self.start_time,
            end=self.end_time,
            uid=str(self.pk),
            description=description,
            location=self.short_address,
            url=event_url,
            categories=[self.subtype.get_type_display()],
            geo=self.coordinates,
            organizer=organizer,
        )

    def _get_participants_counts(self):
        self.all_attendee_count, self.confirmed_attendee_count = (
            self.__class__.objects.with_participants().values_list(
                "all_attendee_count",
                "confirmed_attendee_count").get(id=self.id))

    @property
    def participants(self):
        if not hasattr(self, "all_attendee_count"):
            self._get_participants_counts()

        return self.all_attendee_count

    @property
    def participants_confirmes(self):
        if not hasattr(self, "confirmed_attendee_count"):
            self._get_participants_counts()

        return self.confirmed_attendee_count

    @property
    def type(self):
        return self.subtype.type

    @property
    def local_start_time(self):
        tz = pytz.timezone(self.timezone)
        return self.start_time.astimezone(tz)

    @property
    def local_end_time(self):
        tz = pytz.timezone(self.timezone)
        return self.end_time.astimezone(tz)

    def get_display_date(self):
        start_time = self.local_start_time
        end_time = self.local_end_time

        if start_time.date() == end_time.date():
            date = formats.date_format(start_time, "DATE_FORMAT")
            return _("le {date}, de {start_hour} à {end_hour} ({tz})").format(
                date=date,
                start_hour=formats.time_format(start_time, "TIME_FORMAT"),
                end_hour=formats.time_format(end_time, "TIME_FORMAT"),
                tz=self.timezone,
            )

        return _(
            "du {start_date}, {start_time} au {end_date}, {end_time} ({tz})"
        ).format(
            start_date=formats.date_format(start_time, "DATE_FORMAT"),
            start_time=formats.date_format(start_time, "TIME_FORMAT"),
            end_date=formats.date_format(end_time, "DATE_FORMAT"),
            end_time=formats.date_format(end_time, "TIME_FORMAT"),
            tz=self.timezone,
        )

    def get_simple_display_date(self):
        return _("le {date} à {time} ({tz})").format(
            date=formats.date_format(self.local_start_time, "DATE_FORMAT"),
            time=formats.time_format(self.local_start_time, "TIME_FORMAT"),
            tz=self.timezone,
        )

    def is_past(self):
        return timezone.now() > self.end_time

    def is_current(self):
        return self.start_time < timezone.now() < self.end_time

    def clean(self):
        if self.start_time and self.end_time and self.end_time < self.start_time:
            raise ValidationError({
                "end_time":
                _("La date de fin de l'événement doit être postérieure à sa date de début."
                  )
            })

    def get_price_display(self):
        if self.payment_parameters is None:
            return None

        base_price = self.payment_parameters.get("price", 0)
        min_price = base_price
        max_price = base_price

        for mapping in self.payment_parameters.get("mappings", []):
            prices = [m["price"] for m in mapping["mapping"]]
            min_price += min(prices)
            max_price += max(prices)

        if min_price == max_price == 0:
            if "free_pricing" in self.payment_parameters:
                return "Prix libre"
            else:
                return None

        if min_price == max_price:
            display = "{} €".format(floatformat(min_price / 100, 2))
        else:
            display = "de {} à {} €".format(floatformat(min_price / 100, 2),
                                            floatformat(max_price / 100, 2))

        if "free_pricing" in self.payment_parameters:
            display += " + montant libre"

        return display

    @property
    def is_free(self):
        return self.payment_parameters is None

    @property
    def is_2022(self):
        return self.for_users == self.FOR_USERS_2022

    def get_price(self, submission_data: dict = None):
        price = self.payment_parameters.get("price", 0)

        if submission_data is None:
            return price

        for mapping in self.payment_parameters.get("mappings", []):
            values = [
                submission_data.get(field) for field in mapping["fields"]
            ]

            d = {
                tuple(v for v in m["values"]): m["price"]
                for m in mapping["mapping"]
            }

            price += d[tuple(values)]

        if "free_pricing" in self.payment_parameters:
            field = self.payment_parameters["free_pricing"]
            price += max(0, int(submission_data.get(field, 0) * 100))

        return price

    def get_absolute_url(self):
        return front_url("view_event", args=[self.pk])

    def get_google_calendar_url(self):
        # https://github.com/InteractionDesignFoundation/add-event-to-calendar-docs/blob/master/services/google.md
        df = "%Y%m%dT%H%M00"
        start_time = self.local_start_time.strftime(df)
        end_time = self.local_end_time.strftime(df)

        details = f"{self.description}<p><a href={self.get_absolute_url()}>Page de l'événement</a></p>"
        if self.online_url:
            details += f"<p><a href={self.online_url}>Rejoindre en ligne</a></p>"

        query = {
            "action": "TEMPLATE",
            "ctz": self.timezone,
            "text": self.name,
            "dates": f"{start_time}/{end_time}",
            "location": self.short_address,
            "details": details,
            "sprop": f"website:{self.get_absolute_url()}",
        }

        return f"https://calendar.google.com/calendar/render?{urlencode(query)}&sprop=name:Action%20Populaire"

    def can_rsvp(self, person):
        return True

    def get_meta_image(self):
        if hasattr(self, "image") and self.image:
            return urljoin(settings.FRONT_DOMAIN, self.image.url)

        # Use content hash as cache key for the auto-generated meta image
        content = ":".join((
            self.name,
            self.location_zip,
            self.location_city,
            str(self.coordinates),
            str(self.start_time),
        ))
        content_hash = hashlib.sha1(content.encode("utf-8")).hexdigest()[:8]

        return front_url(
            "view_og_image_event",
            kwargs={
                "pk": self.pk,
                "cache_key": content_hash
            },
            absolute=True,
        )
Beispiel #11
0
class Event(models.Model):
    """
    Represents an event that has happened. For pull request and push, it
    relies on the webhook of the repo server (like GitHub). This function will
    then generate the event. It can also be a manually scheduled event that
    just takes the current status of the branch and creates an Event off of that.
    Jobs will be generated off of this table.
    """
    PULL_REQUEST = 0
    PUSH = 1
    MANUAL = 2
    RELEASE = 3
    CAUSE_CHOICES = (
        (PULL_REQUEST, 'Pull request'),
        (PUSH, 'Push'),
        (MANUAL, 'Scheduled'),
        (RELEASE, 'Release'),
    )
    description = models.CharField(max_length=200, default='', blank=True)
    # the user who initiated the event
    trigger_user = models.CharField(max_length=200, default='', blank=True)
    #the user associated with the build key
    build_user = models.ForeignKey(GitUser,
                                   related_name='events',
                                   on_delete=models.CASCADE)
    head = models.ForeignKey(Commit,
                             related_name='event_head',
                             on_delete=models.CASCADE)
    base = models.ForeignKey(Commit,
                             related_name='event_base',
                             on_delete=models.CASCADE)
    status = models.IntegerField(choices=JobStatus.STATUS_CHOICES,
                                 default=JobStatus.NOT_STARTED)
    complete = models.BooleanField(default=False)
    cause = models.IntegerField(choices=CAUSE_CHOICES, default=PULL_REQUEST)
    comments_url = models.URLField(null=True, blank=True)
    pull_request = models.ForeignKey(PullRequest,
                                     null=True,
                                     blank=True,
                                     related_name='events',
                                     on_delete=models.CASCADE)
    duplicates = models.IntegerField(default=0)
    # stores the actual json that gets sent from the server to create this event
    json_data = models.TextField(blank=True)
    changed_files = models.TextField(blank=True)
    update_branch_status = models.BooleanField(default=True)  # Ignored for PRs

    last_modified = models.DateTimeField(auto_now=True)
    created = models.DateTimeField(db_index=True, auto_now_add=True)

    def __str__(self):
        return '{} : {}'.format(self.CAUSE_CHOICES[self.cause][1],
                                str(self.head))

    class Meta:
        ordering = ['-created']
        get_latest_by = 'last_modified'
        unique_together = ['build_user', 'head', 'base', 'duplicates']

    def cause_str(self):
        if self.PUSH == self.cause:
            return 'Push {}'.format(self.base.branch.name)

        return self.CAUSE_CHOICES[self.cause][1]

    def is_manual(self):
        return self.MANUAL == self.cause

    def status_slug(self):
        return JobStatus.to_slug(self.status)

    def user(self):
        return self.head.user()

    def set_changed_files(self, file_list):
        self.changed_files = json.dumps(file_list, indent=2)

    def get_changed_files(self):
        if not self.changed_files:
            return []
        changed_files = json.loads(self.changed_files)
        return changed_files

    def set_json_data(self, data):
        self.json_data = json.dumps(data, indent=2)

    def get_json_data(self):
        if not self.json_data:
            return None
        data = json.loads(self.json_data)
        return data

    def get_job_depends_on(self):
        """
        For each job attached to this event, get a list of dependencies.
        Return:
          dict: jobs are keys with a list of jobs as values
        """
        depends_on = {}
        all_jobs = [j for j in self.jobs.all()]
        for j in all_jobs:
            deps = []
            for r in j.recipe.depends_on.all():
                for j2 in all_jobs:
                    if j2 != j and j2.recipe.filename == r.filename:
                        deps.append(j2)
            depends_on[j] = deps
        return depends_on

    def get_unrunnable_jobs(self):
        """
        Get a list of jobs that won't run due to failed dependencies.
        Return:
          list[Job]: jobs that won't run
        """
        wont_run = []
        depends = self.get_job_depends_on()
        # We want to check the whole dependecy chain.
        # So if we have j0 -> j1 -> j2 and j0 fails
        # we want the list to have j1 and j2.
        while True:
            added = False
            for job, deps in depends.items():
                if job in wont_run:
                    continue
                for d in deps:
                    if (d in wont_run
                            or (d.complete and d.status
                                in [JobStatus.FAILED, JobStatus.CANCELED])):
                        wont_run.append(job)
                        added = True
            if not added:
                break
        return wont_run

    @staticmethod
    def sorted_jobs(jobs):
        # Take advantage of python stable sorting
        # This used to be in a cmp() style function but python3 removed it.
        jobs = sorted(jobs, key=lambda obj: obj.pk)
        jobs = sorted(jobs, key=lambda obj: obj.config.name)
        jobs = sorted(jobs, key=lambda obj: obj.recipe.display_name)
        jobs = sorted(jobs, key=lambda obj: obj.recipe.priority, reverse=True)
        return jobs

    def get_sorted_jobs(self):
        """
        Get a list of job groups based on dependencies.
        These will be sorted by priority, then name
        Return:
          list: Each entry is a list of sorted jobs
        """
        job_depends = self.get_job_depends_on()
        added_jobs = set()
        other = []
        job_groups = []

        other = list(job_depends.keys())
        while other:
            new_other = []
            new_group = []
            for job in other:
                deps = set(job_depends.get(job, []))
                if deps.issubset(added_jobs):
                    new_group.append(job)
                else:
                    new_other.append(job)
            if not new_group:
                """
                If we haven't made any progress just stop.
                """
                new_group.extend(other)
                other = []
            else:
                other = new_other
            added_jobs |= set(new_group)
            job_groups.append(self.sorted_jobs(new_group))

        return job_groups

    def check_done(self):
        """
        Check to see if the event is done running jobs
        """
        unrunnable_jobs = self.get_unrunnable_jobs()
        for j in self.jobs.all():
            if not j.complete and j not in unrunnable_jobs:
                return False
        return True

    def set_complete_if_done(self):
        """
        If all the jobs are done, set the
        event to complete and update the status
        """
        ret = self.check_done()
        if ret:
            self.set_complete()
        return ret

    def status_from_jobs(self):
        """
        Get the status of the event
        assuming that the event is
        not done yet.
        """
        status = set()
        for job in self.jobs.all():
            status.add(job.status)

        return incomplete_status(status)

    def set_status(self, status=None):
        """
        Sets the status of the event.
        Also updates the status of any associated
        PR or branch
        """
        if status is None:
            self.status = self.status_from_jobs()
        else:
            self.status = status
        self.save()

        if self.pull_request:
            self.pull_request.set_status_from_event(self)
        elif self.update_branch_status:
            self.base.branch.status = self.status
            self.base.branch.save()

    def set_complete(self):
        """
        Set the event to complete
        and update the status along
        with associated branch of pull request
        """
        self.complete = True
        status = set()
        unrunnable_jobs = self.get_unrunnable_jobs()
        for j in self.jobs.all():
            if j.complete and j not in unrunnable_jobs:
                status.add(j.status)
        self.set_status(complete_status(status))

    def make_jobs_ready(self):
        """
        Marks jobs attached to an event as ready to run.

        Jobs are checked to see if dependencies are met and
        if so, then they are marked as ready.
        """

        if self.check_done():
            self.complete = True
            self.save()
            logger.info('Event {}: {} complete'.format(self.pk, self))
            return

        job_depends = self.get_job_depends_on()
        for job, deps in job_depends.items():
            if job.complete or job.ready or not job.active:
                continue
            ready = True
            for d in deps:
                if not d.complete or d.status not in [
                        JobStatus.FAILED_OK, JobStatus.SUCCESS
                ]:
                    logger.info(
                        'job {}: {} does not have depends met: {}'.format(
                            job.pk, job, d))
                    ready = False
                    break

            if ready:
                job.ready = ready
                job.save()
                logger.info('{}: {}: {} : ready: {} : on {}'.format(
                    job.event, job.pk, job, job.ready, job.recipe.repository))

    def auto_cancel_event_except_current(self):
        return self.base.branch.get_branch_setting(
            "auto_cancel_push_events_except_current", False)

    def auto_uncancel_previous_event(self):
        return self.base.branch.get_branch_setting(
            "auto_uncancel_previous_event", False)
class Migration(migrations.Migration):

    initial = True

    dependencies = [
    ]

    operations = [
        migrations.CreateModel(
            name='WebUser',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('password', models.CharField(max_length=128, verbose_name='password')),
                ('last_login', models.DateTimeField(blank=True, null=True, verbose_name='last login')),
                ('username', models.CharField(max_length=50, unique=True, verbose_name='用户名')),
                ('fullname', models.CharField(max_length=50, verbose_name='全名')),
                ('usertype', models.CharField(choices=[('A', '系统管理员'), ('M', '会议管理员'), ('R', '审查人'), ('D', '设计单位')], default='M', max_length=1)),
                ('is_active', models.BooleanField(default=True)),
            ],
            options={
                'verbose_name': '用户',
                'verbose_name_plural': '用户',
            },
        ),
        migrations.CreateModel(
            name='Comment',
            fields=[
                ('ID', models.URLField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False, verbose_name='ID')),
                ('sub_time', models.DateTimeField(verbose_name='提交时间')),
                ('last_update_time', models.DateTimeField(auto_now=True, verbose_name='最后更新时间')),
                ('content', models.TextField(verbose_name='内容')),
            ],
            options={
                'verbose_name': '专家意见',
                'verbose_name_plural': '专家意见',
            },
        ),
        migrations.CreateModel(
            name='Conference',
            fields=[
                ('ID', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False, verbose_name='ID')),
                ('name', models.CharField(max_length=100, verbose_name='会议名称')),
                ('equipment_stage', models.CharField(blank=True, choices=[('论证阶段', '论证阶段'), ('方案阶段', '方案阶段'), ('工程研制阶段', '工程研制阶段'), ('设计定型阶段', '设计定型阶段'), ('生产定型阶段', '生产定型阶段')], max_length=20, verbose_name='研制阶段')),
                ('review_name', models.CharField(max_length=100, verbose_name='评审名称')),
                ('begin_date', models.DateTimeField(verbose_name='开始时间')),
                ('end_date', models.DateTimeField(verbose_name='结束时间')),
                ('address', models.CharField(max_length=100, verbose_name='会议地址')),
                ('create_time', models.DateTimeField(auto_now_add=True, verbose_name='创建时间')),
                ('last_update_time', models.DateTimeField(auto_now=True, verbose_name='最后更新时间')),
                ('profile', models.TextField(blank=True, verbose_name='会议须知')),
            ],
            options={
                'verbose_name': '审查/评审会议',
                'verbose_name_plural': '审查/评审会议',
            },
        ),
        migrations.CreateModel(
            name='ConferenceGroupMember',
            fields=[
                ('slug', models.SlugField(primary_key=True, serialize=False, verbose_name='ID')),
                ('role', models.CharField(blank=True, choices=[('M', '组长'), ('V', '副组长'), ('E', '成员')], max_length=32, verbose_name='职位')),
                ('conference', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='group_set', to='review_conference.Conference', verbose_name='审查/评审会议')),
            ],
        ),
        migrations.CreateModel(
            name='Document',
            fields=[
                ('ID', models.URLField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False, verbose_name='ID')),
                ('title', models.CharField(max_length=100, verbose_name='题目')),
                ('create_time', models.DateTimeField(auto_now_add=True, verbose_name='创建时间')),
                ('last_update_time', models.DateTimeField(auto_now=True, verbose_name='最后更新时间')),
                ('memo', models.TextField(blank=True, verbose_name='备注')),
                ('file', models.FileField(blank=True, upload_to=review_conference.models.user_directory_path, verbose_name='文件')),
            ],
            options={
                'verbose_name': '技术文件',
                'verbose_name_plural': '技术文件',
            },
        ),
        migrations.CreateModel(
            name='Equipment',
            fields=[
                ('ID', models.URLField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False, verbose_name='ID')),
                ('name', models.CharField(max_length=100, verbose_name='名称')),
                ('create_time', models.DateTimeField(auto_now_add=True, verbose_name='创建时间')),
                ('last_update_time', models.DateTimeField(auto_now=True, verbose_name='最后更新时间')),
                ('memo', models.TextField(blank=True, verbose_name='备注')),
            ],
            options={
                'verbose_name': '技术设备',
                'verbose_name_plural': '技术设备',
            },
        ),
        migrations.CreateModel(
            name='ReviewGroup',
            fields=[
                ('ID', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False, verbose_name='ID')),
                ('name', models.CharField(max_length=32, verbose_name='名称')),
            ],
            options={
                'verbose_name': '评审组',
                'verbose_name_plural': '评审组',
            },
        ),
        migrations.CreateModel(
            name='Summary',
            fields=[
                ('ID', models.URLField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False, verbose_name='ID')),
                ('sub_time', models.DateTimeField(verbose_name='提交时间')),
                ('last_update_time', models.DateTimeField(auto_now=True, verbose_name='最后更新时间')),
                ('content', models.TextField(verbose_name='内容')),
                ('conference', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='review_conference.Conference', verbose_name='会议')),
                ('equipment', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='review_conference.Equipment', verbose_name='技术设备')),
            ],
            options={
                'verbose_name': '评审意见',
                'verbose_name_plural': '评审意见',
            },
        ),
        migrations.CreateModel(
            name='ConferenceManager',
            fields=[
                ('webuser_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to=settings.AUTH_USER_MODEL)),
                ('gender', models.CharField(blank=True, choices=[('男', '男'), ('女', '女')], max_length=4, verbose_name='性别')),
                ('organization', models.CharField(blank=True, max_length=50, verbose_name='工作单位')),
                ('department', models.CharField(blank=True, max_length=50, verbose_name='部门')),
                ('title', models.CharField(blank=True, max_length=20, verbose_name='职务/职称')),
                ('phone', models.CharField(blank=True, max_length=13, verbose_name='电话')),
                ('memo', models.TextField(blank=True, verbose_name='备注')),
            ],
            options={
                'verbose_name': '会议管理员',
                'verbose_name_plural': '会议管理员',
            },
            bases=('review_conference.webuser',),
        ),
        migrations.CreateModel(
            name='DesignOrganization',
            fields=[
                ('webuser_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to=settings.AUTH_USER_MODEL)),
                ('shortname', models.CharField(blank=True, max_length=50, verbose_name='简称')),
                ('address', models.CharField(blank=True, max_length=100, verbose_name='单位地址')),
                ('contactor', models.CharField(blank=True, max_length=20, verbose_name='联系人')),
                ('phone', models.CharField(blank=True, max_length=13, verbose_name='联系电话')),
                ('profile', models.TextField(blank=True, verbose_name='简介')),
            ],
            options={
                'verbose_name': '研制单位',
                'verbose_name_plural': '研制单位',
            },
            bases=('review_conference.webuser',),
        ),
        migrations.CreateModel(
            name='Reviewer',
            fields=[
                ('webuser_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to=settings.AUTH_USER_MODEL)),
                ('gender', models.CharField(blank=True, choices=[('男', '男'), ('女', '女')], max_length=4, verbose_name='性别')),
                ('type', models.CharField(blank=True, choices=[('主管机关', '主管机关'), ('军事代表', '军事代表'), ('承制单位', '承制单位'), ('承试单位', '承试单位'), ('使用部队', '使用部队')], max_length=10, verbose_name='类别')),
                ('organization', models.CharField(blank=True, max_length=50, verbose_name='工作单位')),
                ('department', models.CharField(blank=True, max_length=50, verbose_name='部门')),
                ('title', models.CharField(blank=True, max_length=20, verbose_name='职务/职称')),
                ('phone', models.CharField(blank=True, max_length=13, verbose_name='电话')),
                ('memo', models.TextField(blank=True, verbose_name='备注')),
            ],
            options={
                'verbose_name': '会议代表',
                'verbose_name_plural': '会议代表',
            },
            bases=('review_conference.webuser',),
        ),
        migrations.CreateModel(
            name='WebAdmin',
            fields=[
                ('webuser_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to=settings.AUTH_USER_MODEL)),
                ('gender', models.CharField(blank=True, choices=[('男', '男'), ('女', '女')], max_length=4, verbose_name='性别')),
                ('organization', models.CharField(blank=True, max_length=50, verbose_name='工作单位')),
                ('department', models.CharField(blank=True, max_length=50, verbose_name='部门')),
                ('title', models.CharField(blank=True, max_length=20, verbose_name='职务/职称')),
                ('phone', models.CharField(blank=True, max_length=13, verbose_name='电话')),
                ('memo', models.TextField(blank=True, verbose_name='备注')),
            ],
            options={
                'verbose_name': '系统管理员',
                'verbose_name_plural': '系统管理员',
            },
            bases=('review_conference.webuser',),
        ),
        migrations.AddField(
            model_name='summary',
            name='reviewer',
            field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL, verbose_name='评审专家'),
        ),
        migrations.AddField(
            model_name='document',
            name='equipment',
            field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, related_name='document_of_equipment', to='review_conference.Equipment', verbose_name='技术设备'),
        ),
        migrations.AddField(
            model_name='conferencegroupmember',
            name='group',
            field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='member_set', to='review_conference.ReviewGroup', verbose_name='评审组'),
        ),
        migrations.AddField(
            model_name='conference',
            name='documents',
            field=models.ManyToManyField(blank=True, related_name='document_of', to='review_conference.Document', verbose_name='技术文件'),
        ),
        migrations.AddField(
            model_name='conference',
            name='equipments',
            field=models.ManyToManyField(blank=True, related_name='equipment_of', to='review_conference.Equipment', verbose_name='技术设备'),
        ),
        migrations.AddField(
            model_name='conference',
            name='groups',
            field=models.ManyToManyField(blank=True, related_name='group_of', to='review_conference.ReviewGroup', verbose_name='评审组'),
        ),
        migrations.AddField(
            model_name='comment',
            name='conference',
            field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='review_conference.Conference', verbose_name='会议'),
        ),
        migrations.AddField(
            model_name='comment',
            name='equipment',
            field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='review_conference.Equipment', verbose_name='技术设备'),
        ),
        migrations.AddField(
            model_name='comment',
            name='reviewer',
            field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL, verbose_name='评审专家'),
        ),
        migrations.AddField(
            model_name='equipment',
            name='organization',
            field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='review_conference.DesignOrganization'),
        ),
        migrations.AddField(
            model_name='document',
            name='organization',
            field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, related_name='document_of_organization', to='review_conference.DesignOrganization', verbose_name='设计单位'),
        ),
        migrations.AddField(
            model_name='conferencegroupmember',
            name='member',
            field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='review_conference.Reviewer', verbose_name='成员'),
        ),
        migrations.AddField(
            model_name='conference',
            name='creator',
            field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, related_name='conference_creator', to='review_conference.ConferenceManager', verbose_name='创建人'),
        ),
        migrations.AddField(
            model_name='conference',
            name='last_updater',
            field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, related_name='conference_updater', to='review_conference.ConferenceManager', verbose_name='最后更新人'),
        ),
        migrations.AddField(
            model_name='conference',
            name='managers',
            field=models.ManyToManyField(blank=True, related_name='manager_of', to='review_conference.ConferenceManager', verbose_name='会务组'),
        ),
        migrations.AddField(
            model_name='conference',
            name='reviewers',
            field=models.ManyToManyField(blank=True, related_name='reviewer_of', to='review_conference.Reviewer', verbose_name='会议代表'),
        ),
    ]
class Migration(migrations.Migration):

    initial = True

    dependencies = [
    ]

    operations = [
        migrations.CreateModel(
            name='Album',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('display', models.BooleanField(default=True, verbose_name='Public')),
                ('title', models.CharField(max_length=100)),
                ('link', models.URLField()),
                ('cover_art', models.ImageField(blank=True, null=True, upload_to='cover-art-photos/')),
                ('release_date', models.DateField()),
                ('label', models.CharField(default='Interline Records', max_length=150)),
                ('created_at', models.DateTimeField(auto_now_add=True)),
                ('updated_at', models.DateTimeField(auto_now=True)),
            ],
        ),
        migrations.CreateModel(
            name='Artist',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('display_artist', models.BooleanField(default=False)),
                ('name', models.CharField(max_length=100)),
                ('slug', models.SlugField(null=True)),
                ('photo', models.ImageField(blank=True, null=True, upload_to='artist-photos/')),
                ('biography', models.TextField(blank=True, max_length=500, null=True)),
                ('contact_name', models.CharField(default='Interline Records', max_length=100, verbose_name='Contact / Management Name')),
                ('contact_link', models.URLField(default='https://www.interlinerecords.com', verbose_name='Contact / Management URL')),
                ('contact_email', models.EmailField(default='*****@*****.**', max_length=254, verbose_name='Contact / Management Email')),
                ('website', models.URLField(blank=True, null=True)),
                ('spotify', models.URLField(blank=True, null=True)),
                ('youtube', models.URLField(blank=True, null=True, verbose_name='YouTube')),
                ('bandcamp', models.URLField(blank=True, null=True)),
                ('itunes', models.URLField(blank=True, null=True, verbose_name='iTunes')),
                ('facebook', models.URLField(blank=True, null=True)),
                ('twitter', models.URLField(blank=True, null=True)),
                ('instagram', models.URLField(blank=True, null=True)),
                ('soundcloud', models.URLField(blank=True, null=True)),
                ('vimeo', models.URLField(blank=True, null=True)),
                ('created_at', models.DateTimeField(auto_now_add=True)),
                ('updated_at', models.DateTimeField(auto_now=True)),
            ],
        ),
        migrations.CreateModel(
            name='Video',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('display', models.BooleanField(default=True, verbose_name='Public')),
                ('title', models.CharField(max_length=100)),
                ('link', models.URLField()),
                ('description', models.CharField(blank=True, max_length=200, null=True)),
                ('video_service', models.CharField(choices=[('yt', 'Youtube'), ('vm', 'Vimeo')], default='yt', max_length=2)),
                ('created_at', models.DateTimeField(auto_now_add=True)),
                ('updated_at', models.DateTimeField(auto_now=True)),
                ('artist', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='videos', to='artists.Artist')),
            ],
        ),
        migrations.AddField(
            model_name='album',
            name='artist',
            field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='albums', to='artists.Artist'),
        ),
    ]
Beispiel #14
0
class Migration(migrations.Migration):

    initial = True

    dependencies = []

    operations = [
        migrations.CreateModel(
            name='Genre',
            fields=[
                ('id',
                 models.AutoField(auto_created=True,
                                  primary_key=True,
                                  serialize=False,
                                  verbose_name='ID')),
                ('genre_name',
                 models.CharField(choices=[('var', 'バラエティ'), ('mus', '音楽'),
                                           ('news', 'ニュース'), ('edu', '教育'),
                                           ('info', '情報'), ('hob', '趣味')],
                                  max_length=4,
                                  null=True,
                                  unique=True,
                                  verbose_name='ジャンル')),
            ],
        ),
        migrations.CreateModel(
            name='Program',
            fields=[
                ('id',
                 models.AutoField(auto_created=True,
                                  primary_key=True,
                                  serialize=False,
                                  verbose_name='ID')),
                ('title', models.CharField(max_length=200,
                                           verbose_name='番組名')),
                ('corner_title',
                 models.CharField(blank=True,
                                  max_length=200,
                                  null=True,
                                  verbose_name='コーナー名')),
                ('address',
                 models.EmailField(blank=True,
                                   max_length=254,
                                   null=True,
                                   verbose_name='メールアドレス')),
                ('url',
                 models.URLField(blank=True,
                                 null=True,
                                 verbose_name='公式Webページ')),
                ('created_date',
                 models.DateTimeField(blank=True,
                                      default=django.utils.timezone.now,
                                      null=True,
                                      verbose_name='作成時間')),
                ('published_date',
                 models.DateTimeField(blank=True,
                                      default=django.utils.timezone.now,
                                      null=True,
                                      verbose_name='更新時間')),
                ('genrelist',
                 models.ManyToManyField(blank=True,
                                        related_name='genres',
                                        to='myapp.Genre',
                                        verbose_name='ジャンル')),
            ],
        ),
        migrations.CreateModel(
            name='Week',
            fields=[
                ('id',
                 models.AutoField(auto_created=True,
                                  primary_key=True,
                                  serialize=False,
                                  verbose_name='ID')),
                ('weeks',
                 models.IntegerField(choices=[(1, '月'), (2, '火'), (3, '水'),
                                              (4, '木'), (5, '金'), (6, '土'),
                                              (7, '日')],
                                     null=True,
                                     unique=True,
                                     verbose_name='曜日')),
            ],
        ),
        migrations.CreateModel(
            name='Station',
            fields=[
                ('id',
                 models.AutoField(auto_created=True,
                                  primary_key=True,
                                  serialize=False,
                                  verbose_name='ID')),
                ('station_name',
                 models.IntegerField(choices=[(0, '指定なし'), (1, 'TBSラジオ'),
                                              (2, 'ニッポン放送'), (3, '文化放送'),
                                              (4, 'NHK')],
                                     verbose_name='ラジオ局')),
                ('start_time',
                 models.TimeField(blank=True, null=True, verbose_name='開始時間')),
                ('end_time',
                 models.TimeField(blank=True, null=True, verbose_name='終了時間')),
                ('day_of_the_week',
                 models.ManyToManyField(blank=True,
                                        related_name='day_of_the_weeks',
                                        to='myapp.Week',
                                        verbose_name='曜日')),
                ('program',
                 models.ForeignKey(on_delete=django.db.models.deletion.CASCADE,
                                   related_name='stations',
                                   to='myapp.Program')),
            ],
        ),
        migrations.CreateModel(
            name='Listener',
            fields=[
                ('id',
                 models.AutoField(auto_created=True,
                                  primary_key=True,
                                  serialize=False,
                                  verbose_name='ID')),
                ('listener_name',
                 models.CharField(max_length=100, verbose_name='主なハガキ職人')),
                ('program',
                 models.ForeignKey(on_delete=django.db.models.deletion.CASCADE,
                                   related_name='listeners',
                                   to='myapp.Program')),
            ],
        ),
        migrations.CreateModel(
            name='Dj',
            fields=[
                ('id',
                 models.AutoField(auto_created=True,
                                  primary_key=True,
                                  serialize=False,
                                  verbose_name='ID')),
                ('dj_name', models.CharField(max_length=100,
                                             verbose_name='出演者')),
                ('main_dj', models.BooleanField(verbose_name='メインパーソナリティ')),
                ('program',
                 models.ForeignKey(on_delete=django.db.models.deletion.CASCADE,
                                   related_name='djs',
                                   to='myapp.Program')),
            ],
        ),
        migrations.CreateModel(
            name='Comment',
            fields=[
                ('id',
                 models.AutoField(auto_created=True,
                                  primary_key=True,
                                  serialize=False,
                                  verbose_name='ID')),
                ('author', models.CharField(max_length=200)),
                ('text', models.TextField()),
                ('created_date',
                 models.DateTimeField(default=django.utils.timezone.now)),
                ('approved_comment', models.BooleanField(default=False)),
                ('program',
                 models.ForeignKey(on_delete=django.db.models.deletion.CASCADE,
                                   related_name='comments',
                                   to='myapp.Program')),
            ],
        ),
    ]
Beispiel #15
0
class Schema(models.Model):

    EXPERIMENT = 1
    DATASET = 2
    DATAFILE = 3
    NONE = 4
    _SCHEMA_TYPES = (
        (EXPERIMENT, 'Experiment schema'),
        (DATASET, 'Dataset schema'),
        (DATAFILE, 'Datafile schema'),
        (NONE, 'None')
    )

    namespace = models.URLField(unique=True,
                                verify_exists=False,
                                max_length=255)
    name = models.CharField(blank=True, null=True, max_length=50)
    type = models.IntegerField(
        choices=_SCHEMA_TYPES, default=EXPERIMENT)

    # subtype will be used for categorising the type of experiment, dataset
    # or datafile schemas. for example, the type of beamlines are usually used
    # further categorise the experiment, dataset, and datafile schemas. the
    # subtype might then allow for the following values: 'mx', 'ir', 'saxs'
    subtype = models.CharField(blank=True, null=True, max_length=30)
    objects = SchemaManager()
    immutable = models.BooleanField(default=False)
    

    def natural_key(self):
        return (self.namespace,)

    def _getSchemaTypeName(self, typeNum):
        return dict(self._SCHEMA_TYPES)[typeNum]

    @classmethod
    def getSubTypes(cls):
        return set([schema.subtype for schema in Schema.objects.all() \
            if schema.subtype])

    @classmethod
    def getNamespaces(cls, type, subtype=None):
        """Return the list of namespaces for equipment, sample, and experiment
        schemas.

        """
        if subtype:
            return [schema.namespace for schema in
                    Schema.objects.filter(type=type, subtype=subtype)]
        else:
            return [schema.namespace for schema in
                    Schema.objects.filter(type=type)]

    def __unicode__(self):
        return self._getSchemaTypeName(self.type) + (self.subtype and ' for ' +
            self.subtype.upper() or '') + ': ' + self.namespace

    class UnsupportedType(Exception):

        def __init__(self, msg):
            Exception.__init__(self, msg)
class Migration(migrations.Migration):

    dependencies = [
        migrations.swappable_dependency(settings.AUTH_USER_MODEL),
        ('core', '0017_drop_oidc_fields'),
        ('course_metadata', '0225_credit_not_verified'),
    ]

    operations = [
        migrations.CreateModel(
            name='HistoricalOrganization',
            fields=[
                ('id',
                 models.IntegerField(auto_created=True,
                                     blank=True,
                                     db_index=True,
                                     verbose_name='ID')),
                ('created',
                 django_extensions.db.fields.CreationDateTimeField(
                     auto_now_add=True, verbose_name='created')),
                ('modified',
                 django_extensions.db.fields.ModificationDateTimeField(
                     auto_now=True, verbose_name='modified')),
                ('uuid',
                 models.UUIDField(default=uuid.uuid4,
                                  editable=False,
                                  verbose_name='UUID')),
                ('key',
                 models.CharField(
                     help_text=
                     "Please do not use any spaces or special characters other than period, underscore or hyphen. This key will be used in the course's course key.",
                     max_length=255)),
                ('name', models.CharField(max_length=255)),
                ('description', models.TextField(blank=True, null=True)),
                ('homepage_url',
                 models.URLField(blank=True, max_length=255, null=True)),
                ('logo_image_url', models.URLField(blank=True, null=True)),
                ('banner_image_url', models.URLField(blank=True, null=True)),
                ('certificate_logo_image_url',
                 models.URLField(
                     blank=True,
                     help_text=
                     'Logo to be displayed on certificates. If this logo is the same as logo_image_url, copy and paste the same value to both fields.',
                     null=True)),
                ('salesforce_id',
                 models.CharField(blank=True, max_length=255, null=True)),
                ('auto_generate_course_run_keys',
                 models.BooleanField(
                     default=True,
                     help_text=
                     'When this flag is enabled, the key of a new course run will be auto generated.  When this flag is disabled, the key can be manually set.',
                     verbose_name='Automatically generate course run keys')),
                ('history_id',
                 models.AutoField(primary_key=True, serialize=False)),
                ('history_date', models.DateTimeField()),
                ('history_change_reason',
                 models.CharField(max_length=100, null=True)),
                ('history_type',
                 models.CharField(choices=[('+', 'Created'), ('~', 'Changed'),
                                           ('-', 'Deleted')],
                                  max_length=1)),
                ('history_user',
                 models.ForeignKey(
                     null=True,
                     on_delete=django.db.models.deletion.SET_NULL,
                     related_name='+',
                     to=settings.AUTH_USER_MODEL)),
                ('partner',
                 models.ForeignKey(
                     blank=True,
                     db_constraint=False,
                     null=True,
                     on_delete=django.db.models.deletion.DO_NOTHING,
                     related_name='+',
                     to='core.Partner')),
            ],
            options={
                'verbose_name': 'historical organization',
                'get_latest_by': 'history_date',
                'ordering': ('-history_date', '-history_id'),
            },
            bases=(simple_history.models.HistoricalChanges, models.Model),
        ),
    ]
class Migration(migrations.Migration):

    initial = True

    dependencies = [
        migrations.swappable_dependency(settings.AUTH_USER_MODEL),
        ('contenttypes', '0001_initial'),
    ]

    operations = [
        migrations.CreateModel(
            name='Alert',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('created', model_utils.fields.AutoCreatedField(default=django.utils.timezone.now, editable=False, verbose_name='created')),
                ('modified', model_utils.fields.AutoLastModifiedField(default=django.utils.timezone.now, editable=False, verbose_name='modified')),
                ('uuid', waldur_core.core.fields.UUIDField()),
                ('alert_type', models.CharField(db_index=True, max_length=50)),
                ('message', models.CharField(max_length=255)),
                ('severity', models.SmallIntegerField(choices=[(10, 'Debug'), (20, 'Info'), (30, 'Warning'), (40, 'Error')])),
                ('closed', models.DateTimeField(blank=True, null=True)),
                ('is_closed', models.CharField(blank=True, max_length=32)),
                ('acknowledged', models.BooleanField(default=False)),
                ('context', waldur_core.core.fields.JSONField(blank=True)),
                ('object_id', models.PositiveIntegerField(null=True)),
                ('content_type', models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, to='contenttypes.ContentType')),
            ],
        ),
        migrations.CreateModel(
            name='EmailHook',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('created', model_utils.fields.AutoCreatedField(default=django.utils.timezone.now, editable=False, verbose_name='created')),
                ('modified', model_utils.fields.AutoLastModifiedField(default=django.utils.timezone.now, editable=False, verbose_name='modified')),
                ('uuid', waldur_core.core.fields.UUIDField()),
                ('event_types', waldur_core.core.fields.JSONField(verbose_name='List of event types')),
                ('event_groups', waldur_core.core.fields.JSONField(default=[], verbose_name='List of event groups')),
                ('is_active', models.BooleanField(default=True)),
                ('last_published', models.DateTimeField(default=django.utils.timezone.now)),
                ('email', models.EmailField(max_length=75)),
                ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
            ],
            options={
                'abstract': False,
            },
        ),
        migrations.CreateModel(
            name='PushHook',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('created', model_utils.fields.AutoCreatedField(default=django.utils.timezone.now, editable=False, verbose_name='created')),
                ('modified', model_utils.fields.AutoLastModifiedField(default=django.utils.timezone.now, editable=False, verbose_name='modified')),
                ('uuid', waldur_core.core.fields.UUIDField()),
                ('event_types', waldur_core.core.fields.JSONField(verbose_name='List of event types')),
                ('event_groups', waldur_core.core.fields.JSONField(default=[], verbose_name='List of event groups')),
                ('is_active', models.BooleanField(default=True)),
                ('last_published', models.DateTimeField(default=django.utils.timezone.now)),
                ('type', models.SmallIntegerField(choices=[(1, 'iOS'), (2, 'Android')])),
                ('device_id', models.CharField(max_length=255, null=True, unique=True)),
                ('device_manufacturer', models.CharField(blank=True, max_length=255, null=True)),
                ('device_model', models.CharField(blank=True, max_length=255, null=True)),
                ('token', models.CharField(max_length=255, null=True, unique=True)),
                ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
            ],
        ),
        migrations.CreateModel(
            name='SystemNotification',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('event_types', waldur_core.core.fields.JSONField(verbose_name='List of event types')),
                ('event_groups', waldur_core.core.fields.JSONField(default=[], verbose_name='List of event groups')),
                ('hook_content_type', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, related_name='+', to='contenttypes.ContentType')),
            ],
            options={
                'abstract': False,
            },
        ),
        migrations.CreateModel(
            name='WebHook',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('created', model_utils.fields.AutoCreatedField(default=django.utils.timezone.now, editable=False, verbose_name='created')),
                ('modified', model_utils.fields.AutoLastModifiedField(default=django.utils.timezone.now, editable=False, verbose_name='modified')),
                ('uuid', waldur_core.core.fields.UUIDField()),
                ('event_types', waldur_core.core.fields.JSONField(verbose_name='List of event types')),
                ('event_groups', waldur_core.core.fields.JSONField(default=[], verbose_name='List of event groups')),
                ('is_active', models.BooleanField(default=True)),
                ('last_published', models.DateTimeField(default=django.utils.timezone.now)),
                ('destination_url', models.URLField()),
                ('content_type', models.SmallIntegerField(choices=[(1, 'json'), (2, 'form')], default=1)),
                ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
            ],
            options={
                'abstract': False,
            },
        ),
        migrations.AlterUniqueTogether(
            name='pushhook',
            unique_together=set([('user', 'device_id', 'type')]),
        ),
        migrations.AlterUniqueTogether(
            name='alert',
            unique_together=set([('content_type', 'object_id', 'alert_type', 'is_closed')]),
        ),
    ]
Beispiel #18
0
class Event(models.Model):

    filter_central = models.BooleanField(default=False, help_text="This event is central to the discussion")
    blockquote = models.TextField(blank=True)

    url = models.URLField(blank=True, help_text="Most events should have one")
    media_outlet = models.CharField(max_length = 100, blank=True, help_text="Try to make sure that you use the same spelling and capitalization as previous events in the same outlet")
    author = models.CharField(max_length = 100, blank=True)

    filtersets = models.ManyToManyField(Filterset, blank=True)
    timeline = models.ForeignKey(Timeline, related_name="event") 
    outlet = models.ForeignKey(Outlet, related_name="outlet", null=True) 
    cleared_for_publication = models.BooleanField(default=False)

    headline = models.CharField(max_length = 300, blank=True, help_text="The headline that is to be displayed on the timeline, NOT the headline of the orignial article. In most cases you do not have to specify this as it's constructed from the AUTHOR and MEDIAOUTLET fields")
    #startdate =  models.DateTimeField()
    #startdate_specificity = models.CharField(max_length=30, choices=DATE_SPECIFICITY_CHOICES, default=DATE_SPECIFICITY_CHOICE_DAY)
    text = models.TextField(blank=True)
    
   
    media = models.URLField(blank=True)
    image = models.ImageField(upload_to="images/timeline/", null=True, blank=True )
    caption = models.CharField(max_length = 400, blank=True, help_text="If you've added an image the caption goes here")
    credit = models.CharField(max_length = 400, blank=True, help_text="If you've added an image the credit for the image goes here") 

        
    
   
    startdate_copy = models.DateTimeField(editable=False, default=datetime.datetime.now)



    facebook_total_count = models.IntegerField(default=-1,editable=False)

    added_by = models.ForeignKey(User, related_name="event",  null=True, blank=True, editable=False)

    arguments = models.ManyToManyField(Argument, blank=True)
    
    html_raw = models.TextField(null=True, blank=True)
    text_headline = models.TextField(null=True, blank=True)
    text_body = models.TextField(null=True, blank=True)
    text_byline  = models.TextField(null=True, blank=True)


    
    def populate_text_helper(self, selector, targetattr):
        jQuery = PyQuery(self.html_raw)
        text = jQuery(selector.encode("ascii")).text()

        #print self.html_raw[:100]
        print "-"*100
        try:
            print text[:100]
        except:
            pass
        setattr(self, targetattr, text)
        self.save()

    def populate_text_headline(self):
        self.populate_text_helper(self.outlet.selector_headline, "text_headline")

    def populate_text_body(self):
        self.populate_text_helper(self.outlet.selector_body, "text_body")


    def populate_text_byline(self):
        self.populate_text_helper(self.outlet.selector_byline, "text_byline")
   
    def populate_text(self):
        if self.html_raw != None:
            if self.outlet != None:
                print "="*100
                if self.outlet.selector_body != None:
                    self.populate_text_body()

                if self.outlet.selector_headline != None:
                    self.populate_text_headline()

                if self.outlet.selector_byline != None:
                    self.populate_text_byline()

    def filterset_repr(self):
        return string.join([item.title for item in self.filtersets.all() if item.title != "everything"], ", ")

    def url_repr(self):
        if self.url != "":
            return "<a href='{0}'>link</a>".format(self.url)
        else:
            return ""

    url_repr.allow_tags = True

    def live_view(self):
        return "<a href='/thedebate/filtered/id/{0}/'>live</a>".format(self.pk)

    live_view.allow_tags = True

    def save(self, *args, **kwargs):
        try:
            self.startdate_copy = self.get_startdate()
        except:
            pass

        super(Event, self).save(*args, **kwargs)

    def get_startdate(self):
        return (self.startdate.get()).datetime

    def url_truncated(self, length=100):
        #if len(url) > length:
            #start = url
        return self.url[:40]
    
    def get_headline(self):
        if self.headline:
            return self.headline
        elif self.author and self.media_outlet:
            if "blogg" in self.media_outlet:
                prep = u" på "
            else:
                prep = " i "
            return self.author +  prep + self.media_outlet
        else:
            return "Rubbe Rubbe Rubbe"
    
    
    def get_json(self):
        
        if self.image:
            media = self.image.url
        elif self.blockquote:
            media = u"<blockquote>{0}</blockquote>".format(escape_chars(self.blockquote))
        else:
            media = self.media
        
        #datestr = get_datestr(self.startdate, self.startdate_specificity)
        datestr = self.startdate.all()[0].json_dumps()

        text = self.text
        translateurl = "http://translate.google.com/translate?sl=sv&tl=en&js=n&prev=_t&hl=sv&ie=UTF-8&layout=2&eotf=1&u={0}".format(self.url)
        if self.facebook_total_count >  0:
            fbcount = "<p>facebook likes: {0}</p>".format(self.facebook_total_count)
        else:
            fbcount = ""

        if self.url:
            text += u"<p><a href='{0}'>länk</a>".format(self.url)

        #if request.user.is_staff():
            #text += "<p>edit</p>"

        result = u"""
        {{
        "startDate": "{date}",
        "headline": "{headline}",
        "text": {text},
        "asset":
        {{
            "media":"{media}",
            "credit":"{credit}",
            "caption":"{caption}"
        }}
        }}
        """.format(date=datestr, 
                  headline=self.get_headline(),
                  text=escape_text(text),
                  media=media,
                  credit=self.credit,
                  caption=self.caption)
        return result
class Migration(migrations.Migration):

    initial = True

    dependencies = [
        ('chat_user_profile', '0001_initial'),
    ]

    operations = [
        migrations.CreateModel(
            name='Message',
            fields=[
                ('id',
                 models.AutoField(auto_created=True,
                                  primary_key=True,
                                  serialize=False,
                                  verbose_name='ID')),
                ('message', models.TextField()),
                ('attachment', models.URLField()),
                ('is_draft', models.BooleanField()),
                ('is_delivered', models.BooleanField()),
                ('is_read', models.BooleanField()),
                ('timestamp_created', models.DateTimeField(auto_now_add=True)),
                ('timestamp_delivered', models.DateTimeField()),
                ('timestamp_read', models.DateTimeField()),
            ],
        ),
        migrations.CreateModel(
            name='Thread',
            fields=[
                ('id',
                 models.AutoField(auto_created=True,
                                  primary_key=True,
                                  serialize=False,
                                  verbose_name='ID')),
                ('name', models.CharField(max_length=255)),
                ('thread_photo', models.URLField()),
                ('timestamp_created', models.DateTimeField(auto_now_add=True)),
            ],
        ),
        migrations.CreateModel(
            name='ThreadMember',
            fields=[
                ('id',
                 models.AutoField(auto_created=True,
                                  primary_key=True,
                                  serialize=False,
                                  verbose_name='ID')),
                ('is_admin', models.BooleanField()),
                ('timestamp_joined', models.DateTimeField(auto_now_add=True)),
                ('timestamp_left', models.DateTimeField()),
                ('last_rejoined', models.DateTimeField()),
                ('profile',
                 models.ForeignKey(on_delete=django.db.models.deletion.CASCADE,
                                   related_name='threadmember_profile',
                                   to='chat_user_profile.Profile')),
                ('thread',
                 models.ForeignKey(on_delete=django.db.models.deletion.CASCADE,
                                   related_name='threadmember_thread',
                                   to='chat.Thread')),
            ],
        ),
        migrations.CreateModel(
            name='ThreadAction',
            fields=[
                ('id',
                 models.AutoField(auto_created=True,
                                  primary_key=True,
                                  serialize=False,
                                  verbose_name='ID')),
                ('action', models.CharField(max_length=7)),
                ('timestamp_action', models.DateTimeField(auto_now_add=True)),
                ('profile',
                 models.ForeignKey(on_delete=django.db.models.deletion.CASCADE,
                                   related_name='threadaction_profile',
                                   to='chat_user_profile.Profile')),
                ('thread',
                 models.ForeignKey(on_delete=django.db.models.deletion.CASCADE,
                                   related_name='threadaction_thread',
                                   to='chat.Thread')),
            ],
        ),
        migrations.CreateModel(
            name='MessageAction',
            fields=[
                ('id',
                 models.AutoField(auto_created=True,
                                  primary_key=True,
                                  serialize=False,
                                  verbose_name='ID')),
                ('action', models.CharField(max_length=7)),
                ('timestamp_action', models.DateTimeField(auto_now_add=True)),
                ('message',
                 models.ForeignKey(on_delete=django.db.models.deletion.CASCADE,
                                   related_name='messageaction_message',
                                   to='chat.Message')),
                ('profile',
                 models.ForeignKey(on_delete=django.db.models.deletion.CASCADE,
                                   related_name='messageaction_profile',
                                   to='chat_user_profile.Profile')),
            ],
        ),
        migrations.AddField(
            model_name='message',
            name='sent_by',
            field=models.ForeignKey(
                on_delete=django.db.models.deletion.CASCADE,
                related_name='message_sent_by',
                to='chat.ThreadMember'),
        ),
        migrations.AddField(
            model_name='message',
            name='thread',
            field=models.ForeignKey(
                on_delete=django.db.models.deletion.CASCADE,
                related_name='message_thread',
                to='chat.Thread'),
        ),
        migrations.CreateModel(
            name='ForwardedMessage',
            fields=[
                ('id',
                 models.AutoField(auto_created=True,
                                  primary_key=True,
                                  serialize=False,
                                  verbose_name='ID')),
                ('timestamp_forwarded',
                 models.DateTimeField(auto_now_add=True)),
                ('forwarded_by',
                 models.ForeignKey(
                     on_delete=django.db.models.deletion.CASCADE,
                     related_name='forwardedmessage_forwarded_by',
                     to='chat_user_profile.Profile')),
                ('forwarded_to',
                 models.ForeignKey(
                     on_delete=django.db.models.deletion.CASCADE,
                     related_name='forwardedmessage_forwarded_to',
                     to='chat.Thread')),
                ('message',
                 models.ForeignKey(on_delete=django.db.models.deletion.CASCADE,
                                   related_name='forwardedmessage_message',
                                   to='chat.Message')),
            ],
        ),
    ]
Beispiel #20
0
class Timeline(models.Model):
    headline = models.CharField(max_length = 300)
    type = models.CharField(max_length = 20, default="default")
    text = models.TextField()
    media = models.URLField(blank=True)
    blockquote = models.TextField(blank=True)
    credit = models.CharField(max_length = 400, blank=True) 
    caption = models.CharField(max_length = 400, blank=True)

    def __unicode__(self):
        return u"{0}".format(self.headline)



    
    def get_json_id(self,  pk):
        #pk = int(kwargs['id'])
        qs = self.event.filter(id=pk)
        return self.get_json_qs(qs)

    def get_json_qs(self, qs):

        datestr = self.startdate.all()[0].json_dumps()
        eventsjson = []
        for event in qs:
            eventsjson.append(event.get_json())
        eventsjsonstr = u",\n".join(eventsjson)

        result = u"""
        {{
        "timeline":
        {{
            "startDate": "{date}",
            "type":"default",
            "headline": "{headline}",
            "text": {text},
            "asset":
            {{
                "media":"{media}",
                "credit":"{credit}",
                "caption":"{caption}"
            }},
        "date": [
        {dates}
        ]
        }}
        }}
        """.format(date=datestr,
                  headline=self.headline,
                  text=escape_text(self.text),
                  media=self.media,
                  credit=self.credit,
                  caption=self.caption,
                  dates=eventsjsonstr)
        return result

    def get_json_filterset(self, filterset):
        qs = self.event.filter(cleared_for_publication=True, filtersets__title=filterset)
        return self.get_json_qs(qs)

    def get_json(self):
        qs = self.event.filter(cleared_for_publication=True, filter_central=True)
        return self.get_json_qs(qs)
class Migration(migrations.Migration):

    dependencies = [
        ('user_groups', '0001_initial'),
        migrations.swappable_dependency(settings.AUTH_USER_MODEL),
        ('forms', '0001_initial'),
    ]

    operations = [
        migrations.CreateModel(
            name='Campaign',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('campaign_id', models.CharField(unique=True, max_length=100)),
                ('create_dt', models.DateTimeField(auto_now_add=True)),
                ('update_dt', models.DateTimeField(auto_now=True)),
                ('status', models.CharField(default='D', max_length=1, choices=[('S', 'Sent'), ('C', 'Scheduled'), ('D', 'Draft')])),
                ('name', models.CharField(max_length=100)),
                ('subject', models.CharField(max_length=500)),
                ('sent_date', models.DateTimeField(null=True, blank=True)),
                ('web_version_url', models.URLField(null=True, blank=True)),
                ('total_recipients', models.IntegerField(default=0)),
                ('scheduled_date', models.DateTimeField(null=True, blank=True)),
                ('scheduled_time_zone', models.CharField(max_length=100, null=True, blank=True)),
                ('preview_url', models.URLField(null=True, blank=True)),
                ('from_name', models.CharField(max_length=100, null=True, blank=True)),
                ('from_email', models.EmailField(max_length=254, null=True, blank=True)),
                ('reply_to', models.EmailField(max_length=254, null=True, blank=True)),
            ],
            options={
                'permissions': (('view_campaign', 'Can view campaign'),),
            },
        ),
        migrations.CreateModel(
            name='GroupQueue',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('group', models.ForeignKey(to='user_groups.Group', on_delete=django.db.models.deletion.CASCADE)),
            ],
        ),
        migrations.CreateModel(
            name='ListMap',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('list_id', models.CharField(max_length=100)),
                ('create_dt', models.DateTimeField(auto_now_add=True)),
                ('update_dt', models.DateTimeField(auto_now=True)),
                ('last_sync_dt', models.DateTimeField(null=True)),
                ('group', models.ForeignKey(to='user_groups.Group', on_delete=django.db.models.deletion.CASCADE)),
            ],
        ),
        migrations.CreateModel(
            name='SubscriberQueue',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('group', models.ForeignKey(to='user_groups.Group', on_delete=django.db.models.deletion.CASCADE)),
                ('subscriber', models.ForeignKey(to='forms.FormEntry', null=True, on_delete=django.db.models.deletion.CASCADE)),
                ('user', models.ForeignKey(on_delete=django.db.models.deletion.SET_NULL, to=settings.AUTH_USER_MODEL, null=True)),
            ],
        ),
        migrations.CreateModel(
            name='Template',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('template_id', models.CharField(max_length=100, unique=True, null=True)),
                ('name', models.CharField(max_length=100)),
                ('create_dt', models.DateTimeField(auto_now_add=True)),
                ('update_dt', models.DateTimeField(auto_now=True)),
                ('cm_preview_url', models.URLField(null=True)),
                ('cm_screenshot_url', models.URLField(null=True)),
                ('html_file', models.FileField(null=True, upload_to=tendenci.apps.files.models.file_directory)),
                ('zip_file', models.FileField(null=True, upload_to=tendenci.apps.files.models.file_directory)),
            ],
            options={
                'permissions': (('view_template', 'Can view template'),),
            },
        ),
        migrations.AddField(
            model_name='campaign',
            name='lists',
            field=models.ManyToManyField(to='campaign_monitor.ListMap'),
        ),
        migrations.AddField(
            model_name='campaign',
            name='template',
            field=models.ForeignKey(blank=True, to='campaign_monitor.Template', null=True, on_delete=django.db.models.deletion.CASCADE),
        ),
    ]
Beispiel #22
0
class Migration(migrations.Migration):

    dependencies = [
        ('accounts', '0022_auto_20150511_1546'),
    ]

    operations = [
        migrations.CreateModel(
            name='CopyPasteWidget',
            fields=[
            ],
            options={
                'proxy': True,
            },
            bases=('accounts.widgetconfiguration',),
        ),
        migrations.CreateModel(
            name='NewsletterWidget',
            fields=[
            ],
            options={
                'proxy': True,
            },
            bases=('accounts.widgetconfiguration',),
        ),
        migrations.CreateModel(
            name='SharingButtonsWidget',
            fields=[
            ],
            options={
                'proxy': True,
            },
            bases=('accounts.widgetconfiguration',),
        ),
        migrations.AddField(
            model_name='widgetconfiguration',
            name='media_url',
            field=models.URLField(max_length=255, blank=True),
            preserve_default=True,
        ),
        migrations.AddField(
            model_name='widgetconfiguration',
            name='page_title',
            field=models.CharField(max_length=255, blank=True),
            preserve_default=True,
        ),
        migrations.AddField(
            model_name='widgetconfiguration',
            name='page_url',
            field=models.URLField(max_length=255, blank=True),
            preserve_default=True,
        ),
        migrations.AddField(
            model_name='widgetconfiguration',
            name='type',
            field=models.CharField(default='sharing-buttons', max_length=20, choices=[(b'sharing-buttons', b'Sharing buttons'), (b'copy-paste', b'Copy-paste'), (b'newsletter', b'Newsletter'), (b'mobile', b'Mobile')]),
            preserve_default=False,
        ),
        migrations.AlterField(
            model_name='widgetconfiguration',
            name='button_size',
            field=models.CharField(blank=True, max_length=20, choices=[(b'small', b'Small'), (b'medium', b'Medium'), (b'big', b'Big'), (b'large', b'Large')]),
            preserve_default=True,
        ),
        migrations.AlterField(
            model_name='widgetconfiguration',
            name='button_style',
            field=models.CharField(blank=True, max_length=20, choices=[(b'icon', b'Icon'), (b'label', b'Label')]),
            preserve_default=True,
        ),
        migrations.AlterField(
            model_name='widgetconfiguration',
            name='counter_position',
            field=models.CharField(blank=True, max_length=20, choices=[(b'top', b'Top'), (b'right', b'Right'), (b'no_counter', b'No counter')]),
            preserve_default=True,
        ),
        migrations.AlterField(
            model_name='widgetconfiguration',
            name='orientation',
            field=models.CharField(blank=True, max_length=20, choices=[(b'vertical', b'Vertical'), (b'horizontal', b'Horizontal')]),
            preserve_default=True,
        ),
        migrations.AlterField(
            model_name='widgetconfiguration',
            name='title',
            field=models.CharField(max_length=255),
            preserve_default=True,
        ),
        migrations.AlterUniqueTogether(
            name='widgetconfiguration',
            unique_together=set([('user', 'title')]),
        ),
    ]
Beispiel #23
0
class Migration(migrations.Migration):

    initial = True

    dependencies = []

    operations = [
        migrations.CreateModel(
            name='Event',
            fields=[
                ('id', models.IntegerField(primary_key=True, serialize=False)),
                ('event', models.CharField(max_length=30)),
                ('label', models.CharField(max_length=30, null=True)),
                ('created_at', models.DateTimeField(blank=True, null=True)),
            ],
        ),
        migrations.CreateModel(
            name='PullRequest',
            fields=[
                ('number',
                 models.IntegerField(primary_key=True, serialize=False)),
                ('title', models.CharField(max_length=200)),
                ('state', models.CharField(max_length=30)),
                ('body', models.TextField(default='')),
                ('created_at', models.DateTimeField(blank=True, null=True)),
                ('updated_at', models.DateTimeField(blank=True, null=True)),
                ('closed_at', models.DateTimeField(blank=True, null=True)),
                ('closed_after_sec', models.IntegerField(blank=True,
                                                         null=True)),
                ('html_url', models.URLField(null=True)),
            ],
        ),
        migrations.CreateModel(
            name='User',
            fields=[
                ('id', models.IntegerField(primary_key=True, serialize=False)),
                ('login', models.CharField(max_length=30)),
                ('avatar_url', models.URLField(null=True)),
                ('url', models.URLField(null=True)),
            ],
        ),
        migrations.AddField(
            model_name='pullrequest',
            name='user',
            field=models.ForeignKey(
                on_delete=django.db.models.deletion.CASCADE,
                to='pr_stats.User'),
        ),
        migrations.AddField(
            model_name='event',
            name='actor',
            field=models.ForeignKey(
                on_delete=django.db.models.deletion.CASCADE,
                to='pr_stats.User'),
        ),
        migrations.AddField(
            model_name='event',
            name='pull_request',
            field=models.ForeignKey(
                on_delete=django.db.models.deletion.CASCADE,
                to='pr_stats.PullRequest'),
        ),
    ]
Beispiel #24
0
class Partner(ArchivedModel):
    """
    Object that this whole app is built around.

    """
    name = models.CharField(max_length=255,
                            verbose_name='Partner Organization',
                            help_text='Name of the Organization')
    data_source = models.CharField(max_length=255,
                                   verbose_name='Source',
                                   blank=True,
                                   help_text='Website, event, or other source where you found the partner')
    uri = models.URLField(verbose_name='URL', blank=True,
                        help_text='Full url. ie http://partnerorganization.org')
    primary_contact = models.ForeignKey('Contact', null=True, blank=True,
                                        related_name='primary_contact',
                                        on_delete=models.SET_NULL,
                                        help_text='Denotes who the primary contact is for this organization.')
    # used if this partner was created by using the partner library
    library = models.ForeignKey('PartnerLibrary', null=True, blank=True,
                                on_delete=models.SET_NULL)
    tags = models.ManyToManyField('Tag', null=True,
        help_text='ie \'Disability\', \'veteran-outreach\', etc. Separate tags with a comma.')
    # owner is the Company that owns this partner.
    owner = models.ForeignKey('seo.Company', null=True, blank=True,
                              on_delete=models.SET_NULL)
    approval_status = models.OneToOneField('mypartners.Status', null=True,
                                           blank=True,verbose_name="Approval Status")
    last_action_time = models.DateTimeField(default=datetime.now, blank=True)

    company_ref = 'owner'

    def __unicode__(self):
        return self.name

    natural_key = __unicode__

    # get_searches_for_partner
    def get_searches(self):
        saved_searches = self.partnersavedsearch_set.all()
        saved_searches = saved_searches.order_by('-created_on')
        return saved_searches

    # get_logs_for_partner
    def get_logs(self, content_type_id=None, num_items=10):
        logs = ContactLogEntry.objects.filter(partner=self)
        if content_type_id:
            logs = logs.filter(content_type_id=content_type_id)
        return logs.order_by('-action_time')[:num_items]

    def get_contact_locations(self):
        """Return a list of unique contact locations as strings."""

        # Unique city and state pairs attached to contacts belonging to this
        # partner.
        locs = Location.objects.filter(
            contacts__in=self.contact_set.all()).exclude(
                contacts__archived_on__isnull=False).values(
                    'city', 'state').distinct().order_by('state', 'city')

        # Convert these city/state pairs into comma separated strings
        return [", ".join(filter(bool, [l['city'], l['state']])) for l in locs]

    # get_contact_records_for_partner
    def get_contact_records(self, contact_name=None, record_type=None,
                            created_by=None, date_start=None, date_end=None,
                            order_by=None, keywords=None, tags=None):

        records = self.contactrecord_set.prefetch_related('tags').all()
        if contact_name:
            records = records.filter(contact__name=contact_name)
        if date_start:
            records = records.filter(date_time__gte=date_start)
        if date_end:
            date_end = date_end + timedelta(1)
            records = records.filter(date_time__lte=date_end)
        if record_type:
            records = records.filter(contact_type=record_type)
        if created_by:
            records = records.filter(created_by=created_by)
        if tags:
            for tag in tags:
                records = records.filter(tags__name__icontains=tag)
        if keywords:
            query = models.Q()
            for keyword in keywords:
                query &= (models.Q(contact_email__icontains=keyword) |
                          models.Q(contact_phone__icontains=keyword) |
                          models.Q(subject__icontains=keyword) |
                          models.Q(notes__icontains=keyword) |
                          models.Q(job_id__icontains=keyword))

            records = records.filter(query)

        if order_by:
            records = records.order_by(order_by)
        else:
            records = records.order_by('-date_time')

        return records

    def get_all_tags(self):
        """Gets unique tags for partner and its contacts"""
        tags = set(self.tags.all())
        tags.update(
            Tag.objects.filter(contact__in=self.contact_set.all()))

        return tags

    def update_last_action_time(self, save=True):
        self.last_action_time = datetime.now()
        if save:
            self.save()
Beispiel #25
0
class Clinical_Trials(models.Model):
    ntc_number = models.CharField(max_length=15)
    url = models.URLField(max_length=100)
    title = models.TextField(max_length=100)
    drug = models.ForeignKey(Drug)
Beispiel #26
0
class PartnerLibrary(models.Model):
    """
    Partners curated from the Office of Federal Contract Compliance
    Programs (OFCCP).

    .. note:: For the differences between `state` and `st`, see the ofccp
              module.

    """

    def __init__(self, *args, **kwargs):
        """
        Regular initialization with a custom has_valid_location property.
        Rather than modify the data on import, we mark the location as invalid.
        """

        super(PartnerLibrary, self).__init__(*args, **kwargs)
        self.has_valid_location = self.st.upper() in states.keys()

    # Where the data was pulled from
    data_source = models.CharField(
        max_length=255,
        default='Employment Referral Resource Directory')

    # Organization Info
    name = models.CharField(max_length=255,
                            verbose_name='Partner Organization')
    uri = models.URLField(blank=True)
    region = models.CharField(max_length=30, blank=True)
    # long state name
    state = models.CharField(max_length=30, blank=True)
    area = models.CharField(max_length=255, blank=True)

    # Contact Info
    contact_name = models.CharField(max_length=255, blank=True)
    phone = models.CharField(max_length=30, blank=True)
    phone_ext = models.CharField(max_length=10, blank=True)
    alt_phone = models.CharField(max_length=30, blank=True)
    fax = models.CharField(max_length=30, blank=True)
    email = models.CharField(max_length=255, blank=True)

    # Location info
    street1 = models.CharField(max_length=255, blank=True)
    street2 = models.CharField(max_length=255, blank=True)
    city = models.CharField(max_length=255, blank=True)
    # short state name
    st = models.CharField(max_length=10, blank=True)
    zip_code = models.CharField(max_length=12, blank=True)

    # Demographic Info
    is_minority = models.BooleanField('minority', default=False)
    is_female = models.BooleanField('female', default=False)
    is_disabled = models.BooleanField('disabled', default=False)
    is_veteran = models.BooleanField('veteran', default=False)
    is_disabled_veteran = models.BooleanField('disabled_veteran',
                                              default=False)

    def __unicode__(self):
        return self.name

    natural_key = __unicode__

    def save(self, *args, **kwargs):
        self.has_valid_location = self.st.upper() in states.keys()

        super(PartnerLibrary, self).save(*args, **kwargs)
Beispiel #27
0
class FormDefinition(models.Model):
    name = models.SlugField(_('name'), max_length=255, unique=True)
    require_hash = models.BooleanField(_('obfuscate URL to this form'), default=False, help_text=_('If enabled, the form can only be reached via a secret URL.'))
    private_hash = models.CharField(editable=False, max_length=40, default='')
    public_hash = models.CharField(editable=False, max_length=40, default='')
    title = models.CharField(_('title'), max_length=255, blank=True, null=True)
    body = models.TextField(_('body'), help_text=_('Form description. Display on form after title.'), blank=True, null=True)
    action = models.URLField(_('target URL'), help_text=_('If you leave this empty, the page where the form resides will be requested, and you can use the mail form and logging features. You can also send data to external sites: For instance, enter "http://www.google.ch/search" to create a search form.'), max_length=255, blank=True, null=True)
    mail_cover_text = models.TextField(_('email cover text'), help_text=_('Email cover text which can be included in the default email template and in the message template.'), blank=True, null=True)
    mail_to = TemplateCharField(_('send form data to e-mail address'), help_text=_('Separate several addresses with a comma. Your form fields are available as template context. Example: "[email protected], {{ from_email }}" if you have a field named `from_email`.'), max_length=255, blank=True, null=True)
    mail_from = TemplateCharField(_('sender address'), max_length=255, help_text=MAIL_TEMPLATE_CONTEXT_HELP_TEXT, blank=True, null=True)
    mail_reply_to = TemplateCharField(_('reply-to address'), max_length=255, help_text=MAIL_TEMPLATE_CONTEXT_HELP_TEXT, blank=True)
    mail_subject = TemplateCharField(_('email subject'), max_length=255, help_text=_('Your form fields are available as template context. Example: "Contact form {{ subject }}" if you have a field named `subject`.'), blank=True, null=True)
    mail_uploaded_files = models.BooleanField(_('Send uploaded files as email attachments'), default=True)
    method = models.CharField(_('method'), max_length=10, default="POST", choices=(('POST', 'POST'), ('GET', 'GET')))
    success_message = models.CharField(_('success message'), max_length=255, blank=True, null=True)
    error_message = models.CharField(_('error message'), max_length=255, blank=True, null=True)
    submit_label = models.CharField(_('submit button label'), max_length=255, blank=True, null=True)
    log_data = models.BooleanField(_('log form data'), help_text=_('Logs all form submissions to the database.'), default=True)
    save_uploaded_files = models.BooleanField(_('save uploaded files'), help_text=_('Saves all uploaded files using server storage.'), default=True)
    success_redirect = models.BooleanField(_('HTTP redirect after successful submission'), default=True)
    success_clear = models.BooleanField(_('clear form after successful submission'), default=True)
    allow_get_initial = models.BooleanField(_('allow initial values via URL'), help_text=_('If enabled, you can fill in form fields by adding them to the query string.'), default=True)
    message_template = TemplateTextField(_('message template'), help_text=_('Your form fields are available as template context. Example: "{{ message }}" if you have a field named `message`. To iterate over all fields, use the variable `data` (a list containing a dictionary for each form field, each containing the elements `name`, `label`, `value`). If you have set up email cover text, you can use {{ mail_cover_text }} to access it.'), blank=True, null=True)
    form_template_name = models.CharField(_('form template'), max_length=255, blank=True, null=True)
    display_logged = models.BooleanField(_('display logged submissions with form'), default=False)

    class Meta:
        verbose_name = _('Form')
        verbose_name_plural = _('Forms')

    def save(self, *args, **kwargs):
        if not self.private_hash:
            self.private_hash = get_random_hash()
        if not self.public_hash:
            self.public_hash = get_random_hash()
        super().save()

    def get_field_dict(self):
        field_dict = OrderedDict()
        for field in self.formdefinitionfield_set.all():
            field_dict[field.name] = field
        return field_dict

    def get_absolute_url(self):
        if self.require_hash:
            return reverse('form_designer.views.detail_by_hash', [str(self.public_hash)])
        return reverse('form_designer.views.detail', [str(self.name)])

    def get_form_data(self, form):
        # TODO: refactor, move to utils or views
        data = []
        field_dict = self.get_field_dict()
        form_keys = form.fields.keys()
        def_keys = field_dict.keys()
        for key in form_keys:
            if key in def_keys and field_dict[key].include_result:
                value = form.cleaned_data[key]
                if getattr(value, '__form_data__', False):
                    value = value.__form_data__()
                data.append(FormValueDict(key, value, form.fields[key].label))
        return data

    def get_form_data_context(self, form_data):
        # TODO: refactor, move to utils
        dict = {}
        for field in form_data or ():
            dict[field['name']] = field['value']
        return dict

    def compile_message(self, form_data, template=None):
        # TODO: refactor, move to utils
        if template:
            t = get_template(template)
        elif not self.message_template:
            t = get_template(settings.EMAIL_TEMPLATE)
        else:
            t = get_django_template_from_string(self.message_template)
        context = self.get_form_data_context(form_data)
        context['data'] = form_data
        context['mail_cover_text'] = self.mail_cover_text or ''
        return t.render(context)

    def count_fields(self):
        return self.formdefinitionfield_set.count()

    count_fields.short_description = _('Fields')

    def __str__(self):
        return self.title or self.name

    def log(self, form, user=None):
        form_data = self.get_form_data(form)
        created_by = None

        if user and user.is_authenticated:
            created_by = user

        flog = FormLog(form_definition=self, data=form_data, created_by=created_by)
        flog.save()
        return flog

    @warn_about_renamed_method(
        'FormDefinition', 'string_template_replace', 'form_designer.utils.string_template_replace',
        DeprecationWarning
    )
    def string_template_replace(self, text, context_dict):
        return string_template_replace(text, context_dict)

    def send_mail(self, form, files=None):
        if not self.mail_to:
            return
        from form_designer.email import build_form_mail
        message = build_form_mail(form_definition=self, form=form, files=files)
        message.send(fail_silently=False)
        return message

    @property
    def is_template_html(self):
        template = self.message_template
        if template:  # We have a custom inline template string?
            # Assume the template string is HTML-ish if it has at least one opening
            # and closing HTML tag:
            return (re.search("<[^>]+>", template) and re.search("</[^>]+>", template))

        # If there is no custom inline template, see if the `EMAIL_TEMPLATE`
        # setting points to a `.html` file:
        return settings.EMAIL_TEMPLATE.lower().endswith('.html')

    @property
    def submit_flag_name(self):
        name = settings.SUBMIT_FLAG_NAME % self.name
        # make sure we are not overriding one of the actual form fields
        while self.formdefinitionfield_set.filter(name__exact=name).count() > 0:
            name += '_'
        return name
Beispiel #28
0
class Experiment(models.Model):
    """The ``Experiment`` model inherits from :class:`django.db.models.Model`

    :attribute url: **Undocumented**
    :attribute approved: **Undocumented**
    :attribute title: the title of the experiment.
    :attribute institution_name: the name of the institution who created
       the dataset.
    :attribute start_time: **Undocumented**
    :attribute end_time: **Undocumented**
    :attribute created_time: **Undocumented**
    :attribute handle: **Undocumented**
    :attribute public: **Undocumented**
    :attribute objects: default model manager
    :attribute safe: ACL aware model manager

    """
    url = models.URLField(verify_exists=False, max_length=255,
                          null=True, blank=True)
    approved = models.BooleanField()
    title = models.CharField(max_length=400)
    institution_name = models.CharField(max_length=400,
            default=settings.DEFAULT_INSTITUTION)
    description = models.TextField(blank=True)
    start_time = models.DateTimeField(null=True, blank=True)
    end_time = models.DateTimeField(null=True, blank=True)
    created_time = models.DateTimeField(auto_now_add=True)
    update_time = models.DateTimeField(auto_now=True)
    created_by = models.ForeignKey(User)
    handle = models.TextField(null=True, blank=True)
    public = models.BooleanField()
    objects = OracleSafeManager()
    safe = ExperimentManager()  # The acl-aware specific manager.

    def save(self, *args, **kwargs):
        super(Experiment, self).save(*args, **kwargs)
        _publish_public_expt_rifcs(self)

    def getParameterSets(self, schemaType=None):
        """Return the experiment parametersets associated with this
        experiment.

        """
        if schemaType == Schema.EXPERIMENT or schemaType is None:
            return self.experimentparameterset_set.filter(
                schema__type=Schema.EXPERIMENT)
        else:
            raise Schema.UnsupportedType

    def __unicode__(self):
        return self.title

    def get_absolute_filepath(self):
        """Return the absolute storage path
        to the current ``Experiment``"""
        store = settings.FILE_STORE_PATH
        return path.join(store, str(self.id))

    def get_or_create_directory(self):
        dirname = path.join(settings.FILE_STORE_PATH,
                            str(self.id))
        if not path.exists(dirname):
            from os import chmod, mkdir
            try:
                mkdir(dirname)
                chmod(dirname, 0770)
            except:
                dirname = None
        return dirname

    @models.permalink
    def get_absolute_url(self):
        """Return the absolute url to the current ``Experiment``"""
        return ('tardis.tardis_portal.views.view_experiment', (),
                {'experiment_id': self.id})

    @models.permalink
    def get_edit_url(self):
        """Return the absolute url to the edit view of the current
        ``Experiment``

        """
        return ('tardis.tardis_portal.views.edit_experiment', (),
                {'experiment_id': self.id})

    @models.permalink
    def get_create_token_url(self):
        """Return the absolute url to the create token view of the current
        ``Experiment``
        """
        return ('tardis.tardis_portal.views.create_token', (),
                {'experiment_id': self.id})

    def get_download_urls(self, comptype="zip"):
        urls = {}
        kwargs = {'experiment_id': self.id,
                  'comptype': comptype}
        distinct = Dataset_File.objects.filter(dataset__experiment=self.id)\
            .values('protocol').distinct()
        for key_value in distinct:
            protocol = key_value['protocol']
            if protocol in ['', 'tardis', 'file', 'http', 'https']:
                view = 'tardis.tardis_portal.download.download_experiment'
                if not '' in urls:
                    urls[''] = reverse(view, kwargs=kwargs)
            else:
                try:
                    for module in settings.DOWNLOAD_PROVIDERS:
                        if module[0] == protocol:
                            view = '%s.download_experiment' % module[1]
                            urls[protocol] = reverse(view, kwargs=kwargs)
                except AttributeError:
                    pass

        return urls
class Migration(migrations.Migration):

    dependencies = [
        ('catalogue', '0018_auto_20191220_0920'),
        ('wagtailcore', '0052_pagelogentry'),
        ('multisite', '0003_auto_20200827_1719'),
    ]

    operations = [
        migrations.CreateModel(
            name='FooterLinks',
            fields=[
                ('id',
                 models.AutoField(auto_created=True,
                                  primary_key=True,
                                  serialize=False,
                                  verbose_name='ID')),
                ('site',
                 models.OneToOneField(
                     editable=False,
                     on_delete=django.db.models.deletion.CASCADE,
                     to='wagtailcore.Site')),
            ],
            options={
                'abstract': False,
            },
        ),
        migrations.CreateModel(
            name='FooterLinksRelatedLink',
            fields=[
                ('id',
                 models.AutoField(auto_created=True,
                                  primary_key=True,
                                  serialize=False,
                                  verbose_name='ID')),
                ('sort_order',
                 models.IntegerField(blank=True, editable=False, null=True)),
                ('link_external',
                 models.URLField(blank=True, verbose_name='External link')),
                ('title',
                 models.CharField(help_text='Link title', max_length=255)),
                ('link_category',
                 models.ForeignKey(blank=True,
                                   null=True,
                                   on_delete=django.db.models.deletion.CASCADE,
                                   related_name='+',
                                   to='catalogue.Category')),
                ('link_page',
                 models.ForeignKey(blank=True,
                                   null=True,
                                   on_delete='models.CASCADE',
                                   related_name='+',
                                   to='wagtailcore.Page')),
                ('page',
                 modelcluster.fields.ParentalKey(
                     on_delete=django.db.models.deletion.CASCADE,
                     related_name='footer_links',
                     to='multisite.FooterLinks')),
            ],
            options={
                'ordering': ['sort_order'],
                'abstract': False,
            },
        ),
    ]
Beispiel #30
0
class Profile(models.Model):
    GUEST_USER = 0
    ORDINARY_USER = 1
    SUPER_USER = 2
    COHORTS = (
        (GUEST_USER, 'Guest User'),
        (ORDINARY_USER, 'Ordinary User'),
        (SUPER_USER, 'Super User'),
    )

    user = models.OneToOneField(User, on_delete=models.CASCADE)
    cohort = models.PositiveSmallIntegerField(choices=COHORTS,
                                              default=GUEST_USER)
    picture = models.URLField(blank=True)
    interests = models.CharField(max_length=100, blank=True)
    dark_theme_enabled = models.BooleanField(default=False)
    is_locked = models.BooleanField(default=False)
    doc_to_fix = models.IntegerField(blank=True, null=True)

    def __str__(self):
        return str(self.user) + ' ' + self.get_cohort(
        ) + ' ' + self.picture + ' ' + self.interests

    def make_gu(self):
        self.cohort = self.GUEST_USER

    def make_ou(self):
        self.cohort = self.ORDINARY_USER

    def make_su(self):
        self.cohort = self.SUPER_USER

    def set_cohort(self, value):
        self.cohort = value

    def get_cohort(self):
        return self.COHORTS[self.cohort][1]

    def get_cohort_value(self):
        return self.cohort

    def is_gu(self):
        return self.cohort == self.GUEST_USER

    def is_ou(self):
        return self.cohort == self.ORDINARY_USER

    def is_su(self):
        return self.cohort == self.SUPER_USER

    def has_gu_rights(self):
        return self.cohort >= self.GUEST_USER

    def has_ou_rights(self):
        return self.cohort >= self.ORDINARY_USER

    def has_su_rights(self):
        return self.cohort >= self.SUPER_USER

    def locked(self):
        return self.is_locked

    def get_userid(self):
        return self.user.id