【问题标题】:why list of users are not shown in the django template?为什么用户列表没有显示在 django 模板中?
【发布时间】:2020-09-13 19:50:29
【问题描述】:

我的目标是在 django 的模板上显示用户列表。但它不会呈现用户。

accounts/models.py:

class CustomUser(AbstractUser):
    age = models.PositiveIntegerField(null=True, blank=True)
    name = models.CharField(max_length=200, blank=True)

帐户/admin.py:

class CustomUserAdmin(UserAdmin):
    add_form = CustomUserCreationForm
    form = CustomUserChangeForm
    model = CustomUser
    list_display = ['email', 'username', 'age', 'is_staff', ]
admin.site.register(CustomUser, CustomUserAdmin)

accounts/form.py:

class CustomUserCreationForm(UserCreationForm):
    class Meta(UserCreationForm.Meta):
        model = CustomUser
        fields = UserCreationForm.Meta.fields + ('age',)
class CustomUserChangeForm(UserChangeForm):
    class Meta:
        model = CustomUser
        fields = UserChangeForm.Meta.fields

accounts/views.py:

class SignUpView(CreateView):
    form_class = CustomUserCreationForm
    success_url = reverse_lazy('login')
    template_name = 'signup.html'
class UsersView(TemplateView):
    template_name='homepage.html'
    def get_context_data(self,**kwargs):
        context = super(UsersView,self).get_context_data(**kwargs)
        context['object_list'] = CustomUser.objects.all()
        return context

和 blogapp/urls.py:

urlpatterns = [
    path('admin/', admin.site.urls),
    path('accounts/',include('accounts.urls')),
    path('accounts/',include('django.contrib.auth.urls')),
    path('',TemplateView.as_view(template_name='homepage.html'),name='homepage'),
]

模板/homepage.html:

{% block content %}
<h1>Online users</h1>
<ul>
    {% for user in object_list %}
        <li class="user">{{ user }}</li>
    {% endfor %}
</ul>
{% endblock content %}

当我执行 python manage.py runserver 时,它只显示标题在线用户,但没有用户列表。我在管理员中创建了三个用户,但模板中没有显示任何内容,也没有错误。

请你帮我解决这个问题好吗?

【问题讨论】:

    标签: django django-models django-views django-templates


    【解决方案1】:

    我找到了解决办法。

    在 blogapp/urls.py 中,我必须改变这个:

    urlpatterns = [
        path('admin/', admin.site.urls),
        path('',include('accounts.urls')), #here is the change...delete accounts/
        path('accounts/',include('django.contrib.auth.urls')),
        path('',TemplateView.as_view(template_name='homepage.html'),name='homepage'),
    ]
    

    之后我必须更改一些设置,例如 LOGIN_REDIRECT_URL 和 LOGIN_REDIRECT_URL,因为它们在登录和注销后重定向页面。删除了几个完整的项目。我不知道为什么会这样,但我做了我的工作。如果有人知道,请提及。

    谢谢大家

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-05-21
      • 2021-08-16
      • 1970-01-01
      • 1970-01-01
      • 2016-08-14
      • 1970-01-01
      • 2022-10-16
      相关资源
      最近更新 更多