Django authentication inlinemodeladmin - but with a common relationship

Earlier I had such models:

class AssemblyAnnotation(models.Model): assembly = models.ForeignKey(Assembly) type = models.ForeignKey(AssemblyAnnotationType) ... def clean(self): from django.core.exceptions import ValidationError if not self.type.can_annotate_aliases and self.assembly.alias_of_id is not None: raise ValidationError('The selected annotation type cannot be applied to this assembly.') 

The effect was that the new AssemblyAnnotation (attached via the built-in) can only have a subset of the values ​​for the type attribute depending on the parent assembly.

It worked perfectly.

Now it's time to apply these annotations to other objects that are slightly different:

 class ObjectAnnotation(models.Model): content_type = models.ForeignKey(ContentType) object_id = models.PositiveIntegerField() content_object = generic.GenericForeignKey() type = models.ForeignKey(AssemblyAnnotationType) ... def clean(self): from django.core.exceptions import ValidationError if self.content_type == ContentType.objects.get_for_model(Assembly): if not self.type.can_annotate_aliases and self.content_object.alias_of_id is not None: raise ValidationError('The selected annotation type cannot be applied to this assembly.') 

As you can see, I want the same rules to apply. However, there is a problem. The GenericInline that I am currently using does not set self.content_type before running my clean () method.

Is there any way around this? Am I doing it wrong?

Thanks for the help.

+6
django django-admin models
source share
2 answers

Would the right side return the list in if self.content_type == ContentType.objects.get_for_model(Assembly): :?

I think you will need to do if self.content_type in ContentType.objects.get_for_model(Assembly):

0
source share

I use the same as you, and it works as expected. Here is my code:

In models:

 class GroupFlagIntermediate(models.Model): group_flag = models.ForeignKey(GroupFlag, related_name='flag_set') content_type = models.ForeignKey(ContentType, verbose_name='Flag Type') flag_pk = models.CharField('Flag PK', max_length=100, blank=True, default='') flag = generic.GenericForeignKey('content_type', 'flag_pk') def clean(self): from django.core.exceptions import ValidationError if not self.is_valid_flag(self.content_type.model_class()): raise ValidationError('The selected flag is not a real Flag.') 

And in admin:

 class GroupFlagIntermediateInline(admin.TabularInline): model = GroupFlagIntermediate class GroupFlagAdmin(admin.ModelAdmin): list_display = ('name', ...) inlines = [GroupFlagIntermediateInline] admin.site.register(GroupFlag, GroupFlagAdmin) 

After some tests, I found that the fields content_type and object_id ( flag_pk in my case) are set before calling clean (), but GenericForeignKey ( flag in my case) doesn’t.

0
source share

All Articles