Django Model Class Missing in Admin - python

For some reason, the classes archive and album show all of their fields in the django admin panel, but image isn't showing an album field when I go to add an image to the image panel. If I open a shell, it shows that album is a subset of image, it just isn't showing up in the image's admin interface (but it does through the CLI). Why?
class archive(models.Model):
name = models.CharField(max_length = 30)
archivedata = models.TextField(blank=True, help_text="Documentation for album/image.archivedata methodology is put here")
def __unicode__(self):
return self.name
class tag(models.Model):
archive = models.ForeignKey(archive)
tag = models.CharField(max_length=60)
def __unicode__(self):
return self.tag
class album(models.Model):
archive = models.ForeignKey(archive)
title = models.CharField(max_length=60)
tags = models.ManyToManyField(tag, blank=True, help_text="Searchable Keywords")
archivedata = models.TextField(blank=True, null=True, help_text="Data specific to particular archiving methods or processes can be stored here")
def __unicode__(self):
return self.title
class image(models.Model):
album = models.ForeignKey(album)
archive = models.ForeignKey(archive)
imagefile = models.ImageField(upload_to='ns/') #image.width/height
title = models.CharField(max_length=60, blank=True, help_text="Descriptive image title")
tags = models.ManyToManyField(tag, blank=True, help_text="Searchable Keywords")
Update: Including my admin.py per request:
from django.db.models import get_models, get_app
from django.contrib import admin
from django.contrib.admin.sites import AlreadyRegistered
def autoregister(*app_list):
for app_name in app_list:
app_models = get_app(app_name)
for model in get_models(app_models):
try:
admin.site.register(model)
except AlreadyRegistered:
pass
autoregister('appname')

Your admin.py file should typically look like this.
from django.contrib import admin
admin.site.register(archive)
admin.site.register(album)
admin.site.register(image)
Based on your admin.py I would do this.
autoregister('archive', 'album', 'image')
That said a few pointers - Your admin.py is a bit overly complicated and not needed when 3 lines will suffice. Additionally you should be naming your models in uppercase (Archive, Album, Image)

I do not see any problem do you have some extra code in admin? Some code that overrides the album field ?

Related

How to use reporting and statistics capabilities for blog post using django

models.py
from django.db import models
from django.contrib.auth.models import User
STATUS = (
(0,"Draft"),
(1,"Publish")
)
class BlogModel(models.Model):
id = models.AutoField(primary_key=True)
blog_title = models.CharField(max_length=200)
blog = models.TextField()
status = models.IntegerField(choices=STATUS, default=0)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
class Meta:
ordering = ['-created_at']
def __str__(self):
return f"Blog: {self.blog_title}"
class CommentModel(models.Model):
your_name = models.CharField(max_length=20)
comment_text = models.TextField()
created_at = models.DateTimeField(auto_now_add=True)
blog = models.ForeignKey('BlogModel', on_delete=models.CASCADE)
class Meta:
ordering = ['-created_at']
def __str__(self):
return f"Comment by Name: {self.your_name}"
admin.py
from django.contrib import admin
from blog.models import BlogModel,CommentModel
class PostAdmin(admin.ModelAdmin):
list_display = ('blog_title', 'status','created_at','updated_at')
list_filter = ('status',)
search_fields = ('blog_title', 'content',)
admin.site.register(BlogModel, PostAdmin)
admin.site.register(CommentModel)
I created a simple blog post website with comments and I want to create reports and on the admin panel I have to see how to achieve this.
Like how many posts are created and how many have comments and how many post are draft and published
I checked this module but I don't understand how to implement it https://pypi.org/project/django-reports-admin/
You already have most of this, by using PostAdmin. The list_display already shows you how many posts are published/draft, and the change list has filters for that as well.
To show the comment count, simply add that to list_display:
class PostAdmin(admin.ModelAdmin):
list_display = ('blog_title', 'status', 'comment_count', 'created_at', 'updated_at')
def comment_count(self, obj):
return obj.commentmodel_set.count()
comment_count.short_description = 'Comment count'
This thus defines a custom method on the PostAdmin, that displays the comment count as a column, and gives it a user-friendly name as column header.
You can expand this with more statistics if you like. The Django admin is highly customizable.
Note: model names should be in CamelCase, so BlogModel and CommentModel should be Blog and Comment respectively.

How can I display the contents of a related table within the Django admin change form?

I'm new to programming, Python, and Django, so your patience is appreciated. I have been writing a practice application in Django for storing cooking recipes. I have two models:
class Recipe(models.Model):
recipe_name = models.CharField(max_length=30)
recipe_instructions = models.TextField()
recipe_whyitworks = models.TextField(verbose_name="Why It Works")
recipe_date = models.DateField()
def __str__(self):
return self.recipe_name
def was_published_recently(self):
return self.recipe_date >= timezone.now() -datetime.timedelta(days=5)
class Ingredient(models.Model):
recipe = models.ForeignKey(Recipe, on_delete=models.CASCADE)
ingredient_name = models.CharField(max_length=30)
ingredient_qty = models.DecimalField(verbose_name='Quantity', max_digits=3, decimal_places=2)
ingredient_uom = models.CharField(verbose_name='Unit of Measure', max_length=15)
def __str__(self):
return self.ingredient_name
I have admin set to be able to edit either table:
from django.contrib import admin
# Register your models here.
from .models import Recipe, Ingredient
admin.site.register(Recipe)
admin.site.register(Ingredient)
What I want to do is when I click on an "Ingredient" I would like it to show all previous ingredients added to the recipe, along with the quantity and unit of measure for each in a table, in addition to the fields which allow me to add a new one. Thanks in advance for your help!
You can add inlines like this:
admin.py
from django.contrib import admin
class IngredientInline(admin.TabularInline):
model = Ingredient
class RecipeAdmin(admin.ModelAdmin):
inlines = [
IngredientInline,
]
admin.site.register(Recipe, RecipeAdmin)
admin.site.register(Ingredient)

