为什么注入模板的数据只有在用户登录时才可用?想要所有的publi

2024-04-25 23:43:33 发布

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

我正在做一个投资组合网站,有一个关于页面。模型是在数据库上创建的,并且模板标记正在工作,但前提是用户在管理页面中经过身份验证。我已经将用户模型扩展为一个用户配置文件,以显示数据库中存储的投资组合数据-显然,我希望对每个人都公开,但我无法得到它。另外,我想用超级用户来管理所有与应用程序相关的模型,因为我不需要创建更多的用户,因为对于单个用户来说是一个简单的组合。你知道吗

Example of the view

代码:

from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save


class UserProfile(models.Model):

    user = models.OneToOneField(User)
    bio = models.TextField(max_length=1000, blank=True)
    location = models.CharField(max_length=30, blank=True)

    avatar = models.ImageField(upload_to='profile/', null=True, blank=True)
    uploaded_at = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return "{} Portfolio ".format(self.user)


def create_user_profile(sender, instance, created, **kwargs):
    """Create the UserProfile when a new User is saved"""
    if created:
        profile = UserProfile()
        profile.user = instance
        profile.save()


post_save.connect(create_user_profile, sender=User)

# ########################################################################################

from coltapp.models import Post, Comment, UserProfile
from django.views.generic import (TemplateView, ListView, DetailView,
                                  CreateView, UpdateView, DeleteView)


class AboutView(ListView):

    model = UserProfile
    template_name = 'coltapp/about.html'
    select_related = ('userprofile')

 # ########################################################################################


from coltapp import views
from django.conf.urls import url

#
#
app_name = 'coltapp'

urlpatterns = [

    url(r'^about/$', views.AboutView.as_view(), name='about'),


]

# ########################################################################################


<div class = "separator" >

    <p align = "center" > User: {{user.get_username}} < /p >

    <h3 align = "center" > Bio < /h3 >

    <p align = "center" > {{user.userprofile.bio}} < /p >
    <p align = "center" > {{user}} < /p >
    <p align = "center" > {{object.userprofile.bio}} < /p >


< / div >


# ########################################################################################

粘贴纸:

https://pastebin.com/4XCi0M8Z


Tags: django用户from模型importtruemodelssave
1条回答
网友
1楼 · 发布于 2024-04-25 23:43:33

这是因为默认情况下使用{{ user }}django模板。你知道吗

Django的内置上下文处理器默认提供user,如果未登录,则返回AnonymousUser(检查Django文档here

因此,如果您在模板中使用{{ user }}标记,它会自动在浏览器中显示现在登录的用户—而且浏览器中总是您,因此您可以在您的公文包中看到。你知道吗

1。将自己的用户传递到上下文

如果要使用自己的用户并将其显示给任何人(非登录用户),可以将自己的用户对象上下文传递给模板。你知道吗

2。使用您的UserProfile对象列表

或者你可以从你的ListView中使用object_list:你的公文包列表都在UserProfile对象列表中,对吗?你知道吗

如果你只有一个用户-就是你-你可以简单地在模板中循环你的UserProfile对象。你知道吗

不使用{{ user }},而是使用{{ object_list }}进行循环

如果你有更多的问题,请留下评论。你知道吗

更新

这是使用上下文数据传递您自己的模型的简单示例

from django.contrib.auth.models import User

class AboutView(ListView):

    model = UserProfile
    template_name = 'coltapp/about.html'
    select_related = ('userprofile')

    def get_context_data(self, **kwargs):
        context = super(AboutView, self).get_context_data(**kwargs)
        # just filter your user by username, email, pk...
        my_user = User.objects.get(username="your_username")
        context[my_user] = my_user
        return context

然后可以在模板中使用{{ my_user }}。你知道吗

关于第二个问题,我不太明白你的意思,但是。。。object_list来自AboutView的是UserProfile模型对象。你知道吗

DjangoListView自动传递模型对象,并使用默认名称-object_list。意思是object_list等于UserProfile.objects.all()

因此,如果您使用object_list在模板中进行forloop,那么您的所有UserProfile对象都是循环的。不清楚吗?你知道吗

I recommend not using default object_list. Instead, you can use your own name by adding context_object_name = "profiles" in AboutView. Then you can use profiles in template instead of object_list. Django Class Based View is really easy, but it's little bit implicated. If you want to know how view-template process work, try using FBV

这是使用context_object_name的示例

class AboutView(ListView):

    model = UserProfile
    template_name = 'coltapp/about.html'
    context_object_name = 'profiles'
    select_related = ('userprofile')

    def get_context_data(self, **kwargs):
        context = super(AboutView, self).get_context_data(**kwargs)
        # just filter your user by username, email, pk...
        my_user = User.objects.get(username="your_username")
        context[my_user] = my_user
        return context

相关问题 更多 >