How to change the name of objects in Django admin? - python

What to do? I kept restarting my server but it still didn't work. This is the whole code snippet of my models.py:
from django.db import models
class Blog(models.Model):
title = models.CharField(max_length=50)
pub_date = models.DateField(auto_now_add=True)
# publication date
image = models.ImageField(upload_to='images/')
summary = models.CharField(max_length=200)
body = models.TextField()
def __str__(self):
return self.title
But the names of each objects are still not changing:

Put the method inside the Blog Model as following:
models.py
from django.db import models
class Blog(models.Model):
def __str__(self):
return self.title

Your def str(self) is not indented inside your model class. Make the changes and it will work.
class modelClass(models.Model):
#your properties
#below method should be indented
def __str__(self):
return self.property

Could you try below?
class Blog(models.Model):
........
def __str__(self):
return str(self.title)

Related

When I define a custom manager .. Error:Manager isn't accessible via Post instances

I defined a custom manager inheriting models. Manager put in in my model 'Post'.
The error says that you cant call manager through a instance but i have not called it through a instance it works fine when i remove the custom manager.
models.py:
class PublishedManager(models.Manager):
def get_queryset(self):
return super().get_queryset().filter(status='Published')
class Post(models.Model):
STATUS_CHOICES = [
('draft','Draft'), ('published','Published'),
]
id = models.UUIDField(primary_key=True,default=uuid.uuid4,editable=False)
title = models.CharField(max_length=200)
slug = models.SlugField(max_length=200)
created = models.DateTimeField(auto_now_add=True)
published = models.DateTimeField(default=timezone.now)
updated = models.DateTimeField(auto_now=True)
status = models.CharField(max_length=10,choices=STATUS_CHOICES,default='Published')
author = models.ForeignKey(CustomUser,on_delete=models.CASCADE)
body = models.TextField()
objects = models.Manager()
published = PublishedManager()
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse("detail", kwargs={"slug":self.slug,"id": self.id})
views.py:
class PostListView(ListView):
model = Post
template_name = 'blog/index.html'
context_object_name='posts'
Error image
I think you cannot have a manager named the same as the field of a Model. Try to rename it to something like published_objects.
The error occurs when you try to access post.published (a field) but Django thinks you want to access a manager, hence the error.

Name issue. Can't change the name of the Models in django database

from django.db import models
# Create your models here.
class Course (models.Model):
name = models.CharField(max_length=100)
language= models.CharField(max_length=100)
price= models.CharField(max_length=100)
def __str__(self):
return self.name
in django database the object dosent change name still named Course object (1) in the list. Why does it not change? def str(self):
return self.name
what should one do to make django show the courses names? This should be correct. no errors or anything it just simply dosent do what it should. it seems strange.
The __str__ function should be in your class, not after it
class Course(models.Model):
name = models.CharField(max_length=100)
language = models.CharField(max_length=100)
price = models.CharField(max_length=100)
def __str__(self):
return self.name
class Course(models.Model):
name = models.CharField(max_length=100)
language= models.CharField(max_length=100)
price= models.CharField(max_length=100)
def __str__(self):
return self.name
i got answer for this so you have to add this in respective modules like i have category module in which models.py and then add this method.

Reorganizing ManyToMany models into a different order

I have an setup similar to this.
class Author(models.Model):
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=40)
books = models.ManyToManyField(Book)
def __unicode__(self):
return self.title
class Book(models.Model):
title = models.CharField(max_length=100)
author = models.ForeignKey(Author)
def __unicode__(self):
return self.title
Now in my admin panel I can select an author and add Books underneath that specific author. When I print out all the books for each author it prints them in the order that they were added in the admin panel.
Is it possible to modify the order in the admin panel so that when they print, they print in the order of the admin panel?
admin.py
#admin.register(Author)
class AuthorAdmin(admin.ModelAdmin):
pass
#admin.register(Book)
class BookAdmin(admin.ModelAdmin):
pass
You can add inside every model a class Meta with ordering atribute, to get items in a certain order.
class Book(models.Model):
...
class Meta:
ordering = ['author']
Maybe it helps you.
as i understand you use TabularInline for books if that's right so you just need to make simple function called get_queryset
def get_queryset(self, request):
return super(BookInlineAdmin, self).get_queryset(request).order_by('YOURFIELD')

Django Admin showing Object - not working with __unicode__ OR __str__

my Django admin panel is showing object instead of self.name of the object.
I went through several similar questions here yet couldn't seem to resolve this issue. __unicode__ and __str__ bear the same results, both for books and for authors. I've changed those lines and added new authors/books in every change but no change.
MODELS.PY
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class Author(models.Model):
name = models.CharField(max_length=100)
def __str__(self):
return self.name
class Book(models.Model):
auto_increment_id = models.AutoField(primary_key=True)
name = models.CharField('Book name', max_length=100)
author = models.ForeignKey(Author, blank=False, null=False)
contents = models.TextField('Contents', blank=False, null=False)
def __unicode__(self):
return self.name
I used both unicode & str interchangeably, same result.
Here are the screenshots of the admin panel by menu/action.
1st screen
Author List
Single Author
Your indentation is incorrect. You need to indent the code to make it a method of your model. It should be:
class Author(models.Model):
name = models.CharField(max_length=100)
def __str__(self):
return self.name
If you are using Python 3, use __str__. If you are using Python 2, use __unicode__, or decorate your class with the python_2_unicode_compatible decorator. After changing the code, make sure you restart the server so that code changes take effect.

Django model references from a different model

I'm writing a method in a model and I need to access an attribute from another model.
from django.db import models
class Image(models.Model):
name = models.CharField(max_length=30)
image = models.ImageField(upload_to = slug_path)
def __str__(self):
return "%s %s" % (self.first_name, self.last_name)
def slug_path(self):
# Need Article.slug from Article class here for constructing path
pass
class Article(models.Model):
headline = models.CharField(max_length=100)
pub_date = models.DateField()
reporter = models.ForeignKey(Reporter, on_delete=models.CASCADE)
slug = models.SlugField(max_length=50)
def __str__(self):
return self.headline
I want to write a method in the Image class that will have access to the slug of the Article it is included in via the one to many relation. Is this possible or is there a different way I should be going about this entirely?
Say if only one image can be related to one article, you need to add a field article in the image model which would be foreign key to Article model
article = models.ForeignKey(Article)
Now,
def slug_path(self):
slug = self.article.slug
return slug
Anyway, you can do it in a similar way for many to many fields etc.
Add a relationship to Image corresponding to the Article object, like you did with Article and Reporter.
article = models.ForeignKey(Article, on_delete=models.CASCADE)
Then to get/return the slug:
def slug_path(self):
return self.article.slug

Categories