Autofield column is not showing in admin database - django

i have created a model Post
class Post(models.Model):
id = models.AutoField(primary_key=True)
title = models.CharField(max_length=100)
image = models.ImageField(upload_to='blog_image', default='default.jpg')
smallContent = models.TextField()
content = models.TextField()
data_posted = models.DateTimeField(default=timezone.now)
author = models.ForeignKey(User, on_delete=models.CASCADE)
def __str__(self):
return self.title
but id field is not showing in admin panel. i did makemigrations and migrate and both are done successfully.

AutoField is generated after the model is saved. It is not provided in Admin Panel as it should not be editable.
If want to make id editable (not recommended) override it as a CharField instead of AutoField with primary_key=True.
Else if just want to show it in the panel (while editing a saved model), add it to the read_only list of your model admin.
Read about AutoField here.

Since it is a readonly field I think you probably need to explicitly tell admin to show it.
I don't know if this will work but try in admin.py
from django.contrib import admin
from .models import Post
class PostAdmin(admin.ModelAdmin):
readonly_fields = ['display_id']
def display_id(self, obj):
return obj.id
admin.site.register(Post, PostAdmin)

Related

Django - How to only allow staff users to see their own posts in admin panel

I have a model called listings and I want staff users to only be able to view, edit, delete listings in the admin panel that they created. Currently staff users can view edit and delete all of the listings
here is my listings/admin.py
from django.contrib import admin
from .models import Listing
class ListingAdmin(admin.ModelAdmin):
list_display =('id','Full_Name','Is_Published','Town_Or_City','District','Region','List_Date')
list_display_links = ('id','Full_Name')
list_editable = ('Is_Published',)
search_fields = ('Full_Name','Town_Or_City','District','Region',)
admin.site.register(Listing, ListingAdmin)
here is my listings/models.py
from django.db import models
from datetime import datetime
from FuneralHomes.models import FuneralHome
class Listing(models.Model):
index = models.ForeignKey(index, on_delete=models.DO_NOTHING,blank=True)
Full_Name = models.CharField(max_length=200)
First_Name = models.CharField(max_length=200)
Last_Name = models.CharField(max_length=200)
Nee = models.CharField(max_length=200, blank=True)
Town_Or_City = models.CharField(max_length=200)
District = models.CharField(max_length=200, blank=True)
Region = models.CharField(max_length=200)
List_Date = models.DateField(max_length=200)
Photo = models.ImageField(upload_to='photos/%Y/%m/%d', blank=True)
Is_Published = models.BooleanField(default=True)
List_Date = models.DateTimeField(default=datetime.now, blank=True)
def __str__(self):
return self.Full_Name
The admin panel really isn't the place for things like this (as explained in the first paragraph of the Django documentation).
A quick a dirty way of accomplishing what you're trying to do is probably overriding the delete method for this model to check if the user created it. For only listing the user's posts you could utilize the Manager class. Finally, to handle editing, you would have to override the save method to see if it already exists and if the user created it.
you can override get_queryset function and just filter listings related to that user , in this case user can only see his listings .
class ListingAdmin(admin.ModelAdmin):
def get_queryset (self, request):
return Listing.objects.filter(listing_user = request.user)

Display fields from one model in another in Django Admin connected with a Foreignkey

I have two models, one for uploaded files and one for comments. I now want to display the comments in the Admin view of each uploaded file. So for example, if I upload a file TestFile1, once I click on it in the
Uploaded view in Django admin, I want to have all of the comments associated with that file. Is this possible?
class Uploaded(models.Model):
objects: models.Manager()
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="users")
file = models.FileField(upload_to=user_directory_path)
def __str__(self):
return f"{self.description} {self.file}"
class Comment(models.Model):
objects: models.Manager()
file = models.ForeignKey('Uploaded', on_delete=models.CASCADE, related_name='comments')
text = models.TextField()
def __str__(self):
return self.text
Yes, what you need is to write InlineModelAdmin for your models.
In your case, that would be something like:
from django.contrib import admin
class CommentInlineAdmin(admin.TabularInline):
model = Comment
class UploadedAdmin(admin.ModelAdmin):
inlines = [CommentInlineAdmin]
admin.register(Uploaded, UploadedAdmin)

