gpt4 book ai didi

python - Django 模板显示所有用户而不是单个用户的数据

转载 作者:行者123 更新时间:2023-11-30 22:00:11 24 4
gpt4 key购买 nike

我正在尝试检索有关用户个人资料的信息以显示在页面上。问题是它从每个用户而不是仅登录的用户检索相关信息。

我尝试仅请求当时登录的用户,但不幸的是我无法让它工作。

HTML

    <div>
<span class="bold">
<p>Bio:</p>
</span>
<p>
{{ profile.bio }}
</p>
</div>

模型.py

class Profile(models.Model):
user = models.OneToOneField(User, default=None, null=True, on_delete=models.CASCADE)
bio = models.CharField(max_length=2000)
instrument = models.CharField(max_length=255, choices=instrument_list, blank=True)
level = models.CharField(max_length=255, choices=level_list, blank=True)
preferred_language = models.CharField(max_length=255, choices=language_list, blank=True)
time_zone = models.CharField(max_length=255, choices=time_list, blank=True)

def __str__(self):
return self.profile

@receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
if created:
Profile.objects.create(user=instance)

@receiver(post_save, sender=User)
def save_user_profile(sender, instance, **kwargs):
instance.profile.save()

class ProfileForm(ModelForm):
class Meta:
model = Profile
exclude = ('user',)

View .py

@login_required
def profile_page_edit(request):
if request.method == 'POST':
form = ProfileForm(request.POST)

if form.is_valid():
profile = form.save(commit=False)
profile.user = request.user
profile.save()
return redirect('/student/profile-page')

else:
form = ProfileForm()

form = ProfileForm()

context = {'form': form }
return render(request, 'student/profile_page_edit.html', context)

@login_required
def profile_page(request):
form = ProfileForm
profile = request.user.profile
args = {'form' : form, 'profile' : profile}
return render(request, 'student/profile_page.html', args)

我正在尝试让 profile_page View 仅显示一个用户(当前登录的用户)的相关模型信息。

最佳答案

您需要过滤查询集,从而获取正确的查询集:

from django.contrib.auth.decorators import login_required

<b>@login_required</b>
def profile_page(request):
form = ProfileForm<b>()</b>
<b>profile = request.user.profile</b>
context = {'form' : form, <b>'profile' : profile</b>}
return render(request, 'student/profile_page.html', context)

在模板中,我们当然只渲染 profile 变量的简介:

 <!-- Bio -->
<div>
<span class="bold">
<p>Bio:</p>
</span>
<p>
{{ <b>profile.bio</b> }}
</p>
</div>

请注意,除非您为该用户创建 Profile 对象,否则没有与该User 关联的 Profile 对象。

关于python - Django 模板显示所有用户而不是单个用户的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54389580/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com