Django Admin预先填写用户的电子邮件
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Django Admin预先填写用户的电子邮件相关的知识,希望对你有一定的参考价值。
我需要一些帮助来在我的模型中预先填充用户的电子邮件。必须有一个简单的方法,但我想我太累了看不到这个伎俩。基本上我需要的是,在用户登录到管理员之后,我需要用户模型中的用户,电子邮件和名称等字段已经填充了当前用户的信息。
非常感谢您的帮助!目前我的模型是这样的:
class ParcareManager(models.Manager):
def active(self, *args, **kwargs):
return super(ParcareManager, self).filter(draft=False).filter(parking_on__lte=timezone.now())
class Parcare(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, blank=True, null=True, default=1, on_delete=True)
email=models.EmailField(blank=True, null=True)
# email = models.EmailField(settings.AUTH_USER_MODEL)
parking_on = models.DateField(auto_now=False, auto_now_add=False,blank=True, null=True)
parking_off = models.DateField(
auto_now=False, auto_now_add=False, blank=True, null=True) #plecarea din parcare
location =models.CharField(max_length=120, default="P1", blank=True, null=True)
updated = models.DateTimeField(auto_now=True, auto_now_add=False,blank=True, null=True)
timestamp=models.DateTimeField(auto_now=False, auto_now_add=True,blank=True, null=True)
venire = models.TimeField(default=datetime.time(9, 00),auto_now=False, auto_now_add=False )
plecare = models.TimeField(default=datetime.time(
18, 00), auto_now=False, auto_now_add=False)
objects = ParcareManager()
def __str__(self):
return self.email + " | " + self.location + " | " + str(self.parking_on) + " | " + str(self.parking_off)
class Meta:
verbose_name_plural = "parcare"
class Meta:
ordering = ["-timestamp", "-updated"]
我的管理员是这样的:
from django.contrib import admin
# Register your models here.
from .models import Parcare
class ParcareModelAdmin(admin.ModelAdmin):
list_display = [ "email","user", "location",
"parking_on", "parking_off", "venire", "plecare"]
list_display_links = ["email", "user" ]
list_editable = [ "parking_off", "parking_on","venire", "plecare"]
list_filter = ["parking_on", "parking_off", "venire", "plecare"]
search_fields = ["location", "name"]
class Meta:
model = Parcare
def email(self, obj):
return obj.user.email
admin.site.register(Parcare, ParcareModelAdmin)
答案
如果是这种情况,那么你可以试试这个:
def get_form(self, request, obj=None, **kwargs):
form = super().get_form(request, obj, **kwargs)
if not obj:
user = request.user
form.base_fields['user'].initial = user
form.base_fields['email'].initial = user.email
return form
在这里,您从请求中获取登录的用户对象,然后初始化该用户的值。
以上是关于Django Admin预先填写用户的电子邮件的主要内容,如果未能解决你的问题,请参考以下文章