如何在django admin中自动填充字段并使其成为只读

xoshrz7s  于 2023-04-07  发布在  Go
关注(0)|答案(1)|浏览(123)

我想创建的字段将与当前管理员谁是登录的电子邮件自动填充,它应该是只读字段
我试过这个:
admin.py

from django.contrib import admin
from support.models import Ticket

class TicketAdmin(admin.ModelAdmin):

    def get_form(self, request, obj=None, **kwargs):
        form = super().get_form(request, obj, **kwargs)
        form.base_fields['created_by'].initial = request.user
        return form

    def save_model(self, request, obj, form, change):
        if not obj.created_by:
            obj.created_by = request.user
        super().save_model(request, obj, form, change)

admin.site.register(Ticket, TicketAdmin)

我仍然能够编辑字段,并能够从下拉列表中选择其他电子邮件地址
model.py

class Ticket(models.Model):

    
    PRIORITY = (
        ("High", "high"),
        ("Medium", "medium"),
        ("Low", "low")
    )

    subject = models.CharField(max_length=255)
    body = models.TextField()
    priority = models.CharField(max_length=10,choices=PRIORITY)
    created_by = models.ForeignKey(Users, on_delete=models.CASCADE)

我该如何实施?

kkih6yb8

kkih6yb81#

您可以通过将readonly_fields字段添加到ModelAdmin类来实现这一点:

class TicketAdmin(admin.ModelAdmin):
    readonly_fields = ['created_by']

    def get_form(self, request, obj=None, **kwargs):
        form = super().get_form(request, obj, **kwargs)
        form.base_fields['created_by'].initial = request.user
        return form

    def save_model(self, request, obj, form, change):
        if not obj.created_by:
            obj.created_by = request.user
        super().save_model(request, obj, form, change)

相关问题