[英]How can I fill a field in Django with the username?
I have a model, configuration
, in Django and wish to fill the author
field with get_username
Can this be done within the model or must it be done from the form? 我在Django中有一个
configuration
模型,并希望用get_username
填充author
字段。可以在模型中完成此操作还是必须从表单中完成? If it must be on the form, how can I change the standard admin page to have this functionality? 如果必须在表单上,如何更改标准管理页面以具有此功能? At present, the model reads thus:
目前,该模型的内容如下:
class Configuration(models.Model):
title = models.CharField(max_length=100,unique=True,blank=False)
author = models.CharField(max_length=50,blank=False)
created = models.DateTimeField("date created",auto_now_add=True)
modified = models.DateTimeField("date modified",auto_now=True)
description = models.CharField(max_length=512)
drawing = models.ForeignKey(Drawing)
instruments = models.ManyToManyField(Instrument)
def __unicode__(self):
return self.title
Use models.ForeignKey
: 使用
models.ForeignKey
:
#models.py
from django.contrib.auth.models import User
class Configuration(models.Model):
author = models.ForeignKey(User)
...
#admin.py:
class Configuration_admin(admin.ModelAdmin):
fields = ('title', 'author',....)
something like that: 像这样的东西:
from django.contrib.auth.models import User
class ...
...
username = models.ForeignKey(User)
If you want to make some relationship between your model and default User model then you can extends the User model into your own custom model , like this: 如果要在模型和默认用户模型之间建立某种关系,则可以将用户模型扩展到自己的自定义模型中,如下所示:
models.py models.py
from django.contrib.auth.models import User
class Configuration(models.Model):
author = models.OneToOneField(User)
..
..
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.