monty700
monty700

Reputation: 13

How do you hide Django model fields with foreign keys?

I have a seminar that has several multiple choice questions.

Here is the seminar model:

class Seminar(models.Model):
    seminar_name = models.CharField(max_length = 60)
    is_active = models.BooleanField(default = True)
    seminar_date = models.DateField(null=True, blank=True)

And here is the model for the multiple choice questions:

class Page(models.Model):
    seminar = models.ForeignKey(Seminar)
    multiple_choice_group = models.ForeignKey(MultipleChoiceGroup, null=True, blank=True, verbose_name="Multiple Choice Question")
    page_id = models.IntegerField(verbose_name="Page ID")

I have the following in admin.py:

class PageInline(admin.StackedInline):
    model = Page
    extra = 0
    def get_ordering(self, request):
        return ['page_id']

    # Limit the multiple choice questions that match the seminar that is being edited.
    def formfield_for_foreignkey(self, db_field, request, **kwargs):
        if db_field.name == "multiple_choice_group":
            try:
                parent_obj_id = request.resolver_match.args[0]
                kwargs["queryset"] = MultipleChoiceGroup.objects.filter(seminar = parent_obj_id)
            except IndexError:
                pass

        return super(PageInline, self).formfield_for_foreignkey(db_field, request, **kwargs)

class SeminarAdmin(admin.ModelAdmin):
    model = Seminar
    inlines = (PageInline,)
    list_display = ('seminar_name', 'is_active')
    def get_ordering(self, request):
        return ['seminar_name']

This is how the seminar appears:

Screenshot showing seminar fields

As shown in the screenshot, I'd like to hide some of the fields from the Seminar model and make some of them read-only.

Any help would be appreciated.

Upvotes: 1

Views: 182

Answers (1)

yagus
yagus

Reputation: 1445

You can use the Model.Admin exclude and readonly_fields attributes. See documentation here and here.

For example:

class SeminarAdmin(admin.ModelAdmin):
    model = Seminar
    inlines = (PageInline,)
    list_display = ('seminar_name', 'is_active')
    def get_ordering(self, request):
        return ['seminar_name']

    exclude = ('seminar_name',)
    readonly_fields = ('is_active',)

Upvotes: 1

Related Questions