Why my model field is getting prepopulated in admin? - django

I have created a model as below.
class UserPost(models.Model):
author = models.ForeignKey(User, related_name='userpost', null=True, on_delete=models.CASCADE)
post_date = models.DateTimeField(auto_now_add=True)
title = models.CharField(max_length=150, blank=False)
post_body = models.TextField(blank=True, null=True, default='text')
image = models.ImageField(upload_to='post_pics', blank=True)
likes = models.ManyToManyField(User, blank=True, related_name='post_likes')
I am not populating likes field anywhere, my admin screenshot is below.Why my likes field is getting populated with all the users created?
admin screenshot
admin.py
from django.contrib import admin
from feed.models import UserPost
# Register your models here.
admin.site.register(UserPost)
Edit 1:
Adding a screenshot for Rishabh's answer.
trying to add user from left as suggested by him

You are using ManyToManyField of Django which will show you all records of User table left side and you can add them by double clicking on them or by clicking '+' sign, so your likes field is not prepopulated at all it is just showing User table data.

Related

How to hide fields that belong to the model I'm inheriting from in django admin panel

I have these 2 models in my models.py
class Student(AbstractBaseUser):
date_of_birth = models.DateField(null=True)
phone_number = PhoneNumberField(null=True)
class Teacher(Student):
bio = models.TextField(null=True)
image = CompressedImageField(null=True, blank=True, default="default.png")
student = models.ForeignKey(Student, on_delete=models.SET_NULL, null=True)
Now in admin panel when i go to edit the Teacher instance I display only bio image and student. The issue is that also display those fields when I try to edit Teacher instance but entering from Student model. So is there a way for that?
P.S the models and fields may not make sense because they are examples.
Use ModelAdmin.fields or ModelAdmin.exclude to control which fields you want to include or exclude in the admin site form.
from django.contrib import admin
class TeacherAdmin(admin.ModelAdmin):
exclude = ("date_of_birth", "phone_number")
And register it like so
admin.site.register(Teacher, TeacherAdmin)

Django: model does not render fields correctly in Admin

I've a model that I know is recording correctly the values in DataBase, but it is not showing them correctly in Admin Panel.
I know it's saving this fields correctly because:
1.- I can Query the model in Shell and see the values correctly.
2.- I'm using this model's fields to create another model, and this other model saves correctly and SHOWs correctly it's fields in Admin Panel.
What could be wrong?
Shell:
>>> SizeQuantity.objects.get(pk=9)
<SizeQuantity: variante_125 por cantidad_200>
>>> SizeQuantity.objects.get(pk=9).size
'variante_125'
>>> SizeQuantity.objects.get(pk=9).quantity
'cantidad_200'
What I see in AdminPanel:
This is my other model that uses values from SizeQuantiy:
I was expecting to render the Size and Quantity fields like this for my SizeQuantity model:
from .models import Cart, SizeQuantity
# Register your models here.
admin.site.register(Cart)
admin.site.register(SizeQuantity)
models.py:
class SizeQuantity(models.Model):
cart = models.ForeignKey(Cart, on_delete=models.CASCADE)
product = models.ForeignKey(Product, on_delete=models.CASCADE)
size = models.CharField(max_length=20, choices=TAMANIOS)
quantity = models.CharField(max_length=20, choices=CANTIDADES)
image = models.ImageField(upload_to='images', blank=True, null=True)
comment = models.CharField(max_length=200, blank=True, null=True, default='')
uploaded_at = models.DateTimeField(auto_now_add=True)
def __str__(self):
return str(self.id) + " - " + str(self.size) + " por " + str(self.quantity)
#property
def image_filename(self):
return self.image.url.split('/')[-1]
Probably Django can't render your fields correctly because mentioned values are not included in fields choices (TAMANIOS CANTIDADES)
Your field above ('variante_125', 'cantidad_200') is not in your valid CHOICES.
You can add any char for size and quantity fields although you don't write the values in CHOICES. But you can't use the choices such as get_FOO_display. It's helpful to check docs here (https://docs.djangoproject.com/en/2.1/ref/models/fields/#choices).
You should check TAMANIOS, CANTIDADES choices that have those values.

How to link two models, each with its own template using foreignKey in Django

I want to link two models using foreignKey, The problem is when i try to do that, one model does not get foreignKey value for the next model in the database table.
The aim is for user to fill information on the first page (have its own model and template) then click next (fill more info in the next page having its own model and template) then click next for the same logic. then when other users view this post it must show all content from different models in one page. here is my code.
1st model
class Map(models.Model):
user = models.ForeignKey(User, default=None, blank=True, null=True, on_delete=models.CASCADE)
name = models.CharField(max_length=100)
position = GeopositionField()
HAVING ITS OWN TEMPLATE
2nd Model
class Post(models.Model):
parent = models.ForeignKey("self", default=None, blank=True, null=True, on_delete=models.CASCADE)
user = models.ForeignKey(settings.AUTH_USER_MODEL, default=None, on_delete=models.CASCADE)
title = models.CharField(max_length=50)
content = models.TextField()
map = models.ForeignKey(Map, related_name='mapkey', default=None, blank=True, null=True, on_delete=models.CASCADE)
HAVING ITS OWN TEMPLATE BUT also has serializer method(API) below:
class PostModelSerializer(serializers.ModelSerializer):
user = UserDisplaySerializer(read_only=True)
parent = ParentPostModelSerializer()
map = serializers.SerializerMethodField()
class Meta:
start_date = forms.DateField(widget = forms.SelectDateWidget())
end_date = forms.DateField(widget = forms.SelectDateWidget())
model = Post
fields = [
'id',
'user',
'title',
'content'
'image',
'map',
]
Please focus only on the map field as its isolated in the above codes
everything works perfectly, but the foreignKey. also i didnt see the need to include all the code here but snippets.
i have been struggling with this for days now. do i need to write an api for 1st model also? for views i used class based views.
the database table for model 2, on the map field it shows null all the time.
I have i have provided enough information.Thanks

