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,]
Related
These are my models:
class Partner(models.Model):
name = models.CharField(max_length=200, verbose_name="Organisation name")
class ResearchActivity(models.Model):
title = models.CharField(max_length=200)
partner = models.ManyToManyField(ActivityPartner, blank=True)
I'd like, in the Django administration forms, to have a field in my Partner edit form representing the ResearchActivity linked to that Partner.
Can this be achieved by adding a field to my Partner model (say, naming it linked_partner) and then edit my admin.py like so:
#admin.register(ActivityPartner)
class ActivityPartnerAdmin(admin.ModelAdmin):
search_fields = ['academic',]
autocomplete_fields = ['partnership_type', 'relationship_type', 'academic_links']
def get_changeform_initial_data(self, request):
return {'live_contract': ResearchActivity.objects.all().filter(linked_partner__id=request.ResearchActivity.partner.id)}
?
I have just come across in the display() decorator, new from Django 3.2. With it, I can simply do:
#admin.register(ActivityPartner)
class ActivityPartnerAdmin(admin.ModelAdmin):
search_fields = ['academic',]
autocomplete_fields = ['partnership_type', 'relationship_type', 'academic_links',]
readonly_fields = ('get_ra',)
#admin.display(description='Live contract(s)')
def get_ra(self, obj):
return list(ResearchActivity.objects.filter(partner=obj.id))
to achieve what I want.
If I also wanted to edit those ManyToMany relations, I can use the inlines option:
class LiveContractsInline(admin.TabularInline):
model = ResearchActivity.partner.through
#admin.register(ActivityPartner)
class ActivityPartnerAdmin(admin.ModelAdmin):
inlines = [
LiveContractsInline,
]
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
In my Django Rest Framework api I am attempting to add a property to my model UserPosts that returns all likes for said post. Despite my best efforts I keep running into this error. Here is my post model below:
class UserPosts(models.Model):
userProfile = models.ForeignKey(UserProfile, related_name="posts", on_delete=models.CASCADE)
image = models.ImageField()
caption = models.CharField(max_length=240)
#property
def get_likes(self):
from liked.models import Like
return Like(post=self)
and here is my like model:
class Like(models.Model):
user = models.OneToOneField(UserProfile, on_delete=models.CASCADE,)
post = models.ForeignKey(UserPosts, on_delete=models.CASCADE)
liked_at = models.DateTimeField()
and lastly the post serializer:
class postSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = models.UserPosts
fields = ('userProfile', 'image', 'caption', 'likes')
Thanks.
You have at least three ways. First as #WillemVanOnsem said, by the many_to_one change the likes to like_set
class postSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = models.UserPosts
fields = ('userProfile', 'image', 'caption', 'like_set')
# ^^^^^
Second rename your model's property to likes and fix the queryset inside it
class UserPosts(models.Model):
userProfile = models.ForeignKey(UserProfile, related_name="posts", on_delete=models.CASCADE)
image = models.ImageField()
caption = models.CharField(max_length=240)
#property
def likes(self):
# ^^^^^
from liked.models import Like
return Like.objects.filter(post=self).values() or []
# solution you try ^^^^^^^
return self.like_set.values() or []
# more django way
And Third, the most simple and elegant way for me, is to remove your get_likes and add the related_name to the post ForeignKey:
class Like(models.Model):
user = models.OneToOneField(UserProfile, on_delete=models.CASCADE,)
post = models.ForeignKey(UserPosts, related_name='likes', on_delete=models.CASCADE)
# ^^^^^^^^^^^
liked_at = models.DateTimeField()
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
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