为什么我在 Django 中显示用户个人资料的代码不起作用?

问题描述 投票:0回答:1

我正在学习 Django,我正在制作一个网站,其中包括注册和创建您自己的个人资料。当您登录后,您可以查看其他用户的个人资料,并通过单击他们的图片将您重定向到他们的个人资料网站。

问题是:图片将您重定向到正确的网址,但它显示的是基本模板而不是我想要的模板 我检查了一些网站,甚至聊天 gpt 寻求帮助,但没有成功

我只会展示我的代码的重要部分,但如果缺少某些东西,请告诉我,我会添加它。这是“urls.py”的代码:

from django.urls import path
from . import views
from django.views.generic.base import RedirectView
from django.templatetags.static import static


app_name = 'app'
urlpatterns = [
    path('', views.index, name='index'),
    path('profile/', views.profile, name='profile'),
    path('profile_list/', views.profile_list, name='profile_list'),
    path('user_profile/<int:user_id>/', views.user_profile, name='user_profile'),
]

'views.py'

from django.shortcuts import render, redirect, get_object_or_404
from django.contrib.auth import login, logout, authenticate
from django.contrib.auth.forms import AuthenticationForm
from django.contrib.auth.decorators import login_required
from django.urls import reverse
from django.contrib import messages
from .forms import RegisterForm, UserProfileForm, MessageForm
from .models import UserProfile, Message
from django.contrib.auth.models import User

def index(request):
    return render(request, 'base.html')

@login_required
def profile(request):
    user_profile = UserProfile.objects.get(user=request.user)

    if request.method == 'POST':
        form = UserProfileForm(request.POST, request.FILES, instance=user_profile)
        if form.is_valid():
            form.save()
            return redirect('app:index')
    else:
        form = UserProfileForm(instance=user_profile)

    return render(request, 'profile.html', {'form':form})


def profile_list(request):
    profiles = UserProfile.objects.all()
    return render(request, 'profile_list.html', {'profiles': profiles})


def user_profile(request, user_id):
    profile = get_object_or_404(UserProfile, user_id=user_id)
    return render(request, 'user_profile.html', {'profile': profile})

'models.py'

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


def user_directory_path(instance, filename):
    return 'profile_pics/user_{0}/{1}'.format(instance.user.id, filename)


class UserProfile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    bio = models.CharField(max_length=250)
    profile_pic = models.ImageField(
        upload_to=user_directory_path,
        default='profile_pics/default.jpeg')

    def __str__(self):
        return f'{self.user.username} Profile'

基础模板 'base.html'

<html lang="pl">
  <head>
      {% load static %}
      <link rel='stylesheet' href='{% static 'style.css' %}' type='text/css'>
      <link rel="icon" type="image/x-icon" href="{% static 'images/favicon.ico' %}">
      <link href="https://fonts.googleapis.com/css2?family=Allison&family=Barlow+Condensed:wght@200&family=Ephesis&family=Gwendolyn&family=Lato:wght@100;400&family=Lovers+Quarrel&family=Mea+Culpa&family=MonteCarlo&family=Open+Sans:wght@300;400&family=Pinyon+Script&family=Qwigley&family=Roboto+Condensed:wght@300&family=Roboto:wght@300&family=Source+Sans+Pro:wght@300&family=Whisper&display=swap" rel="stylesheet">
      <meta charset="UTF-8">
  </head>
  <nav>
      {% if user.is_authenticated %}
          <ul>
              <li><a href="{% url 'app:profile_list' %}">Strona główna</a></li>
              <li><a href="{% url 'app:messages' %}">Listy</a></li>
              <li><a href="{% url 'app:profile' %}">Profil</a></li>
              <li><a href="{% url 'app:logout' %}">Wyloguj się</a></li>
          </ul>
      {% else %}
          <ul>
              <li><a href="{% url 'app:index' %}">Strona główna</a></li>
              <li><a href="{% url 'app:login' %}">Zaloguj się</a></li>
              <li><a href="{% url 'app:register' %}">Zarejestruj się</a></li>
          </ul>
      {% endif %}
      <img src="{% static 'border1.png' %}"/>
  </nav>
  <body>
      <section>
          {% block body %}
            <h1>Witaj w aplikacji Czat!</h1>

          {% endblock %}
      </section>
  </body>
</html>


带有配置文件列表的模板 'profile_list.html'

{% extends 'base.html' %}
{% load static %}

{% block body %}
  <h1>Profile użytkowników</h1>
  <ul class="profiles">
      {% for profile in profiles %}
        <li>
            <a href="/user_profile/{{ profile.user.id }}/">
                <img src="{{ profile.profile_pic.url }}" alt="Zdjęcie użytkownika {{ request.user.username }}" style="height: 150px; width:150px">
            </a>
            {{ profile.user.username }}
            {{ profile.user.id }}
        </li>
      {% endfor %}
  </ul>
{% endblock %}

<a href="/user_profile/{{ profile.user.id }}/">
之前我有
<a href="{% url 'user_profile' profile.user.id %}">
它显示错误没有有效的视图,例如'user_profile。更改后,单击一些图片会将我重定向到正确的 url e.x. 127.0.0.1:8000/user_profile/1/ 但正如我之前所说,它不显示所选用户的个人资料,而是显示索引页面

特定用户资料模板 'user_profile.html'

我不确定它是否正确 e.x.如果

{{ user.userprofile.username }}
应该看起来不同以指定我想显示特定用户的信息。我尝试了不同的变体,我不知道什么是最好的选择,但现在我认为这不是主要问题

{% extends 'base.html' %}

{% block content %}
  <div class="profile">
    <img src="{{ user.userprofile.profile_pic.url }}" alt="Zdjęcie profilowe użytkownika {{ request.user.userprofile.username }}">
    <h2>{{ user.userprofile.username }}</h2>
    <p>{{ user.userprofile.bio }}</p>
  </div>
{% endblock %}

我认为这就是所有需要的。

django django-views django-templates django-urls django-users
1个回答
0
投票

在您的profile_list.html中,您必须包含应用程序名称,因为您在urls.py中定义了它,

app_name = 'app'
profiles_list.html

<a href="{% url 'app:user_profile' profile.user.id %}">

接下来,在您的user_profile.html中它应该是

{% extends 'base.html' %}

{% block content %}
  <div class="profile">
    <img src="{{ profile.profile_pic.url }}" alt="Zdjęcie profilowe użytkownika {{ profile.user.username }}">
    <h2>{{ profile.user.username }}</h2>
    <p>{{ profile.bio }}</p>
  </div>
{% endblock %}

为什么?因为在您的

user_profile
视图中,您在您的上下文中发送了
profile
return render(request, 'user_profile.html', {'profile': profile})
。现在,配置文件是您在
models.py
中定义的 UserProfile 对象,具有
bio
profile_pic
的字段,并访问您执行的用户名
profile.user.username
.

© www.soinside.com 2019 - 2024. All rights reserved.