简体   繁体   English

如何将登录用户的用户名添加到 django 中的模型字段

[英]How do I add username of logged in user to model field in django

How to add username of currently logged in user to field in my model?如何将当前登录用户的用户名添加到我的模型中的字段? For example, I need to store info about user like name, email and so on in model, other than default Django user model, but I still use default one to store credentials.例如,我需要在模型中存储有关用户的信息,如姓名、电子邮件等,而不是默认的 Django 用户模型,但我仍然使用默认的模型来存储凭据。 I want to establish relationship between those, so I created username field in my model.我想建立它们之间的关系,所以我在我的模型中创建了username段。 How do I fill it with current user's username upon saving the corresponding form?保存相应表单后如何填写当前用户的用户名? My model我的模型

class ApplicantProfile(models.Model):
    name = models.CharField(max_length = 50)
    dob = models.DateField()
    email = models.EmailField()
    description = models.TextField()
    username = <something>

What do I change <something> with?我用什么来改变<something>

My form我的表格

class ApplicantProfileEdit(forms.ModelForm):
class Meta:
    model = ApplicantProfile
    fields = [
        'name',
        'dob',
        'email',
        'description',
    ]

My view我的看法

def ApplEditView(request):
    form = ApplicantProfileEdit(request.POST or None)
    if form.is_valid():
       form.save()
       form = ApplicantProfileEdit()
    context = {
       'form':form
    }
    return render(request, "applProfileEdit.html", context)

PS I tried to import models straight to my views.py , and assign request.user.username to username field of the model in my view, but it didn't work, just left that field empty. PS 我试图将模型直接导入我的views.py ,并将request.user.username分配给我视图中模型的username字段,但它没有用,只是将该字段留空。 I had username as CharField when I tried this.当我尝试这个时,我的usernameCharField

It is not a good idea to save the username itself, or at least not without a FOREIGN KEY constraint.保存用户名本身不是一个好主意,或者至少在没有FOREIGN KEY约束的情况下不是一个好主意。 If later a user changes their name, then the username now points to a non-existing user, if later another user for example changes their username to thatusername, then your ApplicantProfile will point to the wrong user.如果稍后用户更改了他们的姓名,那么用户名现在指向一个不存在的用户,如果稍后另一个用户将他们的用户名更改为该用户名,那么您的ApplicantProfile档案将指向错误的用户。

Normally one uses a ForeignKey field [Django-doc] , or in case each ApplicantProfile points to a different user, a OneToOneField [Django-doc] :通常使用ForeignKey字段 [Django-doc] ,或者如果每个ApplicantProfile指向不同的用户,则使用OneToOneField [Django-doc]

from django.conf import settings
from django.db import models

class ApplicantProfile(models.Model):
    name = models.CharField(max_length = 50)
    dob = models.DateField()
    email = models.EmailField()
    description = models.TextField()
    # maybe a OneToOneField
    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)

In the view:在视图中:

from django.contrib.auth.decorators import login_required
from django.shortcuts import redirect

@login_required
def appl_edit_view(request):
    if request.method == 'POST':
        form = ApplicantProfileEdit(request.POST)
        if form.is_valid():
            form.instance.user = request.user
            form.save()
            return redirect('some-view-name')
    else:
        form = ApplicantProfileEdit()
    context = {
        'form':form
    }
    return render(request, 'applProfileEdit.html', context)

Note : In case of a successful POST request, you should make a redirect [Django-doc] to implement the Post/Redirect/Get pattern [wiki] .注意:如果 POST 请求成功,您应该进行redirect [Django-doc]以实现Post/Redirect/Get模式 [wiki] This avoids that you make the same POST request when the user refreshes the browser.这可以避免您在用户刷新浏览器时发出相同的 POST 请求。

Note : You can limit views to a view to authenticated users with the @login_required decorator [Django-doc] .注意:您可以使用@login_required装饰器 [Django-doc]将视图限制为经过身份验证的用户的视图。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在不扩展用户 Model 的 Django ModelForm 中自定义默认用户 Model 的用户名字段的显示? - How do I customize the display of username field of default User Model in Django ModelForm without extending User Model? 如何使用 django 添加登录用户的用户名 - How to add the logged in user's username with django 如何获取写入文本的登录用户的用户名并将其永久显示在 Django 中的文本旁边? - How do i get the username of a logged user writing a text and display it beside the text permanently in Django? 如何在 Django 中获取登录用户的用户名? - How can I get the username of the logged-in user 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? 用户登录后如何存储/打印用户 ID/用户名? - How do I store/print userid/username after user logged in? Django,更改用户模型的用户名字段 - Django, alter username field of User model Django模型:从当前登录的用户返回用户名 - Django Model: Returning username from currently logged in user 保存表单时如何在模型字段中保存当前登录的用户名? - How to save currently logged in user username in model's field while saving a form? 如何为Django的用户模型添加索引 - How do I add an index to Django's User model
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM