Home > Net >  Django - Error when viewing HTML template with autogenerated URL link to view function
Django - Error when viewing HTML template with autogenerated URL link to view function

Time:03-14

I am listing a bunch of items and within the HTML template it contains a URL link to the individual item (link is auto-generate), but I am getting this error when viewing the page:

reverse for 'producer_detail' with arguments '('itemxxx', datetime.datetime(1980, 1, 1, 0, 0, tzinfo=<UTC>))' not found. 1 pattern(s) tried: ['producers/(?P<pk>[^/] )/\\Z']

The table has a UniqueConstraint as there are multiple items with the same owner_name.

owner_name = models.CharField(max_length=12, primary_key=True)
logo_svg = models.CharField(max_length=100, blank=True, null=True)
account_name = models.CharField(max_length=12, blank=True, null=True)
metasnapshot_date = models.DateTimeField(blank=True, null=True)

constraints = [
            models.UniqueConstraint(
                fields=['owner_name', 'metasnapshot_date'],
                name="producer_idx",
            )
        ]

urlpatterns = [
    path("", views.producer_index, name="producer_index"),
    path("<str:pk>/", views.producer_detail, name="producer_detail"),
]

My views

def producer_index(request):
     producers = Producer.objects.all()
     context = {
         'producers': producers
     }
     print(producers)
     return render(request, 'producer_index.html', context)
    
def producer_detail(request, pk, metasnapshot_date):
     producer = Producer.objects.filter(pk=pk,metasnapshot_date=metasnapshot_date)
     context = {
         'producer': producer
     }
     return render(request, 'producer_detail.html', context)

My HTML template to view all items

{% extends "base.html" %}
 {% load static %}
 {% block page_content %}
 <h1>Producers</h1>
 <div >
 {% for producer in producers %}
     <div >
         <div >
             <img  src="{{ producer.logo_svg }}">
            <div >
                <h5 >{{ producer.owner_name }}</h5>
                <p >{{ producer.url }}</p>
                 <a href="{% url 'producer_detail' producer.pk producer.metasnapshot_date %}"
                   >
                    Read More
                </a>

            </div>
        </div>
    </div>
    {% endfor %}
</div>
{% endblock %}

The problem I think:

My guess it's not filtering properly to a single item. I am fairly new to Django so not sure whether my view is configured correctly.

CodePudding user response:

You just forgot to pass metasnapshot_date to the url
change this

urlpatterns = [
    path("", views.producer_index, name="producer_index"),
    path("<str:pk>/", views.producer_detail, name="producer_detail"),
]

To

urlpatterns = [
    path("", views.producer_index, name="producer_index"),
    path("<str:pk>/<date:metasnapshot_date>/", views.producer_detail, name="producer_detail"),
]
  • Related