简体   繁体   中英

How to Change OneToOne model Field Default Message in Django Admin?

I have suppose following model.

class Replied(BaseModel):
    reply = models.OneToOneField(Review, on_delete=models.CASCADE)
    show_reply = models.BooleanField(default=False)
    replied_by = models.ForeignKey(User, on_delete=models.CASCADE)

    class Meta:
        verbose_name = 'Reply'
        verbose_name_plural = 'Replies'

    def __str__(self):
        return self.content

When I tried adding more than reply to certain reply the error message by default given by Django Admin is as follow. Reply with this Reply already exists. I want certain message like this.

Reply to this review already exists.

How can I do that? In my opinion it should be done in admin so here is my admin.py code

@admin.register(Replied)
class RepliedAdmin(ModelAdmin):
    list_display = (
        'replied_by',
        'created_at')

    list_filter = ('replied_by',)

    list_display_links = ('replied_by',)

    

You can override the error_messages=… parameter [Django-doc] for the unique error message:

class Replied(BaseModel):
    reply = models.OneToOneField(
        Review,
        on_delete=models.CASCADE,
        
    )
    show_reply = models.BooleanField(default=False)
    replied_by = models.ForeignKey(User, on_delete=models.CASCADE)

    class Meta:
        verbose_name = 'Reply'
        verbose_name_plural = 'Replies'

    def __str__(self):
        return self.content

That being said, the default message is:

,code>'unique': '%(model_name)s with this  already exists.'

so by setting the verbose_name=… [Django-doc] , this issue is also resolved, and all other error messages will be adapted:

class Replied(BaseModel):
    reply = models.OneToOneField(
        Review,
        on_delete=models.CASCADE,
        
    )
    show_reply = models.BooleanField(default=False)
    replied_by = models.ForeignKey(User, on_delete=models.CASCADE)

    class Meta:
        verbose_name = 'Reply'
        verbose_name_plural = 'Replies'

    def __str__(self):
        return self.content

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM