开发者

Django can't display model.id in change form?

开发者 https://www.devze.com 2023-02-25 11:05 出处:网络
I have a model Post whose data I would like to display in model Favorite\'s Admin. Post model: class Post(models.Model):

I have a model Post whose data I would like to display in model Favorite's Admin.

Post model:

class Post(models.Model):
    nickname = models.CharField(max_length=50, default="anonymous")

    def __unicode__(self):
        return self.id

Favorite model:

class Favorite(models.Model):
    us开发者_高级运维er = models.ForeignKey(User, unique=False)
    post = models.ForeignKey(Post, unique=False)

    def __unicode__(self):
        return self.user.username

    def get_post_nickname(self):
        return self.post.nickname

Favorite Admin:

class FavoriteAdmin(admin.ModelAdmin):
    #fields = ('user', 'get_post_nickname')
    list_display= ('user', 'post')

    def save_model(self, request, obj, form, change):
        obj.save()

admin.site.register(Favorite, FavoriteAdmin)
  1. If I use the code as such, when I try to add a Favorite through its Admin I get the following error:

    Caught TypeError while rendering: coercing to Unicode: need string or buffer, int found

  2. OK so it doesn't like to display an Integer, so I thought I'll just display the nickname since its a Charfield. I uncommented the first line in FavoriteAdmin() to call FavoriteModel.get_post_nickname(). Now I get the following error:

'FavoriteAdmin.fields' refers to field 'get_post' that is missing from the form.

How can I solve both #1 and #2? Is it not possible to call a method in fields()? I thought it would be since list_display() accepts a method.


  1. I usually do this:

    class Post(models.Model):
        nickname = models.CharField(max_length=50, default="anonymous")
    
        def __unicode__(self):
            return u"%s" % self.id
    
  2. Fields (docs) is how to control the layout of admin "add" and "change" pages. It wouldn't make sense for you to be able to include methods in a list of fields that aren't for just display. Hence list_display allows you to include methods.


Python is expecting a unicode string, but in both instances you're feeding it something else.

In both instance a simple cast to a unicode string should fix the issue.

return unicode(self.id)

and

return unicode(self.post.nickname)

edit: You don't actually need to cast that part, sorry. Just the int cast to unicode should solve both problems.


You've altered the post.__unicode__() routine to return an int!

This is not a problem using the defaults.

A few special cases to note about list_display:

If the field is a ForeignKey, Django will display the __unicode__() of the related object.

0

精彩评论

暂无评论...
验证码 换一张
取 消