Django admin multiple querysets on one page - django

How to have multiple tables(queryset) on one page in django admin.
For example:
When i go to the company page, i can see the list of departments in the company, i can also see the list of employees in the company.

You can use InlineModelAdmin objects to implement this, although if you want to do nested inlines you should check out this post. Although as that post says:
...it would be a kind of convoluted design to implement.
You didn't provide any code here so the best I can do is guess your model relationships.
models.py
from django.db import models
class Department(models.Model):
name = models.CharField(max_length=250)
...
class Employee(models.Model):
name = models.CharField(max_length=250)
...
class Company(models.Model):
name = models.CharField(max_length=250)
departments = models.ForeignKey(Department)
employees = models.ForeignKey(Employee)
...
admin.py
from django.contrib import admin
class EmployeeInline(admin.StackedInline):
model = Employee
class DepartmentInline(admin.StackedInline):
model = Department
class CompanyAdmin(admin.ModelAdmin):
list_display = ('name')
inlines = [DepartmentInline, EmployeeInline]
admin.site.register(CompanyAdmin)

Related

How to ordering category items a to z in django admin panel?

I have a business directory and when i add new company, categories listing mixed style. How can i order categories a to z.
I added my model these meta ordering but didn't worked.
class Category(models.Model):
name = models.CharField(max_length=100)
class Meta:
ordering = ['name']
You can write a class in your admin.py file, like the following:
from django.contrib import admin
from .models import Category
class CategoryAdmin(admin.ModelAdmin):
ordering = ['name']
admin.site.register(Category,CategoryAdmin)

Setting a Django ForeignKey to multiple models

I have a simple model called WebProfile that stores a webpage URL and its title. This model has a ForeignKey to a Student model, which allows me to store the student's bookmarks.
I would like to reuse this model to also store bookmarks saved by teachers. What is the best way to have the owner ForeignKey point to either a Student or Teacher?
Note: in my actual use case, the target model classes are conceptually very different and do not share any common fields other than the WebProfile links.
class Student(models.Model):
...
class Teacher(models.Model):
...
class WebProfile(models.Model):
title = models.CharField(max_length=50)
link = models.URLField()
owner = models.ForeignKey('Student', on_delete=models.CASCADE, related_name="bookmarks")
If Teacher and Student are related to the User model you could change the ForeignKey in WebProfile to be related to the User model instead.
From there you can then workout when you get a WebProfile object whether the user is a Student or Teacher.
I was able to solve the problem by using Generic Relations as described in Django documentation
from django.contrib.contenttypes.fields import GenericForeignKey
from django.contrib.contenttypes.models import ContentType
class WebProfile(models.Model):
title = models.CharField(max_length=50)
link = models.URLField()
owner_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
owner_id = models.PositiveIntegerField()
owner = GenericForeignKey('owner_type', 'owner_id')

Django OneToOneField and Admin UI

I am having a confusion on how to model a relationship in Django so that it can be edited inline in the Django Admin.
Let me explain the scenario.
I have a Customer Model and An Address Model. In the customer model I have a OneToOneField relationship to Address once for billing and once for shipping address.
class Address(models.Model):
pass
class Employee(models.Model):
billing_address = models.OneToOneField(Address)
shipping_address = models.OneToOneField(Address)
# Many more such fields
Now with this model there is no easy way to make them inline in Admin. I have tried the following
class AddressInline(admin.TabularInline):
model = Address
class Customer(admin.ModelAdmin):
inlines = [AddressInline, ]
I keep getting an error,
<class 'employee.admin.AddressInline'>: (admin.E202) 'employee.Address' has no ForeignKey to 'employee.Customer'.
Now I know there are other bugs similar to this one. ie. Use OneToOneField inlined in Django Admin and Django admin - OneToOneField inline throws "has no ForeignKey" exception
But I think my question is slightly different to warrant this post. Please help!
#1
models.py
class BillingAddress(models.Model):
employee = models.OneToOneField(to=Employee, related_name='billing_address')
class Employee(models.Model):
# Many more such fields
admin.py
class AddressInline(admin.TabularInline):
model = BillingAddress
extra = 1
#admin.register(Employee)
class EmployeeAdmin(admin.ModelAdmin):
inlines = [AddressInline, ]
#2
models.py
class Address(models.Model):
name = models.CharField(max_length=250)
employee = models.ForeignKey(to=Employee, related_name='addresses')
class Employee(models.Model):
# Many more such fields
admin.py
class AddressInline(admin.TabularInline):
model = Address
#admin.register(Employee)
class EmployeeAdmin(admin.ModelAdmin):
inlines = [AddressInline, ]
Full Example:
models.py
class Company(models.Model):
pass
class CompanyScheduler(models.Model):
company = models.OneToOneField(
to=Company,
related_name='scheduling',
on_delete=models.CASCADE,
)
start = models.DateField()
finish = models.DateField()
admin.py
class CompanySchedulerInLine(admin.TabularInline):
model = CompanySchedulerInLine
extra = 1
#admin.register(CompanyModelAdmin)
class CompanyModelAdmin(admin.ModelAdmin):
inlines = [
SchedulerInLine,
]
UI