Django 1.11 many to many does not appear in django admin

Hi i have a django model for notification which have a many-to-many relation but nothing appears in django admin ( all fields do not appear)
class Notification(models.Model):
"""send notification model"""
title = models.CharField(max_length=200)
text = models.TextField(null=True, blank=True)
device = models.ManyToManyField(Device, null=True, blank=True)
country = models.ManyToManyField(Country, null=True, blank=True)
sent = models.BooleanField(default=False)
when i open django admin for this model and press add notification this is what happens (nothing appears)
Country and Device Code
class Device(models.Model):
"""Store device related to :model:`accounts.User`."""
user = models.OneToOneField(User, related_name='device', on_delete=models.CASCADE)
model = models.CharField(max_length=200, blank=True, null=True)
player_id = models.CharField(max_length=200, blank=True, null=True)
class Meta:
verbose_name = 'Device'
verbose_name_plural = 'Devices'
def __str__(self):
return self.model
class Country(models.Model):
name = models.CharField(max_length=255)
def __str__(self):
return self.name
Admin.py
from django.contrib import admin
from .models import Notification
admin.site.register(Notification)
Edit:
Thank you all the problem is solved
The problem was caused by some entries in device model that did have None in the model field so there was a problem displaying it correctly.
According to https://code.djangoproject.com/ticket/2169 :
When a class has a field that isn't shown in the admin interface but
must not be blank, it's impossible to add a new one. You get a cryptic
"Please correct the error below." message with no shown errors. The
error message should probably say something about a hidden field.
Now ManyToManyFields don't need null=True, try removing those statements and see if you get an improvement.
Also, try adding the Country and Device models in admin.py so admin can see them and display them.
https://docs.djangoproject.com/en/1.11/ref/contrib/admin/#working-with-many-to-many-models
Define an inline for the many-to-manys in admin.py:
from django.contrib import admin
class DeviceInline(admin.TabularInline):
model = Notification.device.through
class CountryInline(admin.TabularInline):
model = Notification.country.through
class NotificationAdmin(admin.ModelAdmin):
inlines = [
DeviceInline, CountryInline
]
exclude = ("device", "country")

Why is a Django model taking so long to load in admin?

I have a fairly simple Django set up for a forum, and one of the most basic models is this, for each thread:
class Post(models.Model):
created = models.DateTimeField(auto_now_add=True)
last_reply = models.DateTimeField(auto_now_add=True, blank=True, null=True)
username = models.ForeignKey(User, related_name="forumuser")
fixed = models.BooleanField(_("Sticky"), default=False)
closed = models.BooleanField(default=False)
markdown_enabled = models.BooleanField(default=False)
reply_count = models.IntegerField(default=0)
title = models.CharField(_("Title Post"), max_length=255)
content = models.TextField(_("Content"), blank=False)
rating = models.IntegerField(default=0)
followers = models.IntegerField(default=0)
ip_address = models.CharField(max_length=255)
def __unicode__(self):
return self.title
def get_absolute_url(self):
return "/post/%s/" % self.id
Then we have some replies:
class PostReply(models.Model):
user = models.ForeignKey(User, related_name='replyuser')
post = models.ForeignKey(Post, related_name='replypost')
created = models.DateTimeField(auto_now_add=True)
content = models.TextField()
ip_address = models.CharField(max_length=255)
quoted_post = models.ForeignKey('self', related_name='quotedreply', blank=True, null=True)
rating = models.IntegerField(default=0)
reply_order = models.IntegerField(default=1)
Now, currently there just over 1600 users, 6000 Posts, and 330,000 PostReply objects in the db for this setup. When I run this SQL query:
SELECT * FROM `forum_post` LIMIT 10000
I see that Query took 0.0241 sec which is fine. When I browse to the Django admin section of my site, pulling up an individual Post is rapid, as is the paginated list of Posts.
However, if I try and pull up an individual PostReply, it takes around 2-3 minutes to load.
Obviously each PostReply admin page will have a dropdown list of all the Posts in it, but can anyone tell me why this or anything else would cause such a dramatically slow query? It's worth noting that the forum itself is pretty fast.
Also, if it is something to do with that dropdown list, has anyone got any suggestions for making that more usable?
Try to add all foreign keys in raw_id_fields in admin
class PostReplyAdmin(ModelAdmin):
raw_id_fields = ['user', 'post', 'quoted_post']
This will decrease page's load time in change view. The problem is that django loads ForeignModel.objects.all() for each foreign key's dropdowns.
Another way is to add foreign keys in autocomplete_fields (docs) in admin
class PostReplyAdmin(ModelAdmin):
autocomplete_fields = ['user', 'post', 'quoted_post']
As pointed by #Andrey Nelubin the problem for me was indeed in the page loading all related models for each foreign key's dropdown. However, with autocomplete_fields selects are turned into autocomplete inputs (see figure below), which load options asynchronously.