Python django.db.models.SET_NULL Examples

The following are 28 code examples for showing how to use django.db.models.SET_NULL(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module django.db.models , or try the search function .

Example 1
Project: django-more   Author: ashleywaite   File: patches.py    License: BSD 3-Clause "New" or "Revised" License 7 votes vote down vote up
def ask_remove_enum_values(self, db_type, values):
        """ How to treat records with deleted enum values. """
        # Ordered ensures
        choices = [
            (models.CASCADE, "Cascade - Delete records with removed values"),
            (models.PROTECT, "Protect - Block migrations if records contain removed values"),
            (models.SET_NULL, "Set NULL - Set value to NULL"),
            (models.SET_DEFAULT, "Set default - Set value to field default"),
            (models.SET, "Set value - Provide a one off default now"),
            (models.DO_NOTHING, "Do nothing - Consistency must be handled elsewhere"),
            (None, "Leave it to field definitions")]
        choice, _ = choices[self._choice_input(
            "Enum {db_type} has had {values} removed, "
            "existing records may need to be updated. "
            "Override update behaviour or do nothing and follow field behaviour.".format(
                db_type=db_type,
                values=values),
            [q for (k, q) in choices]) - 1]
        if choice == models.SET:
            return models.SET(self._ask_default())
        return choice 
Example 2
Project: djongo   Author: nesdis   File: test_relative_fields.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def test_on_delete_set_null_on_non_nullable_field(self):
        class Person(models.Model):
            pass

        class Model(models.Model):
            foreign_key = models.ForeignKey('Person', models.SET_NULL)

        field = Model._meta.get_field('foreign_key')
        self.assertEqual(field.check(), [
            Error(
                'Field specifies on_delete=SET_NULL, but cannot be null.',
                hint='Set null=True argument on the field, or change the on_delete rule.',
                obj=field,
                id='fields.E320',
            ),
        ]) 
Example 3
Project: djongo   Author: nesdis   File: test_relative_fields.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def test_to_fields_not_checked_if_related_model_doesnt_exist(self):
        class Child(models.Model):
            a = models.PositiveIntegerField()
            b = models.PositiveIntegerField()
            parent = ForeignObject(
                'invalid_models_tests.Parent',
                on_delete=models.SET_NULL,
                from_fields=('a', 'b'),
                to_fields=('a', 'b'),
            )

        field = Child._meta.get_field('parent')
        self.assertEqual(field.check(), [
            Error(
                "Field defines a relation with model 'invalid_models_tests.Parent', "
                "which is either not installed, or is abstract.",
                id='fields.E300',
                obj=field,
            ),
        ]) 
Example 4
Project: djongo   Author: nesdis   File: tests.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def test_check_composite_foreign_object(self):
        class Parent(models.Model):
            a = models.PositiveIntegerField()
            b = models.PositiveIntegerField()

            class Meta:
                unique_together = (('a', 'b'),)

        class Child(models.Model):
            a = models.PositiveIntegerField()
            b = models.PositiveIntegerField()
            value = models.CharField(max_length=255)
            parent = ForeignObject(
                Parent,
                on_delete=models.SET_NULL,
                from_fields=('a', 'b'),
                to_fields=('a', 'b'),
                related_name='children',
            )

        self.assertEqual(Child._meta.get_field('parent').check(from_model=Child), []) 
Example 5
Project: djongo   Author: nesdis   File: tests.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def test_check_subset_composite_foreign_object(self):
        class Parent(models.Model):
            a = models.PositiveIntegerField()
            b = models.PositiveIntegerField()
            c = models.PositiveIntegerField()

            class Meta:
                unique_together = (('a', 'b'),)

        class Child(models.Model):
            a = models.PositiveIntegerField()
            b = models.PositiveIntegerField()
            c = models.PositiveIntegerField()
            d = models.CharField(max_length=255)
            parent = ForeignObject(
                Parent,
                on_delete=models.SET_NULL,
                from_fields=('a', 'b', 'c'),
                to_fields=('a', 'b', 'c'),
                related_name='children',
            )

        self.assertEqual(Child._meta.get_field('parent').check(from_model=Child), []) 
Example 6
Project: djongo   Author: nesdis   File: test_relative_fields.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def test_on_delete_set_null_on_non_nullable_field(self):
        class Person(models.Model):
            pass

        class Model(models.Model):
            foreign_key = models.ForeignKey('Person', models.SET_NULL)

        field = Model._meta.get_field('foreign_key')
        self.assertEqual(field.check(), [
            Error(
                'Field specifies on_delete=SET_NULL, but cannot be null.',
                hint='Set null=True argument on the field, or change the on_delete rule.',
                obj=field,
                id='fields.E320',
            ),
        ]) 
Example 7
Project: djongo   Author: nesdis   File: test_relative_fields.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def test_to_fields_not_checked_if_related_model_doesnt_exist(self):
        class Child(models.Model):
            a = models.PositiveIntegerField()
            b = models.PositiveIntegerField()
            parent = ForeignObject(
                'invalid_models_tests.Parent',
                on_delete=models.SET_NULL,
                from_fields=('a', 'b'),
                to_fields=('a', 'b'),
            )

        field = Child._meta.get_field('parent')
        self.assertEqual(field.check(), [
            Error(
                "Field defines a relation with model 'invalid_models_tests.Parent', "
                "which is either not installed, or is abstract.",
                id='fields.E300',
                obj=field,
            ),
        ]) 
Example 8
Project: djongo   Author: nesdis   File: tests.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def test_check_composite_foreign_object(self):
        class Parent(models.Model):
            a = models.PositiveIntegerField()
            b = models.PositiveIntegerField()

            class Meta:
                unique_together = (('a', 'b'),)

        class Child(models.Model):
            a = models.PositiveIntegerField()
            b = models.PositiveIntegerField()
            value = models.CharField(max_length=255)
            parent = ForeignObject(
                Parent,
                on_delete=models.SET_NULL,
                from_fields=('a', 'b'),
                to_fields=('a', 'b'),
                related_name='children',
            )

        self.assertEqual(Child._meta.get_field('parent').check(from_model=Child), []) 
Example 9
Project: djongo   Author: nesdis   File: tests.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def test_check_subset_composite_foreign_object(self):
        class Parent(models.Model):
            a = models.PositiveIntegerField()
            b = models.PositiveIntegerField()
            c = models.PositiveIntegerField()

            class Meta:
                unique_together = (('a', 'b'),)

        class Child(models.Model):
            a = models.PositiveIntegerField()
            b = models.PositiveIntegerField()
            c = models.PositiveIntegerField()
            d = models.CharField(max_length=255)
            parent = ForeignObject(
                Parent,
                on_delete=models.SET_NULL,
                from_fields=('a', 'b', 'c'),
                to_fields=('a', 'b', 'c'),
                related_name='children',
            )

        self.assertEqual(Child._meta.get_field('parent').check(from_model=Child), []) 
Example 10
def forwards(self, orm):

        # Changing field 'Location.photo'
        db.alter_column(u'djangocms_gmaps_location', 'photo_id', self.gf('django.db.models.fields.related.ForeignKey')(null=True, on_delete=models.SET_NULL, to=orm['filer.Image']))

        # Changing field 'Location.marker_icon'
        db.alter_column(u'djangocms_gmaps_location', 'marker_icon_id', self.gf('django.db.models.fields.related.ForeignKey')(null=True, on_delete=models.SET_NULL, to=orm['filer.Image'])) 
Example 11
def backwards(self, orm):
        # Adding model 'MaterialShapeNicenessLabel'
        db.create_table(u'shapes_materialshapenicenesslabel', (
            ('quality_method', self.gf('django.db.models.fields.CharField')(max_length=1, null=True, blank=True)),
            ('admin_score', self.gf('django.db.models.fields.IntegerField')(default=0)),
            ('time_active_ms', self.gf('django.db.models.fields.IntegerField')(blank=True, null=True, db_index=True)),
            ('canttell', self.gf('django.db.models.fields.NullBooleanField')(null=True, blank=True)),
            ('shape', self.gf('django.db.models.fields.related.ForeignKey')(related_name='nicenesses', to=orm['shapes.MaterialShape'])),
            ('added', self.gf('django.db.models.fields.DateTimeField')(default=datetime.datetime.now)),
            ('user', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['accounts.UserProfile'])),
            (u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
            ('mturk_assignment', self.gf('django.db.models.fields.related.ForeignKey')(related_name='+', null=True, to=orm['mturk.MtAssignment'], on_delete=models.SET_NULL, blank=True)),
            ('invalid', self.gf('django.db.models.fields.BooleanField')(default=False)),
            ('sandbox', self.gf('django.db.models.fields.BooleanField')(default=False)),
            ('time_ms', self.gf('django.db.models.fields.IntegerField')(blank=True, null=True, db_index=True)),
            ('reward', self.gf('django.db.models.fields.DecimalField')(null=True, max_digits=8, decimal_places=4, blank=True)),
            ('nice', self.gf('django.db.models.fields.BooleanField')(default=False)),
        ))
        db.send_create_signal(u'shapes', ['MaterialShapeNicenessLabel'])

        # Adding field 'MaterialShape.nice'
        db.add_column(u'shapes_materialshape', 'nice',
                      self.gf('django.db.models.fields.NullBooleanField')(null=True, blank=True),
                      keep_default=False)

        # Adding field 'MaterialShape.nice_score'
        db.add_column(u'shapes_materialshape', 'nice_score',
                      self.gf('django.db.models.fields.FloatField')(null=True, blank=True),
                      keep_default=False) 
Example 12
Project: lego   Author: webkom   File: models.py    License: MIT License 5 votes vote down vote up
def __init__(self, **kwargs):
        kwargs["to"] = "files.File"
        kwargs["on_delete"] = models.SET_NULL
        kwargs["null"] = True
        super().__init__(**kwargs) 
Example 13
Project: wagtailstreamforms   Author: labd   File: test_form.py    License: MIT License 5 votes vote down vote up
def test_post_redirect_page(self):
        field = self.get_field(Form, "post_redirect_page")
        self.assertModelPKField(field, Page, models.SET_NULL, True, True) 
Example 14
Project: adhocracy4   Author: liqd   File: fields.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        defaults = {
            'verbose_name': _('Category'),
            'to': Category,
            'on_delete': models.SET_NULL,
            'null': True,
            'blank': True,
            'related_name': '+',
        }
        defaults.update(kwargs)
        super().__init__(**defaults) 
Example 15
Project: django-sqlserver   Author: denisenkom   File: test_writer.py    License: MIT License 5 votes vote down vote up
def test_serialize_functions(self):
        with self.assertRaisesMessage(ValueError, 'Cannot serialize function: lambda'):
            self.assertSerializedEqual(lambda x: 42)
        self.assertSerializedEqual(models.SET_NULL)
        string, imports = MigrationWriter.serialize(models.SET(42))
        self.assertEqual(string, 'models.SET(42)')
        self.serialize_round_trip(models.SET(42)) 
Example 16
Project: djongo   Author: nesdis   File: test_relative_fields.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def test_to_fields_exist(self):
        class Parent(models.Model):
            pass

        class Child(models.Model):
            a = models.PositiveIntegerField()
            b = models.PositiveIntegerField()
            parent = ForeignObject(
                Parent,
                on_delete=models.SET_NULL,
                from_fields=('a', 'b'),
                to_fields=('a', 'b'),
            )

        field = Child._meta.get_field('parent')
        self.assertEqual(field.check(), [
            Error(
                "The to_field 'a' doesn't exist on the related model 'invalid_models_tests.Parent'.",
                obj=field,
                id='fields.E312',
            ),
            Error(
                "The to_field 'b' doesn't exist on the related model 'invalid_models_tests.Parent'.",
                obj=field,
                id='fields.E312',
            ),
        ]) 
Example 17
Project: djongo   Author: nesdis   File: test_relative_fields.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def test_superset_foreign_object(self):
        class Parent(models.Model):
            a = models.PositiveIntegerField()
            b = models.PositiveIntegerField()
            c = models.PositiveIntegerField()

            class Meta:
                unique_together = (('a', 'b', 'c'),)

        class Child(models.Model):
            a = models.PositiveIntegerField()
            b = models.PositiveIntegerField()
            value = models.CharField(max_length=255)
            parent = ForeignObject(
                Parent,
                on_delete=models.SET_NULL,
                from_fields=('a', 'b'),
                to_fields=('a', 'b'),
                related_name='children',
            )

        field = Child._meta.get_field('parent')
        self.assertEqual(field.check(from_model=Child), [
            Error(
                "No subset of the fields 'a', 'b' on model 'Parent' is unique.",
                hint=(
                    "Add unique=True on any of those fields or add at least "
                    "a subset of them to a unique_together constraint."
                ),
                obj=field,
                id='fields.E310',
            ),
        ]) 
Example 18
Project: djongo   Author: nesdis   File: test_relative_fields.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def test_intersection_foreign_object(self):
        class Parent(models.Model):
            a = models.PositiveIntegerField()
            b = models.PositiveIntegerField()
            c = models.PositiveIntegerField()
            d = models.PositiveIntegerField()

            class Meta:
                unique_together = (('a', 'b', 'c'),)

        class Child(models.Model):
            a = models.PositiveIntegerField()
            b = models.PositiveIntegerField()
            d = models.PositiveIntegerField()
            value = models.CharField(max_length=255)
            parent = ForeignObject(
                Parent,
                on_delete=models.SET_NULL,
                from_fields=('a', 'b', 'd'),
                to_fields=('a', 'b', 'd'),
                related_name='children',
            )

        field = Child._meta.get_field('parent')
        self.assertEqual(field.check(from_model=Child), [
            Error(
                "No subset of the fields 'a', 'b', 'd' on model 'Parent' is unique.",
                hint=(
                    "Add unique=True on any of those fields or add at least "
                    "a subset of them to a unique_together constraint."
                ),
                obj=field,
                id='fields.E310',
            ),
        ]) 
Example 19
Project: djongo   Author: nesdis   File: test_relative_fields.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def test_to_fields_exist(self):
        class Parent(models.Model):
            pass

        class Child(models.Model):
            a = models.PositiveIntegerField()
            b = models.PositiveIntegerField()
            parent = ForeignObject(
                Parent,
                on_delete=models.SET_NULL,
                from_fields=('a', 'b'),
                to_fields=('a', 'b'),
            )

        field = Child._meta.get_field('parent')
        self.assertEqual(field.check(), [
            Error(
                "The to_field 'a' doesn't exist on the related model 'invalid_models_tests.Parent'.",
                obj=field,
                id='fields.E312',
            ),
            Error(
                "The to_field 'b' doesn't exist on the related model 'invalid_models_tests.Parent'.",
                obj=field,
                id='fields.E312',
            ),
        ]) 
Example 20
Project: djongo   Author: nesdis   File: test_relative_fields.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def test_intersection_foreign_object(self):
        class Parent(models.Model):
            a = models.PositiveIntegerField()
            b = models.PositiveIntegerField()
            c = models.PositiveIntegerField()
            d = models.PositiveIntegerField()

            class Meta:
                unique_together = (('a', 'b', 'c'),)

        class Child(models.Model):
            a = models.PositiveIntegerField()
            b = models.PositiveIntegerField()
            d = models.PositiveIntegerField()
            value = models.CharField(max_length=255)
            parent = ForeignObject(
                Parent,
                on_delete=models.SET_NULL,
                from_fields=('a', 'b', 'd'),
                to_fields=('a', 'b', 'd'),
                related_name='children',
            )

        field = Child._meta.get_field('parent')
        self.assertEqual(field.check(from_model=Child), [
            Error(
                "No subset of the fields 'a', 'b', 'd' on model 'Parent' is unique.",
                hint=(
                    "Add unique=True on any of those fields or add at least "
                    "a subset of them to a unique_together constraint."
                ),
                obj=field,
                id='fields.E310',
            ),
        ]) 
Example 21
Project: djongo   Author: nesdis   File: test_writer.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def test_serialize_functions(self):
        with self.assertRaisesMessage(ValueError, 'Cannot serialize function: lambda'):
            self.assertSerializedEqual(lambda x: 42)
        self.assertSerializedEqual(models.SET_NULL)
        string, imports = MigrationWriter.serialize(models.SET(42))
        self.assertEqual(string, 'models.SET(42)')
        self.serialize_round_trip(models.SET(42)) 
Example 22
Project: jorvik   Author: CroceRossaItaliana   File: models.py    License: GNU General Public License v3.0 5 votes vote down vote up
def media_consumi(self):
        rifornimenti = Rifornimento.objects.filter(veicolo=self)
        litri = 0
        for rifornimento in rifornimenti:
            litri += rifornimento.consumo_carburante
        try:
            ultimo_rifornimento = Rifornimento.objects.filter(veicolo=self).latest("data")
            primo_rifornimento = Rifornimento.objects.filter(veicolo=self).earliest("data")
        except Rifornimento.DoesNotExist:
            return 0
        km = ultimo_rifornimento.contachilometri - primo_rifornimento.contachilometri
        litri -= ultimo_rifornimento.consumo_carburante
        if litri != 0:
            return round(km/litri, 2)
        else:
            return 0

# class Immatricolazione(ModelloSemplice, ConMarcaTemporale):
#     """
#     Rappresenta una pratica di immatricolazione di un Veicolo
#
#     Una pratica viene istruita da un ufficio motorizzazione per conto di una unita' CRI richiedente.
#     La stessa viene sottoposta a due stadi di approvazione, in seguito alla istruzione. Quando la
#     pratica termina, il veicolo viene immatricolato ed entra in servizio.
#     """
#
#     class Meta:
#         verbose_name = "Pratica di Immatricolazione"
#         verbose_name_plural = "Pratiche di Immatricolazione"
#
#     richiedente = models.ForeignKey(Sede, related_name='immatricolazioni_richieste', null=True, on_delete=models.SET_NULL)
#     ufficio = models.ForeignKey(Sede, related_name='immatricolazioni_istruite', on_delete=models.PROTECT)
#     veicolo = models.ForeignKey(Veicolo, related_name='richieste_immatricolazione', on_delete=models.CASCADE) 
Example 23
Project: djangocms-forms   Author: mishbahr   File: fields.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        kwargs.update({'null': True})  # always allow Null
        kwargs.update({'editable': False})  # never allow edits in admin
        kwargs.update({'on_delete': SET_NULL})  # never delete plugin
        super(PluginReferenceField, self).__init__(*args, **kwargs) 
Example 24
Project: opensurfaces   Author: seanbell   File: 0001_initial.py    License: MIT License 4 votes vote down vote up
def forwards(self, orm):
        # Adding model 'ShapeRectifiedNormalLabel'
        db.create_table(u'normals_shaperectifiednormallabel', (
            (u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
            ('added', self.gf('django.db.models.fields.DateTimeField')(default=datetime.datetime.now)),
            ('user', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['accounts.UserProfile'])),
            ('mturk_assignment', self.gf('django.db.models.fields.related.ForeignKey')(blank=True, related_name='+', null=True, on_delete=models.SET_NULL, to=orm['mturk.MtAssignment'])),
            ('sandbox', self.gf('django.db.models.fields.BooleanField')(default=False)),
            ('invalid', self.gf('django.db.models.fields.BooleanField')(default=False)),
            ('quality_method', self.gf('django.db.models.fields.CharField')(max_length=1, null=True, blank=True)),
            ('time_ms', self.gf('django.db.models.fields.IntegerField')(db_index=True, null=True, blank=True)),
            ('time_active_ms', self.gf('django.db.models.fields.IntegerField')(db_index=True, null=True, blank=True)),
            ('reward', self.gf('django.db.models.fields.DecimalField')(null=True, max_digits=8, decimal_places=4, blank=True)),
            ('admin_score', self.gf('django.db.models.fields.IntegerField')(default=0)),
            ('shape', self.gf('django.db.models.fields.related.ForeignKey')(related_name='rectified_normals', to=orm['shapes.MaterialShape'])),
            ('automatic', self.gf('django.db.models.fields.BooleanField')(default=False)),
            ('method', self.gf('django.db.models.fields.CharField')(max_length=1, blank=True)),
            ('uvnb', self.gf('django.db.models.fields.TextField')()),
            ('num_vanishing_lines', self.gf('django.db.models.fields.IntegerField')(null=True, blank=True)),
            ('pos_x', self.gf('django.db.models.fields.FloatField')(null=True, blank=True)),
            ('pos_y', self.gf('django.db.models.fields.FloatField')(null=True, blank=True)),
            ('focal_pixels', self.gf('django.db.models.fields.FloatField')(null=True, blank=True)),
            ('canvas_width', self.gf('django.db.models.fields.IntegerField')(null=True, blank=True)),
            ('canvas_height', self.gf('django.db.models.fields.IntegerField')(null=True, blank=True)),
            ('correct', self.gf('django.db.models.fields.NullBooleanField')(null=True, blank=True)),
            ('correct_score', self.gf('django.db.models.fields.FloatField')(db_index=True, null=True, blank=True)),
            ('image_rectified', self.gf('django.db.models.fields.files.ImageField')(max_length=255, null=True, blank=True)),
        ))
        db.send_create_signal(u'normals', ['ShapeRectifiedNormalLabel'])

        # Adding model 'ShapeRectifiedNormalQuality'
        db.create_table(u'normals_shaperectifiednormalquality', (
            (u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
            ('added', self.gf('django.db.models.fields.DateTimeField')(default=datetime.datetime.now)),
            ('user', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['accounts.UserProfile'])),
            ('mturk_assignment', self.gf('django.db.models.fields.related.ForeignKey')(blank=True, related_name='+', null=True, on_delete=models.SET_NULL, to=orm['mturk.MtAssignment'])),
            ('sandbox', self.gf('django.db.models.fields.BooleanField')(default=False)),
            ('invalid', self.gf('django.db.models.fields.BooleanField')(default=False)),
            ('quality_method', self.gf('django.db.models.fields.CharField')(max_length=1, null=True, blank=True)),
            ('time_ms', self.gf('django.db.models.fields.IntegerField')(db_index=True, null=True, blank=True)),
            ('time_active_ms', self.gf('django.db.models.fields.IntegerField')(db_index=True, null=True, blank=True)),
            ('reward', self.gf('django.db.models.fields.DecimalField')(null=True, max_digits=8, decimal_places=4, blank=True)),
            ('rectified_normal', self.gf('django.db.models.fields.related.ForeignKey')(related_name='qualities', to=orm['normals.ShapeRectifiedNormalLabel'])),
            ('correct', self.gf('django.db.models.fields.BooleanField')(default=False)),
            ('canttell', self.gf('django.db.models.fields.NullBooleanField')(null=True, blank=True)),
        ))
        db.send_create_signal(u'normals', ['ShapeRectifiedNormalQuality']) 
Example 25
Project: wagtail   Author: wagtail   File: models.py    License: BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def check(cls, **kwargs):
        errors = super(Page, cls).check(**kwargs)

        # Check that foreign keys from pages are not configured to cascade
        # This is the default Django behaviour which must be explicitly overridden
        # to prevent pages disappearing unexpectedly and the tree being corrupted

        # get names of foreign keys pointing to parent classes (such as page_ptr)
        field_exceptions = [field.name
                            for model in [cls] + list(cls._meta.get_parent_list())
                            for field in model._meta.parents.values() if field]

        for field in cls._meta.fields:
            if isinstance(field, models.ForeignKey) and field.name not in field_exceptions:
                if field.remote_field.on_delete == models.CASCADE:
                    errors.append(
                        checks.Warning(
                            "Field hasn't specified on_delete action",
                            hint="Set on_delete=models.SET_NULL and make sure the field is nullable or set on_delete=models.PROTECT. Wagtail does not allow simple database CASCADE because it will corrupt its tree storage.",
                            obj=field,
                            id='wagtailcore.W001',
                        )
                    )

        if not isinstance(cls.objects, PageManager):
            errors.append(
                checks.Error(
                    "Manager does not inherit from PageManager",
                    hint="Ensure that custom Page managers inherit from wagtail.core.models.PageManager",
                    obj=cls,
                    id='wagtailcore.E002',
                )
            )

        try:
            cls.clean_subpage_models()
        except (ValueError, LookupError) as e:
            errors.append(
                checks.Error(
                    "Invalid subpage_types setting for %s" % cls,
                    hint=str(e),
                    id='wagtailcore.E002'
                )
            )

        try:
            cls.clean_parent_page_models()
        except (ValueError, LookupError) as e:
            errors.append(
                checks.Error(
                    "Invalid parent_page_types setting for %s" % cls,
                    hint=str(e),
                    id='wagtailcore.E002'
                )
            )

        return errors 
Example 26
Project: devops   Author: madre   File: models.py    License: MIT License 4 votes vote down vote up
def send(self, **kwargs):
        current_site = kwargs["site"] if "site" in kwargs else Site.objects.get_current()
        protocol = getattr(settings, "DEFAULT_HTTP_PROTOCOL", "http")
        activate_url = "{0}://{1}{2}".format(
            protocol,
            current_site.domain,
            reverse(settings.ACCOUNT_EMAIL_CONFIRMATION_URL, args=[self.key])
        )
        ctx = {
            "account": self.account,
            "user": self.account.user,
            "activate_url": activate_url,
            "current_site": current_site,
            "key": self.key,
        }
        hookset.send_confirmation_email([self.account.user.email], ctx)
        self.sent = timezone.now()
        self.save()
        signals.email_confirmation_sent.send(sender=self.__class__, confirmation=self)

# class AccountDeletion(models.Model):
#
#     user = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, blank=True, on_delete=models.SET_NULL)
#     email = models.EmailField()
#     date_requested = models.DateTimeField(_("date requested"), default=timezone.now)
#     date_expunged = models.DateTimeField(_("date expunged"), null=True, blank=True)
#
#     class Meta:
#         verbose_name = _("account deletion")
#         verbose_name_plural = _("account deletions")
#
#     @classmethod
#     def expunge(cls, hours_ago=None):
#         if hours_ago is None:
#             hours_ago = settings.ACCOUNT_DELETION_EXPUNGE_HOURS
#         before = timezone.now() - datetime.timedelta(hours=hours_ago)
#         count = 0
#         for account_deletion in cls.objects.filter(date_requested__lt=before, user__isnull=False):
#             settings.ACCOUNT_DELETION_EXPUNGE_CALLBACK(account_deletion)
#             account_deletion.date_expunged = timezone.now()
#             account_deletion.save()
#             count += 1
#         return count
#
#     @classmethod
#     def mark(cls, user):
#         account_deletion, created = cls.objects.get_or_create(user=user)
#         account_deletion.email = user.email
#         account_deletion.save()
#         settings.ACCOUNT_DELETION_MARK_CALLBACK(account_deletion)
#         return account_deletion 
Example 27
Project: django-sqlserver   Author: denisenkom   File: tests.py    License: MIT License 4 votes vote down vote up
def test_foreign_key(self):
        # Test basic pointing
        from django.contrib.auth.models import Permission
        field = models.ForeignKey("auth.Permission", models.CASCADE)
        field.remote_field.model = Permission
        field.remote_field.field_name = "id"
        name, path, args, kwargs = field.deconstruct()
        self.assertEqual(path, "django.db.models.ForeignKey")
        self.assertEqual(args, [])
        self.assertEqual(kwargs, {"to": "auth.Permission", "on_delete": models.CASCADE})
        self.assertFalse(hasattr(kwargs['to'], "setting_name"))
        # Test swap detection for swappable model
        field = models.ForeignKey("auth.User", models.CASCADE)
        name, path, args, kwargs = field.deconstruct()
        self.assertEqual(path, "django.db.models.ForeignKey")
        self.assertEqual(args, [])
        self.assertEqual(kwargs, {"to": "auth.User", "on_delete": models.CASCADE})
        self.assertEqual(kwargs['to'].setting_name, "AUTH_USER_MODEL")
        # Test nonexistent (for now) model
        field = models.ForeignKey("something.Else", models.CASCADE)
        name, path, args, kwargs = field.deconstruct()
        self.assertEqual(path, "django.db.models.ForeignKey")
        self.assertEqual(args, [])
        self.assertEqual(kwargs, {"to": "something.Else", "on_delete": models.CASCADE})
        # Test on_delete
        field = models.ForeignKey("auth.User", models.SET_NULL)
        name, path, args, kwargs = field.deconstruct()
        self.assertEqual(path, "django.db.models.ForeignKey")
        self.assertEqual(args, [])
        self.assertEqual(kwargs, {"to": "auth.User", "on_delete": models.SET_NULL})
        # Test to_field preservation
        field = models.ForeignKey("auth.Permission", models.CASCADE, to_field="foobar")
        name, path, args, kwargs = field.deconstruct()
        self.assertEqual(path, "django.db.models.ForeignKey")
        self.assertEqual(args, [])
        self.assertEqual(kwargs, {"to": "auth.Permission", "to_field": "foobar", "on_delete": models.CASCADE})
        # Test related_name preservation
        field = models.ForeignKey("auth.Permission", models.CASCADE, related_name="foobar")
        name, path, args, kwargs = field.deconstruct()
        self.assertEqual(path, "django.db.models.ForeignKey")
        self.assertEqual(args, [])
        self.assertEqual(kwargs, {"to": "auth.Permission", "related_name": "foobar", "on_delete": models.CASCADE}) 
Example 28
Project: djangocms-forms   Author: mishbahr   File: 0001_initial.py    License: BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def forwards(self, orm):
        # Adding model 'Form'
        db.create_table(u'djangocms_forms_form', (
            (u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
            ('name', self.gf('django.db.models.fields.CharField')(max_length=255, db_index=True)),
        ))
        db.send_create_signal(u'djangocms_forms', ['Form'])

        # Adding model 'FormDefinition'
        db.create_table(u'djangocms_forms_formdefinition', (
            (u'cmsplugin_ptr', self.gf('django.db.models.fields.related.OneToOneField')(to=orm['cms.CMSPlugin'], unique=True, primary_key=True)),
            ('name', self.gf('django.db.models.fields.CharField')(max_length=255)),
            ('title', self.gf('django.db.models.fields.CharField')(max_length=150, blank=True)),
            ('description', self.gf('django.db.models.fields.TextField')(blank=True)),
            ('submit_btn_txt', self.gf('django.db.models.fields.CharField')(default=u'Submit', max_length=100)),
            ('post_submit_msg', self.gf('django.db.models.fields.TextField')(default=u'Thank You', blank=True)),
            ('success_redirect', self.gf('django.db.models.fields.BooleanField')(default=False)),
            ('page_redirect', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['cms.Page'], null=True, on_delete=models.SET_NULL, blank=True)),
            ('external_redirect', self.gf('django.db.models.fields.URLField')(max_length=200, blank=True)),
            ('email_to', self.gf('django.db.models.fields.CharField')(max_length=255, blank=True)),
            ('email_from', self.gf('django.db.models.fields.EmailField')(max_length=255, blank=True)),
            ('email_subject', self.gf('django.db.models.fields.CharField')(max_length=255, blank=True)),
            ('email_uploaded_files', self.gf('django.db.models.fields.BooleanField')(default=True)),
            ('save_data', self.gf('django.db.models.fields.BooleanField')(default=True)),
            ('spam_protection', self.gf('django.db.models.fields.SmallIntegerField')(default=0)),
            ('form_template', self.gf('django.db.models.fields.CharField')(default='djangocms_forms/form_template/default.html', max_length=150, blank=True)),
            ('plugin_reference', self.gf('django.db.models.fields.related.ForeignKey')(related_name='plugin', null=True, on_delete=models.SET_NULL, to=orm['djangocms_forms.Form'])),
        ))
        db.send_create_signal(u'djangocms_forms', ['FormDefinition'])

        # Adding model 'FormField'
        db.create_table(u'djangocms_forms_formfield', (
            (u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
            ('form', self.gf('django.db.models.fields.related.ForeignKey')(related_name='fields', to=orm['djangocms_forms.FormDefinition'])),
            ('field_type', self.gf('django.db.models.fields.CharField')(default='text', max_length=100)),
            ('label', self.gf('django.db.models.fields.CharField')(max_length=255)),
            ('placeholder_text', self.gf('django.db.models.fields.CharField')(max_length=100, blank=True)),
            ('required', self.gf('django.db.models.fields.BooleanField')(default=True)),
            ('help_text', self.gf('django.db.models.fields.TextField')(blank=True)),
            ('initial', self.gf('django.db.models.fields.CharField')(max_length=255, blank=True)),
            ('choice_values', self.gf('django.db.models.fields.TextField')(blank=True)),
            ('position', self.gf('django.db.models.fields.PositiveIntegerField')(null=True, blank=True)),
        ))
        db.send_create_signal(u'djangocms_forms', ['FormField'])

        # Adding model 'FormSubmission'
        db.create_table(u'djangocms_forms_formsubmission', (
            (u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
            ('plugin', self.gf('django.db.models.fields.related.ForeignKey')(related_name='submissions', to=orm['djangocms_forms.Form'])),
            ('creation_date', self.gf('django.db.models.fields.DateTimeField')(auto_now=True, blank=True)),
            ('created_by', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['auth.User'], null=True)),
            ('ip', self.gf('django.db.models.fields.GenericIPAddressField')(max_length=39, null=True, blank=True)),
            ('form_data', self.gf('jsonfield.fields.JSONField')()),
        ))
        db.send_create_signal(u'djangocms_forms', ['FormSubmission'])