bugfix> python > 投稿

いくつかのコードに苦労しています。多くの人がこの問題を抱えているのを見てきましたが、彼らのコード修正を私のもので動作させることができないようです(もちろん私のプロジェクトに合うように変更します)。私はまだこれに本当に新しいです。

product_list.htmlの商品リストから商品を編集できるようにしたい。 製品を編集できるproduct_update.htmlというHTMLページを作成しましたが、これは機能します。しかし、product_listページの「編集」リンクをそのproduct_updateページに誘導したいと思います。


このエラーが発生します:引数 '(' '、)'が見つからない 'product-update'の/ products/ReverseにあるNoReverseMatch。 1つのパターンが試行されました:['products /(?P [0-9] +)/ edit/$']

これが私のコードです:

views.py

from django.http import Http404
from django.shortcuts import render, get_object_or_404, redirect
from django.views.generic import UpdateView
from .forms import ProductForm, RawProductForm
from .models import Product
def product_list_view(request):
queryset = Product.objects.all()
context = {
    "object_list": queryset
}
return render(request, "products/product_list.html", context)
# ------------------------------------------------------------ #
class UpdateProductView(UpdateView):
model = Product
template_name = 'products/product_update.html'
fields = ['title', 'image', 'description', 'price', 'summary', 'featured']

product_list.html

{% extends 'base.html' %}
{% block content %}
{% for instance in object_list %}
  <p>
    {{ instance.id }} -
    <a href="{{ instance.get_absolute_url }}">{{ instance.title }}</a>
    |
    <a href="{% url 'products:product-update' %}">(Edit)</a>
    |
    <!-- <a href="">Delete</a> -->
  </p>
{% endfor %}
{% endblock %}

models.py

   from django.db import models
    from django.urls import reverse
    from PIL import Image
    class Product(models.Model):
        title       = models.CharField(max_length=120) # max_length = required
        image       = models.ImageField(null=True, blank=True, upload_to="images/")
        description = models.TextField(blank=True, null=True)
        price       = models.DecimalField(decimal_places=2, max_digits=10000)
        summary     = models.TextField(blank=True, null=False)
        featured    = models.BooleanField(default=False)
        def get_absolute_url(self):
            return reverse("products:product-detail", kwargs={"id": self.id})
            # return f"products/{self.id}/"
        def save(self, *args, **kwargs):
            super().save(*args, **kwargs)
            img = Image.open(self.image.path)
            # if img.height > 300 or img.weight > 300:
            #     output_size = (300, 300)
            #     img.thumbnail(output_size)
            #     img.save(self.image.path)

urls.py

   from django.contrib import admin
    from django.urls import path
    from products.views import (
        product_detail_view,
        product_create_view,
        product_delete_view,
        product_list_view,
        dynamic_lookup_view,
        UpdateProductView,
        )
    app_name = 'products'
    urlpatterns = [
        path('', product_list_view, name='product-list'),
        path('', product_detail_view),
        path('<int:id>/', dynamic_lookup_view, name='product-detail'),
        path('<int:id>/delete/', product_delete_view, name='product-delete'),
        path('create/', product_create_view),
        path('<int:pk>/edit/', UpdateProductView.as_view(), name='product-update'),
    ]

トレースバック

Environment:
Request Method: GET
Request URL: http://127.0.0.1:8000/products/
Django Version: 3.1.3
Python Version: 3.9.0
Installed Applications:
['django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'pages',
 'products',
 'blog',
 'members']
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']
Template error:
In template /Users/alfiemitchell/Documents/Dev/tryDjango/src/templates/base.html, error at line 0
   Reverse for 'product-update' with arguments '('',)' not found. 1 pattern(s) tried: ['products/(?P<pk>[0-9]+)/edit/$']
   1 : <!doctype html>
   2 : <html>
   3 : <head>
   4 :   <title>Try Django</title>
   5 : </head>
   6 :     <body>
   7 :       {% include 'navbar.html' %}
   8 : 
   9 :       {% block content %}
   10 :       {% endblock %}
