简体   繁体   English

如何在Django中使用用户名填充字段?

[英]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.

相关问题 如何填写视图中的 Django 表单字段? - How can I fill the Django forms field in view? 如何在Django用户名中允许空格? - How can I allow spaces in a Django username? 我如何使用 django 中的额外字段(除用户名/ email 和密码之外)验证任何用户登录 - How can i authenticate any user for login with an extra field (other then username/ email and password) in django 如何用当前用户名填写作者字段 - how to fill an author field with current username 如何在Django中使用CreateView / UpdateView在表单中使用当前用户填写字段? - How can I fill a field with current user in form using CreateView/UpdateView in Django? 如何将登录用户的用户名添加到 django 中的模型字段 - How do I add username of logged in user to model field in django 我如何填表? (Python,Django) - How can I fill the table? (Python, Django) 我应该如何在 django 中自动填充字段并使其只读? - How should i auto fill a field and make it readonly in django? 我如何在 django 中使用模型对象预填充表单字段 - how do i pre fill a form field with a models object in django 如何检查存储为 ForeignKey 字段的用户名和 request.user.username 在 Django 中是否相等? - How do I check whether username stored as a ForeignKey field and request.user.username are equal in Django?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM