字段 'id' 需要一个数字但得到了 'logout_view'

Field 'id' expected a number but got 'logout_view'

我尝试添加新路径,结果发生了这种情况

Field 'id' expected a number but got 'logout_view'.

在 pycharm 终端我有其他错误 o.O

ValueError: Field 'id' expected a number but got 'favicon.ico'.

文件:

urls.py ->

from django.contrib import admin
from django.urls import path
from Artykuly.views import *

urlpatterns = [
    path('admin', admin.site.urls),
    path('', index, name='index'),
    path('<category_id>', category, name='category'),
    path('artykul/<category_id>', article, name='article'),
    path('login', login_view, name='login_view'),
    path('register', register_view, name='register_view'),
    path('logout', logout_view, name='logout_view'),
]

views.py

from django.contrib.auth import login
from django.contrib.auth import authenticate, login, logout
from django.shortcuts import render, redirect
from django.http import HttpResponse
from .models import Category, Article
from .forms import LoginForm, RegisterForm
# Create your views here.


def index(request):
    Categories = Category.objects.all()
    dane = {
        'Categories': Categories
    }
    return render(request, 'template.html', dane)


def category(request, category_id):
    category_user = Category.objects.get(pk=category_id)
    article_data = Article.objects.filter(category_id=category_id).all()
    Categories = Category.objects.all()
    dane = {
        'category_user': category_user,
        'article_data': article_data,
        'Categories': Categories,
    }
    return render(request, 'category.html', dane)


def article(request, category_id):
    article = Article.objects.get(pk=category_id)
    article_user = Article.objects.filter(pk=category_id)
    Categories = Category.objects.all()
    dane = {
        'article': article,
        'article_user': article_user,
        'Categories': Categories,
    }
    return render(request, 'artykul.html', dane)


def register_view(request):
    form = RegisterForm(request.POST or None)
    if form.is_valid():
        username = form.cleaned_data.get("username")
        email = form.cleaned_data.get("email")
        password = form.cleaned_data.get("password1")
        password2 = form.cleaned_data.get("password2")
        try:
            user = User.objects.create_user(username, email, password)
        except:
            user = None
        if user != None:
            login(request, user)
            return redirect("/")
        else:
            request.session['register_error'] = 1
    return render(request, 'forms.html', {'form': form})


def login_view(request):
    form = LoginForm(request.POST or None)
    if form.is_valid():
        username = form.cleaned_data.get("username")
        password = form.cleaned_data.get("password")
        user = authenticate(request, username=username, password=password)
        if user != None:
            login(request, user)
            return redirect("/")
        else:
            request.session['invalid_user'] = 1
    return render(request, 'forms.html', {'form': form})


def logout_view(request):
    logout(request)
    return redirect("login")

回溯 ->

Environment:


Request Method: GET
Request URL: http://127.0.0.1:8000/logout_view

Django Version: 3.2
Python Version: 3.8.6
Installed Applications:
['django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'Artykuly']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware']



Traceback (most recent call last):
  File "D:\Program Files (x86)\Python\Blog\venv\lib\site-packages\django\db\models\fields\__init__.py", line 1823, in get_prep_value
    return int(value)

The above exception (invalid literal for int() with base 10: 'logout_view') was the direct cause of the following exception:
  File "D:\Program Files (x86)\Python\Blog\venv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
    response = get_response(request)
  File "D:\Program Files (x86)\Python\Blog\venv\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "D:\Program Files (x86)\Python\Blog\Blog\Artykuly\views.py", line 19, in category
    category_user = Category.objects.get(pk=category_id)
  File "D:\Program Files (x86)\Python\Blog\venv\lib\site-packages\django\db\models\manager.py", line 85, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "D:\Program Files (x86)\Python\Blog\venv\lib\site-packages\django\db\models\query.py", line 424, in get
    clone = self._chain() if self.query.combinator else self.filter(*args, **kwargs)
  File "D:\Program Files (x86)\Python\Blog\venv\lib\site-packages\django\db\models\query.py", line 941, in filter
    return self._filter_or_exclude(False, args, kwargs)
  File "D:\Program Files (x86)\Python\Blog\venv\lib\site-packages\django\db\models\query.py", line 961, in _filter_or_exclude
    clone._filter_or_exclude_inplace(negate, args, kwargs)
  File "D:\Program Files (x86)\Python\Blog\venv\lib\site-packages\django\db\models\query.py", line 968, in _filter_or_exclude_inplace
    self._query.add_q(Q(*args, **kwargs))
  File "D:\Program Files (x86)\Python\Blog\venv\lib\site-packages\django\db\models\sql\query.py", line 1396, in add_q
    clause, _ = self._add_q(q_object, self.used_aliases)
  File "D:\Program Files (x86)\Python\Blog\venv\lib\site-packages\django\db\models\sql\query.py", line 1415, in _add_q
    child_clause, needed_inner = self.build_filter(
  File "D:\Program Files (x86)\Python\Blog\venv\lib\site-packages\django\db\models\sql\query.py", line 1350, in build_filter
    condition = self.build_lookup(lookups, col, value)
  File "D:\Program Files (x86)\Python\Blog\venv\lib\site-packages\django\db\models\sql\query.py", line 1196, in build_lookup
    lookup = lookup_class(lhs, rhs)
  File "D:\Program Files (x86)\Python\Blog\venv\lib\site-packages\django\db\models\lookups.py", line 25, in __init__
    self.rhs = self.get_prep_lookup()
  File "D:\Program Files (x86)\Python\Blog\venv\lib\site-packages\django\db\models\lookups.py", line 77, in get_prep_lookup
    return self.lhs.output_field.get_prep_value(self.rhs)
  File "D:\Program Files (x86)\Python\Blog\venv\lib\site-packages\django\db\models\fields\__init__.py", line 1825, in get_prep_value
    raise e.__class__(

Exception Type: ValueError at /logout_view
Exception Value: Field 'id' expected a number but got 'logout_view'.

发生这种情况的原因是因为你的模式:

path(<b>'<category_id>'</b>, category, name='category'),

由于您没有指定路径转换器类型,因此假定为string,从而匹配所有字符串,包括favicons.ico。但这可能行不通,因为这背后的观点 (category) 期望 category_id 成为 int.

您可以将 category_id 指定为具有 <<b>int:</b>category_id> 的数字序列:

urlpatterns = [
    path('admin', admin.site.urls),
    path('', index, name='index'),
    path('<<b>int:</b>category_id>', category, name='category'),
    path('artykul/<<b>int:</b>category_id>', article, name='article'),
    path('login', login_view, name='login_view'),
    path('register', register_view, name='register_view'),
    path('logout', logout_view, name='logout_view'),
]

这也是loginlogout等不会被触发的原因:因为如果你不指定category_id是一个数字序列,它将是第一个匹配的路径,因此它将“触发” category.

其他错误:

Field 'id' expected a number but got '<b>logout_view</b>'.

可能是因为 URL(例如在 <a …> 标签中)将 logout_view 用作 url,您应该使用 {% url … } template tag [Django-doc]为此。