Many-To-Many Fields View on Django Admin

Basically I am trying to recreate a fields in this model that is similar to django user authenticate system, for this I try using many-to-many fields but it ended up like this.
I am trying to have another field that can show what exist and another field for I have chosen similar to django admin, which looks like this.
This is my code
class Category(models.Model):
name = models.CharField(max_length=128, unique=True)
class BlogPage(models.Model):
category = models.ManyToManyField(Category)
title = models.CharField(max_length=128)
preview = models.TextField(max_length=256)
content = models.TextField()
I believe what you want is a filter_horizontal widget used in the Admin template. This should help: Django Admin ManyToManyField
currently i am able to display many to many fields is admin panel
models.py
class Abc(models.Model):
course = models.ManyToManyField(Course, blank=True)
admin.py
class AbcsAdmin(admin.ModelAdmin):
"""
Admin panel management for Alumni
"""
list_display = ["id","get_course"]
def get_course(self,obj):
return [course.name for course in obj.course.all()]

Django 1.2.1 Inline Admin for Many To Many Fields

I recently upgraded to Django 1.2.1 because I was specifically interested in the ability to have basic many-to-many inline fields. When using the admin like so:
Initial models:
class Ingredient(models.Model):
name = models.TextField()
class Recipe(models.Model):
ingredients = models.ManyToManyField(Ingredient)
Initial admin:
class IngredientInline(admin.TabularInline):
model = Recipe.ingredients.through
class RecipeOptions(admin.ModelAdmin):
inlines = [IngredientInline,]
exclude = ('ingredients',)
admin.site.register(Recipe,RecipeOptions)
What I got was the same form you would normally see on a ManyToMany field, with some extra rows. Supplying it with extra parameters like an Ingredient ModelForm did not help. Suspecting that something might be wrong with the basic ModelForm associations via model = Foo.manyfields.through, I decided to see if an intermediary model would help. It now displays a working inline form via:
New models:
class RecipeJoin(models.Model):
pass
class Recipe(models.Model):
ingredients = models.ManyToManyField(RecipeJoin,through='Ingredient')
class Ingredient(models.Model):
name = models.TextField()
test = models.ForeignKey(RecipeJoin,null=True,blank=True,editable=False)
New admin:
class IngredientInline(admin.TabularInline):
model = Recipe.ingredients.through
class RecipeOptions(admin.ModelAdmin):
inlines = [IngredientInline,]
admin.site.register(Recipe,RecipeOptions)
Obviously this is not a hack I'd like to use. Anyone know of a way to get a manytomany relationship to display via inline form without either (a) creating an entirely new BasicInline form and template or (b) putting it through an intermediary (or generic admin) model?
TIA. (I apologize for verbosity, it's my first post so wanted to be thorough).
Do one of these examples accomplish what you are trying to do?
a:
# Models:
class Ingredient(models.Model):
name = models.CharField(max_length=128)
class Recipe(models.Model):
name = models.CharField(max_length=128)
ingredients = models.ManyToManyField(Ingredient, through='RecipeIngredient')
class RecipeIngredient(models.Model):
recipe = models.ForeignKey(Recipe)
ingredient = models.ForeignKey(Ingredient)
amount = models.CharField(max_length=128)
# Admin:
class RecipeIngredientInline(admin.TabularInline):
model = Recipe.ingredients.through
class RecipeAdmin(admin.ModelAdmin):
inlines = [RecipeIngredientInline,]
class IngredientAdmin(admin.ModelAdmin):
pass
admin.site.register(Recipe,RecipeAdmin)
admin.site.register(Ingredient, IngredientAdmin)
b:
# Models:
class Recipe(models.Model):
name = models.CharField(max_length=128)
class Ingredient(models.Model):
name = models.CharField(max_length=128)
recipe = models.ForeignKey(Recipe)
# Admin:
class IngredientInline(admin.TabularInline):
model = Ingredient
class RecipeAdmin(admin.ModelAdmin):
inlines = [IngredientInline,]
admin.site.register(Recipe,RecipeAdmin)
If I remember correctly (and it's been a while since I've done this part), you need to add the admin for Ingredient and set it to have the custom ModelForm. Then that form will be used in the inline version of Ingredient.