django admin inline has no foreign key relation

I have a model like:
class Category(models.Model):
name = models.CharField(max_length=100)
description = models.TextField()
thumbnail = models.ForeignKey(MediaFile)
def __unicode__(self):
return self.name
Here I have thumbnail foreign key to MediaFile.
I want to have Inline of Category model.
I have done this :
class MediaInline(admin.StackedInline):
model = MediaFile
extra = 0
max_num=0
class CategoryAdmin(admin.ModelAdmin):
list_display = ('name',)
inlines = [ MediaInline, ]
admin.site.register(Category, CategoryAdmin)
Its not happening.. Here I am assuming to have MediaFile Inline to Category . What is wrong in here ?
Your foreign key is the wrong way round. If you want multiple mediafiles in one category, the fk needs to live on the MediaFile model. That way the inline will work.
You cannot set inlines this way because Category instance will be saved before MediaFile. Yet, Django wouldn't be able to set Category.thumbnail while MediaFile is not saved.
You should rather have a CategoryInline in MediaFileAdmin for instance.

Many-To-Many Fields View on Django Admin

Basically I am trying to recreate a fields in this model that is similar to django user authenticate system, for this I try using many-to-many fields but it ended up like this.
I am trying to have another field that can show what exist and another field for I have chosen similar to django admin, which looks like this.
This is my code
class Category(models.Model):
name = models.CharField(max_length=128, unique=True)
class BlogPage(models.Model):
category = models.ManyToManyField(Category)
title = models.CharField(max_length=128)
preview = models.TextField(max_length=256)
content = models.TextField()
I believe what you want is a filter_horizontal widget used in the Admin template. This should help: Django Admin ManyToManyField
currently i am able to display many to many fields is admin panel
models.py
class Abc(models.Model):
course = models.ManyToManyField(Course, blank=True)
admin.py
class AbcsAdmin(admin.ModelAdmin):
"""
Admin panel management for Alumni
"""
list_display = ["id","get_course"]
def get_course(self,obj):
return [course.name for course in obj.course.all()]

How can I let a user to post several images to one model?

I have one listing model :
class Listing(models.Model):
owner = models.ForeignKey(User, verbose_name=_('offerer'))
title = models.CharField(_('Title'), max_length=255)
slug = models.CharField(editable=False, max_length=255)
price = models.PositiveIntegerField(_("Price"), null=True, blank=True)
description = models.TextField(_('Description'))
time = models.DateTimeField(_('Created time'),
default = datetime.now,
editable = False
)
Then I have one ListingImage, which holds the pictures of the listing:
from photologue.models import ImageModel
class ListingImage(ImageModel):
pictures = models.ForeignKey(Listing, related_name="images")
forms.py
class ListingForm(forms.ModelForm):
class Meta:
model = Listing
exclude = ('owner',)
def __init__(self, *args, **kwargs):
super(ListingForm, self).__init__(*args, **kwargs)
Why in the upload page , there is no field to upload a picture??
ListingImage has a ForeignKey to Listing, so a ModelForm for Listing has nothing to do with ListingImage.
You shouldn't be expecting a ModelForm for the Listing model to show you anything but the Listing model. ListingImage is a reverse relationship to the Listing model.
If this was a ModelAdmin, you'd get the admin site to show you these reverse relationships by defining inlines:
http://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.InlineModelAdmin
Since it doesn't look like you're talking about the admin panel, you're looking at InlineModelFormsets: http://docs.djangoproject.com/en/dev/topics/forms/modelforms/#using-an-inline-formset-in-a-view
Also, you could show us your views so that we can see the whole picture.