pythonDjango如何获取登录用户的值视图.py?

2024-09-28 03:16:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我有CustomUser类用于日志记录,还有另一个coach类用于记录用户的信息。每个用户都链接到coach类。 我想创建模板,我的用户,如果他们完成了他们的个人资料将看到他们的信息,如果他们没有完成他们的个人资料,他们将看到一条消息。我正在学习pythondjango,例如,我不知道如何从类coach中获取我登录的用户的Adresse,并检查它是否为空。 你知道怎么解决吗?你知道吗

我的视图.py你知道吗

d级

def Profile(request):
    u = request.user.username
    x = u.coach.Adresse

    if len(x)!= 0:
        completed = "profile completed"
        return render(request, 'Profile.html', {'completed': completed})
    else:
        notcompleted = "please complete your profile"
        return render(request, 'Profile.html', {'notcompleted': notcompleted})

我的型号.py你知道吗

class coach(models.Model):
    user = models.OneToOneField(CustomUser,on_delete=models.CASCADE)
    Adresse = models.TextField(max_length=140, default='DEFAULT VALUE')
    Telephone = models.IntegerField(null=True, max_length=140, default='111')

Tags: 用户py信息modelsrequest记录profile个人资料
2条回答

Django推荐的最不痛苦的方法是通过OneToOneField(User)属性。你知道吗

Extending the existing User model …

If you wish to store information related to User, you can use a one-to-one relationship to a model containing the fields for additional information. This one-to-one model is often called a profile model, as it might store non-auth related information about a site user.

也就是说,扩展django.contrib.auth.models.User并替换它也能起作用。。。你知道吗

Substituting a custom User model Some kinds of projects may have authentication requirements for which Django’s built-in User model is not always appropriate. For instance, on some sites it makes more sense to use an email address as your identification token instead of a username.

[Ed: Two warnings and a notification follow, mentioning that this is pretty drastic.]

不是编写自己的用户类,而是扩展现有的用户模型。。你知道吗

您的请求将自动添加到模板中,这意味着您可以在模板中访问它,而无需在上下文中传递它。它由render函数传递给模板。你知道吗

所以在Profile.html模板中写下这个:

{% if request.user.is_authenticated %}
    <p>
        {% if request.user.coach.Adresse != 'DEFAULT VALUE' %}
            Profile Completed
        {% else %}
            Please complete your profile
        {% endif %}    
    </p>
{% endif %}

并将Profile方法更改为

def Profile(request):
    return render(request, 'Profile.html')

但是我认为你应该改变adrese字段,因为我看不出你为什么要使用默认值。只需删除默认值并允许其为空,如下所示:

Adresse = models.TextField(max_length=140, blank=True, null=True)

在模板中而不是{% if request.user.coach.Adresse != 'DEFAULT VALUE' %}{% if request.user.coach.Adresse %}

相关问题 更多 >

    热门问题