I really need somebody to explain/show me how I can achieve a TabularInline display in the django admin console of my example. Could somebody help me out?
My models are as follows:
from django.db import models
class Player(models.Model):
player_id = models.IntegerField(primary_key=True)
team = models.ForeignKey(Team)
player_name = models.CharField(max_length=140)
position = models.CharField(max_length=10)
def __str__(self):
return '%s' % (self.player_name)
class MatchdayStats(models.Model):
MATCHDAY_STATS_ID = models.AutoField(primary_key=True)
appeared = models.BooleanField(default=False)
goal = models.IntegerField(default=0)
minutes_under_60 = models.BooleanField(default=False)
minutes_60 = models.BooleanField(default=False)
assist = models.IntegerField(default=0)
def __str__(self):
return '%s' % (self.MATCHDAY_STATS_ID)
class PlayerGameweekStats(models.Model):
PLAYER_GAMEWEEK_ALLSTATS_ID = models.AutoField(primary_key=True)
player = models.ForeignKey(Player)
gameweek = models.ForeignKey('fixturesresults.Gameweek')
matchday_stats = models.ForeignKey(MatchdayStats)
def __str__(self):
return '%s (gw=%s,msid=%s)' % (self.player.player_name,self.gameweek.GAMEWEEK_ID,self.matchday_stats.MATCHDAY_STATS_ID)
I would like there to be a tabular display for the PlayerGameweekStats model, where you can enter MatchdayStats fields for each player.
The admin code below causes a Foreign Key error <class 'playerteamstats.models.MatchdayStats'> has no ForeignKey to <class 'playerteamstats.models.PlayerGameweekStats'>
class StatsInLine(admin.TabularInline):
model = MatchdayStats
class PlayerGameweekStatsAdmin(admin.ModelAdmin):
list_display = ('player', 'gameweek')
exclude = ('gameweek')
inlines = [
StatsInLine,
]
admin.site.register(PlayerGameweekStats, PlayerGameweekStatsAdmin)
To build TabularInline models need to be connected with ForeignKey.
From Django docs example:
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)
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,
]
In you case you need to have ForeignKey to PlayerGameweekStats in MatchdayStats.
Related
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
I am a newbie in Django. I have 3 models: Continent, Country, Region
Here is the code:
from django.db import models
# Create your models here.
class Continent(models.Model):
continent = models.CharField(max_length=50, unique=True)
class Meta:
ordering = ['continent']
def __str__(self):
return self.continent
class Country(models.Model):
country = models.CharField(max_length=50, unique=True)
continent = models.ForeignKey(Continent)
class Meta:
ordering = ['country']
verbose_name_plural = 'Countries'
def __str__(self):
return self.country
class Region(models.Model):
country = models.ForeignKey(Country)
region = models.CharField(max_length=50)
class Meta:
ordering = ['region']
def __str__(self):
return self.region
def get_continent(self):
return self.get_continent()
my admin.py looks like this:
from django.contrib import admin
from location.models import Continent, Country, Region
# Register your models here.
class MyAdmin1(admin.ModelAdmin):
list_display = ['continent']
#list_display_links = None
#actions = None
class MyAdmin2(admin.ModelAdmin):
list_display = ['country', 'continent']
class MyAdmin3(admin.ModelAdmin):
model = Region
list_display = ['region', 'country', 'get_continent']
admin.site.register(Continent, MyAdmin1)
admin.site.register(Country, MyAdmin2)
admin.site.register(Region, MyAdmin3)
But in admin panel when I click on table regions it doesn't show 3 attributes in 3 columns. Please, help.
You get a infinite recursion in the Region.get_continent() method:
class Region(models.Model):
...
def get_continent(self):
return self.get_continent()
Change it to:
def get_continent(self):
return self.country.continent
I have the following django model.
In the django admin model of TestCase table, in its list_display, i want to display the most recent comment and the modifier name of Remark table.
models.py
from django.db import models
class Release(models.Model):
title = models.CharField(max_length=128)
start_time = models.DateField('Release Start Date')
release_date = models.DateField('Release Ended Date')
def __str__(self):
return self.title
class TestCase(models.Model):
query = models.CharField(max_length=256)
ksq_id = models.IntegerField()
status = models.CharField(max_length=64)
release = models.ForeignKey(Release) # Release can have many test cases
def __str__(self):
return self.query
class Remark(models.Model):
owner = models.CharField(max_length=64)
module = models.CharField(max_length=64)
comment = models.CharField(max_length=1024)
modified_ts = models.DateTimeField('date modified', auto_now=True)
modifier = models.CharField(max_length=64)
testcase = models.ForeignKey(TestCase) # Testcase can have many Re
admin.py
from django.contrib import admin
from kramer_release.models import Release, TestCase, Remark
class RemarksInline(admin.TabularInline):
model = Remark
extra = 0
class RemarkAdmin(admin.ModelAdmin):
list_display = ('owner', 'module', 'testcase_query')
def testcase_query(self, obj):
return obj.testcase.query
class TestCaseAdmin(admin.ModelAdmin):
inlines = [RemarksInline]
list_display = ('query', 'status')
admin.site.register(Release)
admin.site.register(TestCase, TestCaseAdmin)
admin.site.register(Remark, RemarkAdmin)
You can defined a function to get the latest comment as part of you admin class, something like:
class TestCaseAdmin(admin.ModelAdmin):
inlines = [RemarksInline]
list_display = ('query', 'status', 'latest_comment')
def latest_comment(self, obj):
remarks = Remark.objects.filter(testcase=obj).order_by('-modified_ts')
if remarks:
return '%s - %s' % (remarks[0].comment, remarks[0].modifier)
return None
see the docs
I am working on multiple django sites and have been limited in making my project look nice for clients.
For example in the same app I have two models images and image galleries. It would be so much nicer to just have an admin entry for galleries and in that a table of images.
That's exactly what InlineModelAdmin is for. Taken a models.py like this:
class Gallery(models.Model):
name = models.CharField(max_length=100)
class Image(models.Model):
image = models.ImageField()
gallery = models.ForeignKey(Gallery)
You create an admin.py like this and only register an admin class for the Gallery:
class ImageInline(admin.TabularInline):
model = Image
class GalleryAdmin(admin.ModelAdmin):
inlines = [ImageInline]
admin.site.register(Gallery, GalleryAdmin)
This is my solution thanks to Dirk's help.
from django.db import models
PHOTO_PATH = 'media_gallery'
class Gallerys(models.Model):
title = models.CharField(max_length=30, help_text='Title of the image maximum 30 characters.')
slug = models.SlugField(unique_for_date='date', help_text='This is automatic, used in the URL.')
date = models.DateTimeField()
class Meta:
verbose_name_plural = "Image Galleries"
ordering = ('-date',)
def __unicode__(self):
return self.title
class Images(models.Model):
title = models.CharField(max_length=30, help_text='Title of the image maximum 30 characters.')
content = models.FileField(upload_to=PHOTO_PATH,blank=False, help_text='Ensure the image size is small and it\'s aspect ratio is 16:9.')
gallery = models.ForeignKey(Gallerys)
date = models.DateTimeField()
class Meta:
verbose_name_plural = "Images"
ordering = ('-date',)
def __unicode__(self):
return self.title
import models
from django.contrib import admin
class ImageInline(admin.TabularInline):
model = Images
class GallerysAdmin(admin.ModelAdmin):
list_display = ('title', 'date', 'slug')
inlines = [ImageInline]
admin.site.register(models.Gallerys,GallerysAdmin)
I am quite newbie in Django world. My question is I ve two models shown below. It works quite well with Grapelli and inline-sortables. Only problem is whenever I add a new foreign key for "equipment" or "image type" fields. They don't show up in the drop down menu of newly added inline rows. I went through internet but couldn't find a smilar problem and a solution.
I would appreciate some help with this.
My model is:
from django.db import models
from datetime import datetime
from thumbs import ImageWithThumbsField
from positions.fields import PositionField
class Artist(models.Model):
name = models.CharField(max_length=55)
def __unicode__(self):
return self.name
class ImageType(models.Model):
name = models.CharField(max_length=55)
def __unicode__(self):
return self.name
class Equipment(models.Model):
name = models.CharField(max_length=55)
def __unicode__(self):
return self.name
class Image(models.Model):
name = models.CharField(max_length=255)
image_file = models.ImageField(upload_to = "images/%Y-%m-%d")
Image_Type = models.ForeignKey(ImageType)
upload_date = models.DateTimeField('date_published',default=datetime.now)
artist = models.ForeignKey(Artist)
equipment = models.ForeignKey(Equipment)
order = PositionField(collection='artist')
def __unicode__(self):
return self.name
class Meta:
ordering = ['order']
And My admin.py is:
from gallery.models import Image,ImageType,Artist,Equipment
from django.contrib import admin
class ImageUploadAdmin(admin.ModelAdmin):
fields = ['name','artist','equipment','image_file','Image_Type','upload_date']
list_filter = ['upload_date']
date_hierarchy = 'upload_date'
class ImageInline(admin.TabularInline):
model = Image
list_display = ('name','equipment','image_file','Image_Type','upload_date')
sortable_field_name = "order"
exclude = ('upload_date',)
extra = 0
class ArtistAdmin(admin.ModelAdmin):
inlines = [
ImageInline,
]
admin.site.register(Artist,ArtistAdmin)
admin.site.register(Image, ImageUploadAdmin)
admin.site.register(ImageType)
admin.site.register(Equipment)