Traceback (most recent call last):
  File "/Users/alfiemitchell/Documents/Dev/tryDjango/venv/lib/python3.9/site-packages/django/core/handlers/exception.py", line 47, in inner
    response = get_response(request)
  File "/Users/alfiemitchell/Documents/Dev/tryDjango/venv/lib/python3.9/site-packages/django/core/handlers/base.py", line 179, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/Users/alfiemitchell/Documents/Dev/tryDjango/src/products/views.py", line 82, in product_list_view
    return render(request, "products/product_list.html", context)
  File "/Users/alfiemitchell/Documents/Dev/tryDjango/venv/lib/python3.9/site-packages/django/shortcuts.py", line 19, in render
    content = loader.render_to_string(template_name, context, request, using=using)
  File "/Users/alfiemitchell/Documents/Dev/tryDjango/venv/lib/python3.9/site-packages/django/template/loader.py", line 62, in render_to_string
    return template.render(context, request)
  File "/Users/alfiemitchell/Documents/Dev/tryDjango/venv/lib/python3.9/site-packages/django/template/backends/django.py", line 61, in render
    return self.template.render(context)
  File "/Users/alfiemitchell/Documents/Dev/tryDjango/venv/lib/python3.9/site-packages/django/template/base.py", line 170, in render
    return self._render(context)
  File "/Users/alfiemitchell/Documents/Dev/tryDjango/venv/lib/python3.9/site-packages/django/template/base.py", line 162, in _render
    return self.nodelist.render(context)
  File "/Users/alfiemitchell/Documents/Dev/tryDjango/venv/lib/python3.9/site-packages/django/template/base.py", line 938, in render
    bit = node.render_annotated(context)
  File "/Users/alfiemitchell/Documents/Dev/tryDjango/venv/lib/python3.9/site-packages/django/template/base.py", line 905, in render_annotated
    return self.render(context)
  File "/Users/alfiemitchell/Documents/Dev/tryDjango/venv/lib/python3.9/site-packages/django/template/loader_tags.py", line 150, in render
    return compiled_parent._render(context)
  File "/Users/alfiemitchell/Documents/Dev/tryDjango/venv/lib/python3.9/site-packages/django/template/base.py", line 162, in _render
    return self.nodelist.render(context)
  File "/Users/alfiemitchell/Documents/Dev/tryDjango/venv/lib/python3.9/site-packages/django/template/base.py", line 938, in render
    bit = node.render_annotated(context)
  File "/Users/alfiemitchell/Documents/Dev/tryDjango/venv/lib/python3.9/site-packages/django/template/base.py", line 905, in render_annotated
    return self.render(context)
  File "/Users/alfiemitchell/Documents/Dev/tryDjango/venv/lib/python3.9/site-packages/django/template/loader_tags.py", line 62, in render
    result = block.nodelist.render(context)
  File "/Users/alfiemitchell/Documents/Dev/tryDjango/venv/lib/python3.9/site-packages/django/template/base.py", line 938, in render
    bit = node.render_annotated(context)
  File "/Users/alfiemitchell/Documents/Dev/tryDjango/venv/lib/python3.9/site-packages/django/template/base.py", line 905, in render_annotated
    return self.render(context)
  File "/Users/alfiemitchell/Documents/Dev/tryDjango/venv/lib/python3.9/site-packages/django/template/defaulttags.py", line 211, in render
    nodelist.append(node.render_annotated(context))
  File "/Users/alfiemitchell/Documents/Dev/tryDjango/venv/lib/python3.9/site-packages/django/template/base.py", line 905, in render_annotated
    return self.render(context)
  File "/Users/alfiemitchell/Documents/Dev/tryDjango/venv/lib/python3.9/site-packages/django/template/defaulttags.py", line 446, in render
    url = reverse(view_name, args=args, kwargs=kwargs, current_app=current_app)
  File "/Users/alfiemitchell/Documents/Dev/tryDjango/venv/lib/python3.9/site-packages/django/urls/base.py", line 87, in reverse
    return iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs))
  File "/Users/alfiemitchell/Documents/Dev/tryDjango/venv/lib/python3.9/site-packages/django/urls/resolvers.py", line 685, in _reverse_with_prefix
    raise NoReverseMatch(msg)
Exception Type: NoReverseMatch at /products/
Exception Value: Reverse for 'product-update' with arguments '('',)' not found. 1 pattern(s) tried: ['products/(?P<pk>[0-9]+)/edit/$']

回答 1 件
  • 更新ビューのパラメーターとして主キーを指定する必要があります。 product-list.htmlファイルを次のように変更すると、問題は解決します。

    {% extends 'base.html' %}
    {% block content %}
    {% for instance in object_list %}
      <p>
        {{ instance.id }} -
        <a href="{{ instance.get_absolute_url }}">{{ instance.title }}</a>
        |
        <a href="{% url 'products:product-update' instance.pk %}">(Edit)</a>
        |
        <!-- <a href="">Delete</a> -->
      </p>
    {% endfor %}
    {% endblock %}
    
    

あなたの答え