我想创建的字段将与当前管理员谁是登录的电子邮件自动填充,它应该是只读字段
我试过这个:
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)
我该如何实施?
1条答案
按热度按时间kkih6yb81#
您可以通过将
readonly_fields
字段添加到ModelAdmin类来实现这一点: