Having a bit of trouble using multiple inlines within my admin console over 3 models which im playing around with.
Models:
class carManufacturer(models.Model):
name = models.CharField(max_length=200)
country = models.CharField(max_length=200)
description = models.CharField(max_length=1000)
def __unicode__(self):
return self.name
class vehicleModel(models.Model):
carManufacturer = models.ForeignKey(carManufacturer)
model = models.CharField(max_length=200)
def __unicode__(self):
return self.model
class vehicleCode(models.Model):
vehicleModel = models.ForeignKey(vehicleModel)
variantCode = models.CharField(max_length=200)
variantBadge = models.CharField(max_length=200)
manuStart = models.DateTimeField('Manufacture Start Date')
manuFin = models.DateTimeField('Manufacture End Date')
def __unicode__(self):
return self.variantCode
What I'm looking to do is when I add a car Manufacturer I can add car Models via my inline, and when I am editing models, I can edit vehicle codes/variants via another inline.
I have an admin.py file I am using:
from Cars.models import carManufacturer, vehicleModel, vehicleCode
from django.contrib import admin
class modelInline(admin.TabularInline):
model = vehicleModel
extra = 0
class codeInline(admin.TabularInline):
variantCode = vehicleCode
extra = 0
class CarAdmin(admin.ModelAdmin):
fields = ['name', 'description', 'country']
inlines = [modelInline]
class VehicleModelAdmin(admin.ModelAdmin):
fields = ['carManufacturer','model']
#inlines = [codeInline]
admin.site.register(carManufacturer, CarAdmin)
admin.site.register(vehicleModel, VehicleModelAdmin)
As soon as I uncomment my second inline which uses the same method as the first I get the following error:
'model' is a required attribute of 'VehicleModelAdmin.inlines[0]'.
I am struggling to understand what I am doing wrong, especially since I have got the first inline working, any input would be much appreciated
The codeInline doesn't have model field for any TabularInline you do need model field like one above. It should have something like following
class codeInline(admin.TabularInline):
model = vehicleCode
extra = 0
Related
I have a simple task: I need to expose player name related to Game in game list (Django Admin). Game object has ManyToMany relationship with Player object via 'players' attribute. The problem is that now I have empty 'players_list' field (empty list means I don't know what to do and just leave it here[enter image description here][1]), though I tried Player.objects.all() and obviously got all players even those who are not bound to particular game.
I feel it has simple solution but my brain refuses to work after 55 opened tabs.
Thanks in advance!
This is my models.py
from django.db import model
class Player(models.Model):
name = models.CharField(max_length=54, default="")
email = models.EmailField(max_length=54)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
def __str__(self):
return self.name
class Game(models.Model):
name = models.CharField(max_length=254, default="")
players = models.ManyToManyField(Player, blank=True, related_name='player_games')
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
players_list = []
def __str__(self):
return self.name
and admin.py
from django.contrib import admin
from .models import Game, Player
class PlayerInline(admin.TabularInline):
model = Game.players.through
#admin.register(Player)
class Admin(admin.ModelAdmin):
search_fields = ['name', 'email']
list_display = ('name', 'email', 'created_at', 'updated_at')
inlines = [
PlayerInline,
]
#admin.register(Game)
class AdminAdmin(admin.ModelAdmin):
list_display = ('name', 'created_at', 'updated_at', 'players_list')
inlines = [
PlayerInline,
]
exclude = ('players',)
Pic as it looks now
[1]: https://i.stack.imgur.com/KVJ5y.png
The best approach here will be creating custom method in your model instead of single variable. You will not even have to change your list_display:
class Game(models.Model):
...
def players_list(self):
return self.players.all()
Alternatively, if you want only names of players or anything else from, you can change it (or add another method) to something like that:
class Game(models.Model):
...
def players_list(self):
return [player for player in self.players.all()]
# or
return [player.name for player in self.players.all()]
This is called list comprehension, if you are not familiar with it.
models.py
class Product(models.Model):
title = models.CharField(max_length=200)
description = models.TextField()
price = models.DecimalField(decimal_places=5,max_digits= 1500)
summary = models.TextField()
featured = models.BooleanField()
def __str__(self):
return self.title
# return f'product title:{self.title}-product price:{self.price}'workok
class Meta:
ordering = ('-price',)
class Opinion(models.Model):
name = models.CharField(max_length=20)
email = models.EmailField(max_length=20)
body = models.TextField()
opinion_date = models.DateTimeField(auto_now_add=True)
active = models.BooleanField(default=False)
product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name='opinion_set')
def __str__(self):
return f'({self.name}) add opinion about ({self.product})'
forms.py:
from django.forms import ModelForm
from .models import Product #space after from keyword
class OpinionModelForm(ModelForm):
class Meta:
model = Product
fields = ['name','email','body','product']
invalid in code line :
fields = ['name','email','body','product'] #---- NOT WORK !!!
, but if i change above code to :
fields = "__all__" # ----it is WORKing ok without any problem !!
question : what is the error? I am not need all the fields in the Product model (like active boolean field), I need only 'name','email','body','product' fields .
According to the error and the code you provided the main problem is that you made a mistake in chosing model in serializer:
class OpinionModelForm(ModelForm):
class Meta:
model = Product
fields = ['name','email','body','product']
Serializer name is OpinionModelForm and listed fields belong to Opinion so I guess you actually wanted to serialize Opinion and no Product as you defined at this line:
model = Product
Simply change it to:
model = Opinion
Trying to learn stacked inlines in Django. Have a very basic setup
For admin.py
from django.contrib import admin
from .models import Picture, Review
class ReviewInline(admin.StackedInline):
model = Review
save_on_top = True
fields = ["reviewer"]
##admin.register(Picture)
class PictureAdmin(admin.ModelAdmin):
save_on_top = True
fields = ["painter"]
inlines = [ReviewInline,]
admin.site.register(Review)
admin.site.register(Picture, PictureAdmin)
For models.py
from django.db import models
class Picture(models.Model):
painter = models.CharField(("painter"), max_length=255)
def __str__(self):
return self.painter
class Review(models.Model):
picture = models.ForeignKey(Picture, on_delete=models.CASCADE)
reviewer = models.CharField( max_length=255)
extra = 0
def __str__(self):
return self.reviewer
As can be seen there is no "add more item" button. I think this might be a JS issue but am not sure(I do have JS enabled in browser)
Anyone has any idea?
I beleive you have the extra=0 in the wrong class, it should be in the Inline not the Model...
Remove extra=0 from the model
class Review(models.Model):
picture = models.ForeignKey(Picture, on_delete=models.CASCADE)
reviewer = models.CharField( max_length=255)
# extra = 0 <---- remove this
def __str__(self):
return self.reviewer
Add it to the Inline:
class ReviewInline(admin.StackedInline):
model = Review
save_on_top = True
extra = 0
fields = ["reviewer"]
Justification comes from this snippet from this example:
#admin.register(Painter)
class PainterAdmin(admin.ModelAdmin):
save_on_top = True
fields = ["name"]
inlines = [PictureInline]
class ReviewInline(admin.StackedInline):
model = Review
extra = 0
fields = ["reviewer", "comment"]
Edit: Second thought you may also want to get rid of the save_on_top from the inline as well?
Clearing my Google Chrome cache solved it! I got a clue after realizing that the example worked in Microsoft Edge.
In our project, i've been making use of the latest version of django-nested-inlines v0.3.7 with django 1.7
I have the following definition in my django admin to display the inlines
class SpecsGroupedContentInline(NestedStackedInline):
model = SpecificationGroupedContent
extra = 1
fk_name = "specification"
fields = ["field_unit"]
class SpecsContentInline(NestedStackedInline):
model = SpecificationListContent
extra = 1
fk_name = "specification"
fields = ["content"]
class SpecsInline(NestedStackedInline):
model = Specification
inlines = [SpecsContentInline, SpecsGroupedContentInline]
extra = 1
fk_name = "product"
class ProductAdmin(NestedModelAdmin):
inlines = [
SpecsInline
]
list_display = ('name', 'sku')
form = ProductAdminForm
When the page loads, the page looks like this
Initial product page load
It's a bit hard to see but the specs section has a title, an inline for Listed Contents and an inline for Grouped Contents. Afterwards, there's an empty Specs section with an empty title, empty Listed Contents, and empty Grouped Contents.
When I press the "Add another Specification" button at the bottom of the Specification inline to add a new row, the result of the new entry looks like this
New Specification entry image
As you can see, the Grouped Content field "Field Unit" is missing. I'm not sure if my setup is incorrect, but i found this stack overflow entry with a similar setup to mine
Django nested inlines not working?
It is for a different error though but we have a similar inline setup so i was thinking this setup is ok for django-nested-inlines.
Also, I'm sure if it's related but is django-nested-inlines affected if a nested inline model is a foreign key of another model? The SpecificationsGroupedContent model is a foreign key of another model unlike the SpecificationsListContent. I did a quick test where the SpecsInline inlines contained either SpecsGroupedContentInline only or SpecsContentInline only. It was working perfectly when using only SpecsContentInline but the error occurs when using SpecsGroupedContentInline.
For reference, here are the models I'm using with the related model for SpecsGroupedContent
class Product(AuthorStampedModel):
name = models.CharField(max_length=100)
sku = models.CharField(unique=True, max_length=100, verbose_name='SKU')
summary = models.TextField(blank=True, default="")
def __unicode__(self):
return self.return_product_details()
def return_product_details(self):
return '%s: %s' % (self.sku, self.name)
class Specification(models.Model):
product = models.ForeignKey('Product', related_name='specs')
title = models.CharField(max_length=100)
def __unicode__(self):
return self.return_spec_string()
def return_spec_string(self):
return '%s: %s' % (self.product.return_product_details(), self.title)
class SpecificationListContent(models.Model):
specification = models.ForeignKey('Specification', related_name='list_content')
content = models.CharField(max_length=255)
class Meta:
verbose_name_plural = 'Specification Listed Contents'
def __unicode__(self):
return self.specification.return_spec_string()
class SpecificationGroupedContent(models.Model):
specification = models.ForeignKey('Specification', related_name='group_content')
field_unit = models.CharField(max_length=255)
class Meta:
verbose_name_plural = 'Specification Grouped Contents'
def __unicode__(self):
return self.specification.return_spec_string()
class SpecificationGroupedContentValue(models.Model):
specification_grouped_content = models.ForeignKey(
'SpecificationGroupedContent',
related_name='group_content_value'
)
value = models.CharField(max_length=255)
class Meta:
verbose_name_plural = 'Specification Grouped Content Values'
def __unicode__(self):
return self.specification_grouped_content.specification.return_spec_string()
Thanks
I have a django model like this.
model.py
class Event(models.Model):
name = models.CharField(max_length=255)
def __unicode__(self):
return self.name
class Location(models.Model):
name = models.CharField(max_length=255)
def __unicode__(self):
return self.name
class Occurrence(models.Model):
event = models.ForeignKey(Event)
location = models.ForeignKey(Location)
class TimeSlot(models.Model):
occurrence = models.ForeignKey(Occurrence)
start = models.DateTimeField()
end = models.DateTimeField()
admin.py
class TimeSlotInline(admin.StackedInline):
model = TimeSlot
extra = 1
class OccurrenceInline(admin.StackedInline):
model = Occurrence
inlines = [TimeSlotInline,]
extra = 2
class EventAdmin(admin.ModelAdmin):
inlines = [OccurrenceInline,]
admin.site.register(Event, EventAdmin)
admin.site.register(Location)
I want to display all fields in one page in admin page.(When adding new records.)
Multiple inline doesn't work.(Only first inline comes.)
Is there any other way to do this ?
Update: Can I do this by modifying admin.py file. Can I add a customized form to inlines of admin.py?
You can't have nested inlines (inlines within inlines)in the Django admin at the moment
EDIT
Nested inlines in the Django admin?
It's supposed to be:
class OccurrenceInline(admin.StackedInline):
model = Occurrence
extra = 2
class EventAdmin(admin.ModelAdmin):
inlines = [OccurrenceInline, TimeSlotInline,]