Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django present related_name objects in admin model

I have the following models:

class A(models.Model):
    name = models.CharField(max_length=100)
    c = models.ForeignKey(C, related_name='letters_c', null=True, blank=True)
    ...


class B(models.Model):
    id= models.CharField(max_length=200, blank=False, default="")
    a = models.ForeignKey(A, related_name='letters_a', default=0)
    ...

With the following admin:

class AAdmin(admin.ModelAdmin):
    fields = ['name', 'c', 'letters_a']
    list_display = ['name']
    ordering = ['name']

I got an error

'letters_a' not found.

I guess I do not fully understand the logic between foreign keys and the representation of them in Django models.

I want to be able to add/edit and see in the Django admin the class A letters_a related_name objects.

How can I do it?

like image 952
Reshef Avatar asked Jun 28 '16 07:06

Reshef


People also ask

What is Related_name in Django model?

The related_name attribute specifies the name of the reverse relation from the User model back to your model. If you don't specify a related_name, Django automatically creates one using the name of your model with the suffix _set.

Is it possible to automatically generate an admin page in Django?

Generating admin sites for your staff or clients to add, change and delete content is tedious work that doesn't require much creativity. For that reason, Django entirely automates creation of admin interfaces for models.


1 Answers

To have related model in your admin use InlineAdmin

in your case, add inline admin definition for class B:

class BInlineAdmin(admin.TabularInline):
    model = B

class AAdmin(admin.ModelAdmin):
     fields = ['name', 'c']
     list_display = ['name']
     ordering = ['name']
     inlines = [BInlineAdmin]
like image 92
Jerzyk Avatar answered Nov 10 '22 21:11

Jerzyk