Wagtail Django group pictures into albums based on their tags

I was wondering if it's possible to arrange pictures uploaded to wagtail into galleries based on their tags.
I have an album app, and its models.py contains :
from django.db import models
from wagtail.wagtailcore.models import Page
# Create your models here.
class Category(Page):
name = models.CharField(max_length=250)
slug = models.SlugField()
image = models.ImageField()
parent = models.ForeignKey('self', blank=True, null=True, related_name='children')
def __str__(self):
return self.name
class Post(Page):
title = models.CharField(max_length=120)
category = models.ForeignKey('Category', null=True, blank=True)
publish = models.DateField(auto_now=False, auto_now_add=False, )
slug = models.SlugField(unique=True)
Images use django-taggit for its tags so you can query them easily.
from wagtail.wagtailimages import get_image_model
# Somewhere in your code
image_class = get_image_model()
images = image_class.objects.filter(tags__name='the_slug')
On a side note, the slug field on your Category page in your snippet might shadow the slug field of the base Page model so you might want to be careful with that.

Having admin inline for model without direct relation or foreign key

So, I have this these model:
class Media(models.Model):
title = models.CharField(max_length=50, blank=True)
slug = models.SlugField(max_length=70, blank=True, editable=False)
class Meta:
abstract = True
class Photo(Media):
source = models.ImageField(upload_to='uploads/gallery/photo')
class Video(Media):
source = models.FileField(upload_to='uploads/gallery/photo')
class Item(models.Model):
content_type = models.ForeignKey(
ContentType,
limit_choices_to={'model__in': ['photo', ]},
on_delete=models.CASCADE,
)
object_id = models.PositiveIntegerField()
content_object = GenericForeignKey('content_type', 'object_id')
class Album(Media):
items = models.ManyToManyField(Item)
How can I have an album admin with photo and video as inline so i can upload photo and video when i created an album ?
When I tried making inline for photo and hook it to album admin, I get error "photo has no foreignkey to album", pretty obvious, from there I think there should be a way to link foreignkey needed by album admin with content object from model item.
Note: I specifically doesn't want an item admin. An item are created at model post save signals.
I do not think this works out of the box. But you can use libraries like eg django-smart-selects-generics. Depending on your django version you might need to update some files there.
Installation works with:
pip install django-smart-selects-generic
You also need to have django-smart-selects installed.
Then add both apps in the settings.
INSTALLED_APPS = (
...
'smart_selects',
'smart_generic'
)
And then in your admin.py you can do:
from smart_generic.form_fields import GenericChainedModelChoiceField
from django.forms.models import ModelForm
class TForm(ModelForm):
object_id = GenericChainedModelChoiceField('content_type','content_type',label=u'Content object',queryset=TargetRelation.objects.all())
class Meta:
model = TargetRelation
fields = ['target','content_type']
class TRAdmin(admin.ModelAdmin):
form = TForm
class TRInline(admin.TabularInline):
model = TargetRelation
form = TForm
class PlanetAdmin(admin.ModelAdmin):
inlines=[TRInline,]
Depending on your django version you might need to replace in widgets.py:
Media = ChainedSelect.Media
by
.media = ChainedSelect.Media
And in smart_select views.py add:
import json as simplejson
and replace the return statement by:
return HttpResponse(json, content_type='application/json')

django admin fails using TabularInline

I built a simple django application and now have a really confusing error message. I think it's because of Tabularinline, but I use it properly according to this documentation.
models.py
from django.db import models
class Person(models.Model):
company = models.CharField(max_length=120)
name = models.CharField(max_length=120)
birthday = models.DateField(null=True, blank=True)
def __unicode__(self):
return self.name
class Note(models.Model):
person = models.ForeignKey(Person)
datetime = models.DateTimeField()
text = models.TextField()
admin.py
from addressbook.models import Person, Note
from django.contrib import admin
class NoteInline(admin.TabularInline):
model = Note
class PersonAdmin(admin.ModelAdmin):
model = Person
inlines = [NoteInline, ]
admin.site.register(Note, NoteInline)
admin.site.register(Person, PersonAdmin)
But I always get this error message:
<class 'addressbook.admin.NoteInline'>: (admin.E202) 'addressbook.Note' has no ForeignKey to 'addressbook.Note'.
Which I would understand but why should have Note a reference to itself If I am using it from Person?
I don't think you need to separately register the NoteInline admin template. Just register the PersonAdmin template and that should include your NoteInline

Categories

Resources