为什么“profile/<int:pk>”在 django 中不起作用

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

我是 Django 新手。我的个人资料有问题。当我打开主页或其他页面时,我会被错误地淘汰:

NoReverseMatch at /
Reverse for 'profile' with arguments '('',)' not found. 1 pattern(s) tried: ['registration/profile/(?P<pk>[0-9]+)\\Z']

我不知道该怎么办。 Boom非常感谢您的帮助! 这是代码: models.py:

import os.path
from PIL import Image
from django.contrib.auth.models import User
from django.db import models
from django.conf import settings
from django.db.models.signals import post_save
from django.dispatch import receiver


class reg(models.Model):
    email = models.CharField('email', max_length=50)
    password1 = models.CharField('password1', max_length=20)
    password2 = models.TextField('password2')

    def __str__(self):
        return self.email

    class Meta:
        verbose_name = 'registration'
        verbose_name_plural = 'registration'


class UserProfile(models.Model):
    user = models.OneToOneField(User, primary_key=True, verbose_name='user', related_name='profile', on_delete=models.CASCADE)
    name = models.CharField(max_length=20, blank=True, null=True)
    bio = models.TextField(max_length=500, blank=True, null=True)
    birth_date = models.DateField(null=True, blank=True)
    location = models.CharField(max_length=100, blank=True, null=True)
    picture = models.ImageField(upload_to='media/images', default='media/default.jpg', blank=True)

urls.py:

from django.contrib.auth import views as auth_views
from django.urls import path
from . import views
from .views import ProfileView
from django.conf.urls.static import static
from django.conf import settings

urlpatterns = [
    path('register/', views.register, name='register'),  # Remove leading slash from '/register'
    path('login/', auth_views.LoginView.as_view(), name='login'),
    path('logout/', auth_views.LogoutView.as_view(), name='logout'),
    path('profile/<int:pk>', ProfileView.as_view(), name='profile'),
]

if settings.DEBUG:
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

views.py:

from django.contrib.auth import login, authenticate
from django.contrib.auth.forms import AuthenticationForm
from django.contrib.auth.mixins import LoginRequiredMixin
from django.http import JsonResponse
from django.views import View
from .forms import RegistrationForm
from django.shortcuts import render, redirect, get_object_or_404
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.views.generic.detail import DetailView

from .models import UserProfile


def register(request):  # Change function name to match the URL pattern
    error = ''
    if request.method == 'POST':
        form = RegistrationForm(request.POST)
        if form.is_valid():
            user = form.save()
            login(request, user)
            messages.success(request, f'Аккаунт создан!')
            return redirect('profile')
        else:
            print(form.errors)

    form = RegistrationForm()

    data = {
        'form': form,
        'error': error
    }

    return render(request, 'registration/register.html', {'form': form})


class MyView(LoginRequiredMixin, View):
    login_url = '/login/'
    redirect_field_name = 'redirect_to'


@login_required
def profile(request):
    return render(request, 'registration/user_profile.html')


class ProfileView(View):
    def get(self, request, pk, *args, **kwargs):
        profile = UserProfile.objects.get(pk=pk)
        user = profile.user

        context = {
            'user': user,
            'profile': profile,
        }
        return render(request, 'registration/user_profile.html', context)

layout.html(错误发生在layout.html!):

{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>{% block title %}{% endblock %}</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css"/>
    <link rel="stylesheet" href="{% static 'main/css/main.css' %}">
    <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.8.2/css/all.css">
    <script src="{% static 'fontawesomefree/js/all.min.js' %}"></script>
</head>
<body>
    <aside>
        <img src="{% static 'main/img/LS_logo_BW.png' %}" alt="Beta Logo">
        <span class="logo">Loping</span>
        <h3>Навигация</h3>
          <ul class="sidebar-nav">
  </ul>
        <ul>
            <a href="{% url 'home' %}" style="text-decoration: none;"><li><i class="fa-solid fa-house-chimney"></i> Главная</li></a>
            <a href="{% url 'about' %}" style="text-decoration: none;"><li><i class="fa-solid fa-address-card"></i> О нас</li></a>
            <a href="" style="text-decoration: none;"><li><i class="fa-solid fa-address-book"></i> Контакты</li></a>
            <a href="{% url 'news' %}" style="text-decoration: none;"><li> <i class="fa-solid fa-newspaper"></i> Новости</li></a>
            {% if user.is_staff %}
                <a href="/admin" style="text-decoration: none;"><li><i class="fa-solid fa-lock"></i> Панель админа</li></a>
            {% endif %}
            <a href="{% url 'create' %}" style="text-decoration: none;"><li><button class="btn btn-danger"><i class="fa-solid fa-plus"></i> Добавить запись</button></li></a>
            <a href="{% url 'register' %}" style="text-decoration: none;"><li><button class="btn btn-danger"><i class="fa-solid fa-user"></i> Создать аккаунт</button></li></a>
            {% if user.is_authenticated %}
                <a href="{% url 'logout'%}?next={{request.path}}" style="text-decoration: none;"><li><button class="btn btn-danger"><i class="fa-solid fa-xmark"></i></i> Выйти из аккаунта</button></li></a>
                <a href="{% url 'profile' user.profile.id %}" style="text-decoration: none;"><li><button class="btn btn-danger"><i class="fa-solid fa-xmark"></i></i> Профиль</button></li></a>
                <li>Вы вошли как: {{ user.get_username }}</li>
            {% else %}
                <a href="{% url 'login'%}?next={{request.path}}" style="text-decoration: none;"><li><button class="btn btn-danger"><i class="fa-solid fa-right-to-bracket"></i> Войти в аккаунт</button></li></a>
            {% endif %}
        </ul>
    </aside>
    <main>
        {% block content %}
        {% endblock %}
    </main>
</body>
</html>

user_profile.html:

{% extends 'main/layout.html' %}
{% load static %}
{% block content %}
    <link rel="stylesheet" href="{% static 'profile/css/profile.css'%}">
<div class="row justify-content-center mt-5">
    <div class="features">
        <img class="rounded-circle account-img" src="{{ profile.picture.url }}" style="border-radius: 50%" height="150px" width="150px" />
        {% if profile.name %}
        <h3 class="py-4">{{ profile.name }}</h3>
        {% endif %}

        {% if profile.location %}
        <h3 class="py-4">{{ profile.location }}</h3>
        {% endif %}

        {% if profile.birth_date %}
        <h3 class="py-4">{{ profile.birth_date }}</h3>
        {% endif %}

        {% if profile.bio %}
        <h3 class="py-4">{{ profile.bio }}</h3>
        {% endif %}
    </div>
</div>
{% endblock content %}

我尝试过互联网上的视频和文章。什么都不起作用

python html django django-urls
1个回答
0
投票

'个人资料/int:pk

需要一个号码。

但是您重定向到

 return redirect('profile')

请尝试以下。

 return redirect(f'/profile/{user.id}')
© www.soinside.com 2019 - 2024. All rights reserved.