I have a Django related question about foreign keys in the admin panel. I'm facing the following situation:
class Driver(models.Model):
name = models.CharField(max_length=200)
executable = models.CharField(max_length=200)
class Device(models.Model):
name = models.CharField(max_length=200)
bound_driver = models.ForeignKey(Driver)
class DriverAssignment(models.Model):
device = models.ForeignKey(Device)
driver = models.ForeignKey(Driver)
Every device needs to have a bound driver (which it uses). DriverAssignment should be the table which shows which driver can be used by which device. So one device can have multiple possibilities of drivers which can be bound. Now i would like to have a dropdown on my admin panel showing all possible drivers for a specific device to select the 'bound_driver'.
How can i do this in Django? This is probably an easy thing for an experienced Django guy. I hope someone can give me a hint since i'm kind of new to Django. Thanks a lot!
For Django >1.8
Use the InlineModelAdmin (docs for 2.2) as explained there:
models.py
from django.db import models
class Author(models.Model):
name = models.CharField(max_length=100)
class Book(models.Model):
author = models.ForeignKey(Author, on_delete=models.CASCADE)
title = models.CharField(max_length=100)
admin.py
from django.contrib import admin
class BookInline(admin.TabularInline):
model = Book
class AuthorAdmin(admin.ModelAdmin):
inlines = [
BookInline,
]
Change your model Structure to This:
class Driver(models.Model):
name = models.CharField(max_length=200)
executable = models.CharField(max_length=200)
class Device(models.Model):
name = models.CharField(max_length=200)
bound_driver = models.ForeignKey(Driver, related_name="bound_to")
available_drivers = models.ManyToManyfield(Driver)
ManyToManyField would do the same work as DriverAssignment Table.
You can add Available drivers in Available drivers field.
But then You would also Want that bound_driver is one of the Available Drivers. This validation you will have to do in forms. For that you have to over-ride Admin forms. See links
Links of Reference:
ManytoMany field: https://docs.djangoproject.com/en/1.6/ref/models/fields/#django.db.models.ManyToManyField
Model Admin (to over-ride admin functionality):
https://docs.djangoproject.com/en/1.6/ref/contrib/admin/#modeladmin-objects
You will have to spend some time reading and implementing if you want ot learn more. :)
OR
If you want to go with the same structure, than you will have to over-ride the form in ModelAdmin see here and Provide you custom form, which will be something like this:
class CustomForm(ModelForm)
bound_driver = forms.ModelChoiceField(queryset = <your custom queryset that returns only available drivers>, ...)
class Meta:
model = Device
https://docs.djangoproject.com/en/1.6/ref/contrib/admin/#django.contrib.admin.ModelAdmin.form
There is a snippet for inverse inlines. If you still need it you may try this:
https://gist.github.com/mzbyszewska/8b6afc312b024832aa85
It has been used by me for OneToOneField in django 1.5 and 1.6. Unfortunately I did not test it for ForeignKeyField, but the one of the previous users claims that it works for ForeignKeyField either.
The best description of the snippet is contained in it. The Person class is your DriverAssignment class and Device correspond to the Address class in the example below:
Example:
from django.db import models
class Address(models.Model):
street = models.CharField(max_length = 255)
zipcode = models.CharField(max_length = 10)
city = models.CharField(max_length = 255)
class Person(models.Model):
name = models.CharField(max_length = 255)
business_addr = models.ForeignKey(Address,
related_name = 'business_addr')
home_addr = models.OneToOneField(Address, related_name = 'home_addr')
other_addr = models.OneToOneField(Address, related_name = 'other_addr')
You use reverseadmin in the following way:
from django.contrib import admin
from django.db import models
from models import Person
from reverseadmin import ReverseModelAdmin
class AddressForm(models.Form):
pass
class PersonAdmin(ReverseModelAdmin):
inline_type = 'tabular'
inline_reverse = ('business_addr', ('home_addr', AddressForm), ('other_addr' (
'form': OtherForm
'exclude': ()
)))
admin.site.register(Person, PersonAdmin)
inline_type can be either "tabular" or "stacked" for tabular and
stacked inlines respectively.
Related
I try to develop a relationship as
One admin can add one or many subscription plans.
I try this but not worked
from django.db import models
from django.contrib import admin
class SubscriptionPlansModel(models.Model):
title = models.CharField(max_length=50)
price = models.IntegerField()
duraion = models.IntegerField()
admin = models.ForeignKey(admin,on_delete=models.CASCADE)
you literally making a ForeignKey relation with a module not a db model
Just create "Admin" class in models file. Then, use it as foreign key.
E.g.
class Admin(admin.ModelAdmin):
pass
class SubscriptionPlansModel(models.Model):
title = models.CharField(max_length=50)
price = models.IntegerField()
duraion = models.IntegerField()
admin = models.ForeignKey(admin,on_delete=models.CASCADE)
I have a model with an attribute that is connected to another model as follow:
class Book(models.Model):
synced = models.OneToOneField('SyncedBook'
related_name='internal',
on_delete=models.CASCADE)
# some more attributes here...
#property
def book_address(self)
return self.synced.book_address
However, the book_address is a also a FK in the SyncedBook table as follow:
book_address = models.ForeignKey('Address', db_index=True, null=True, blank=True,
related_name='address_book', on_delete=models.PROTECT)
I don't know and understand how to be able to edit the book_address through the Django admin page in class BookingAdmin(admin.ModelAdmin), even though I have read over the documentation. At first I have the attribute as readonly, but now I want to be able to edit it and save the new address from the Address table. Is there a way to make it happen through the class BookingAdmin(admin.ModelAdmin) and how? Any example and solution would be appreciate
Model properties are typically used for presenting logically defined data for a particular model instance and not necessarily storing data on the model instance itself.
An example of when to use a model property is as follows:
# Defines a product instance
class Product(model.Models):
name = models.CharField(max_length=100)
description = models.TextField()
active = models.BooleanField(default=True)
cost = models.DecimalField(max_digits=5, decimal_places=2)
price = models.DecimalField(max_digits=5, decimal_places=2)
# calculate profits on product
#property
def profit(self)
p = self.price - self.cost
return p
In your case, you are trying to actually be able to modify data against a related model instance within the django admin. To me this sounds like more specifically an Inline (click here for documentation)
So in your case, you would need to create something like the following to your admin.py file:
class SyncedBookInline(admin.TabularInline):
model = BookInline
#admin.Register(Book)
class BookAdmin(admin.ModelAdmin):
# all your model admin settings
inlines = [SyncedBookInline]
Additional Info:
The Inline solution should still work for you. Please see the working code listed below:
models.py:
from django.db import models
class Hero(models.Model):
name = models.CharField(max_length=50)
class HeroAcquaintance(models.Model):
name = models.CharField(max_length=50)
hero = models.OneToOneField(Hero, on_delete=models.CASCADE)
admin.py:
from django.contrib import admin
from .models import *
class HeroAcquaintanceInline(admin.TabularInline):
model = HeroAcquaintance
#admin.register(Hero)
class HeroAdmin(admin.ModelAdmin):
list_display = (
'name',
)
inlines = [HeroAcquaintanceInline]
#admin.register(HeroAcquaintance)
class HeroAcquaintanceAdmin(admin.ModelAdmin):
list_display = (
'name',
)
Screenshot:
I using a nested model in a Django project.
The following snippet code is models.py:
from django.db import models
from django.db.models.deletion import CASCADE
class Model_(models.Model):
name = models.CharField(max_length=50, default="This is a model")
frequently = models.FloatField(default=1.0)
def __str__(self):
return self.name
class SubModel(models.Model):
name = models.CharField(max_length=100)
address = models.CharField(max_length=8, default='0x')
model_ = models.ForeignKey(Model_, on_delete=CASCADE)
def __str__(self):
return self.name
class Metadata(models.Model):
key = models.CharField(max_length=100)
value = models.CharField(max_length=100)
sub_model = models.ForeignKey(SubModel, on_delete=CASCADE)
This is my admin.py script:
from django.contrib import admin
from nested_inline.admin import NestedTabularInline, NestedStackedInline,\
NestedModelAdmin
from <djano-application-name>.models import Model_, SubModel, Metadata
class MetadataAdmin(NestedTabularInline):
model = Metadata
extra = 1
class SubModelAdmin(NestedStackedInline):
model = SubModel
inlines = [MetadataAdmin]
extra = 1
class Model_Admin(NestedModelAdmin):
model = Model_
inlines = [SubModelAdmin]
list_display = ['name']
admin.site.register(Model_, Model_Admin)
Question:
What is the difference between NestedStackedInline and NestedTabularInline in admin.py script?
[NOTE]:
Versions: Python 2.7 and Django 1.11
If you are using django-nested-inline, It means you wanted to edit models on the same page as a parent model and add more than 1 level of children at once with the parent object in admin.
The Django admin is just a normal Django application and you can't have a second level of inlines(nested forms) in the default Django admin.
The difference between NestedStackedInline and NestedTabularInline is just Layout. Indeed, both work exactly the same behind the scenes, the only difference is the template used for rendering. Check the official docs. So, picking one for your project is only a matter of preference regarding the interface layout.
This is how NestedStackedInline will look, each field of the model is under other.
and this is NestedTabularInline, each field of the model is in one line, column wise
I read the docs and this post... Django - Foreign Key to User model
I followed what it said and I still cannot get it to work. When I try to run the migrations I get this error in the traceback...
django.db.utils.ProgrammingError: column "author_id" cannot be cast automatically to type integer
HINT: You might need to specify "USING author_id::integer".
I just don't know how to go about fixing that error.
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class BlogCategory(models.Model):
'''model for categories'''
title = models.CharField(max_length=30)
description = models.CharField(max_length=100)
class BlogPost(models.Model):
'''a model for a blog post'''
author = models.ForeignKey(User)
date = models.DateField()
title = models.CharField(max_length=100)
post = models.TextField()
Don't use the User model directly.
From the documentation
Instead of referring to User directly, you should reference the user
model using django.contrib.auth.get_user_model()
When you define a foreign key or many-to-many relations to the user model, you should specify the custom model using the AUTH_USER_MODEL setting.
Example:
from django.conf import settings
from django.db import models
class Article(models.Model):
author = models.ForeignKey(
settings.AUTH_USER_MODEL,
on_delete=models.CASCADE,
)
If you created a custom User model, you would use setting.AUTH_USER_MODEL, if not you can go ahead an use User model
Referencing Django User model
the column "author_id" doesn't exist, looks like is the same problem from here : Django suffix ForeignKey field with _id , so to avoid this traceback you may use :
author = models.ForeignKey(User, db_column="user")
I do not know the "settings.AUTH_USER_MODEL" approach but a well-known approach and commonly used is the "Auth.User" model. Something like this on your end.
from django.contrib.auth.models import User
class BlogPost(models.Model):
'''a model for a blog post'''
author = models.ForeignKey(User)
date = models.DateField()
title = models.CharField(max_length=100)
post = models.TextField()
Building a generic app to practice learning with Django.
Two classes in Models:
class HouseInformation(models.Model):
house_name = models.CharField(max_length=200)
house_type = models.CharField(max_length=40)
address = models.CharField(max_length=200)
latitude = models.CharField(max_length=200)
longitude = models.CharField(max_length=200)
def __str__(self):
return self.house_name
class HouseReport(models.Model):
the_house = models.ForeignKey(HouseInformation)
visit_date = models.DateField()
In Admin view, I'd like to see a list of the houses with the dates they were visited. The admin.py so far is like so, and its not working:
from django.contrib import admin
from housing.models import HouseInformation
from housing.models import HouseReport
class HouseReport(admin.ModelAdmin)
list_display = ('the_house')
admin.site.register(HouseInformation, HouseReport)
I hope the one-to-many is represented correctly (one house can have many visits).
The problem is the missing ::
class HouseReport(admin.ModelAdmin):
^
Speaking about the task you've initially wanted to solve, check the InlineModelAdmin classes:
The admin interface has the ability to edit models on the same page as
a parent model. These are called inlines.
Add this to the admin.py:
from django.contrib import admin
from housing.models import HouseInformation, HouseReport
class HouseReportInline(admin.TabularInline):
model = HouseReport
class HouseAdmin(admin.ModelAdmin):
inlines = [
HouseReportInline,
]
admin.site.register(HouseInformation, HouseAdmin)
And you will see the House information and all of the HouseReports associated with a House on the House admin page.
You forgot the : after the class definition in line 5
class HouseReport(admin.ModelAdmin):
And you have to write
...
list_display = ('the_house',)
...
notice the trailing comma? It tells python, that it should create a tuple