Я пытаюсь создать подробное представление на основе классов для приложения инвентаризации.
Проблема в том, что когда я ищу указанный c элемент, я получаю следующую ошибку из браузера:
Page not found (404)
Request Method: GET
Request URL: http://127.0.0.1:8000/equipment/57/
Raised by: equipment.views.EquipmentType_DetailView
No equipment item found matching the query
You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page.
Странно то, что если попробовать напрямую «http://127.0.0.1: 8000 / equipment / 57 / update /», приложение будет работать отлично, и я буду перенаправлен на страницу обновления соответствующего объекта . Но если я ищу «http://127.0.0.1: 8000 / equipment / 57», я получаю сообщение об ошибке
Я изо всех сил пытаюсь понять это.
Вот мои URL-адреса в приложении. py:
from django.urls import path
from .views import (
EquipmentType_ListView,
EquipmentType_CreateView,
EquipmentType_UpdateView,
EquipmentType_DetailView,)
urlpatterns=[
path('', EquipmentType_ListView.as_view(), name='equipmentType-home'),
path('<int:pk>/', EquipmentType_DetailView.as_view(), name='equipmentType-detail'),
path('new/', EquipmentType_CreateView.as_view(), name='equipmentType-create'),
path('<int:pk>/update/', EquipmentType_UpdateView.as_view(), name='equipmentType-update'),
]
my views.py:
from django.shortcuts import render, redirect, get_object_or_404
from django.contrib.auth.models import User
from django.views.generic import (
ListView,
DetailView,
CreateView,
UpdateView,
DeleteView
)
from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin
from .models import EquipmentType, EquipmentItem
from django.contrib.messages.views import SuccessMessageMixin
# Create your views here.
class EquipmentType_ListView(LoginRequiredMixin, ListView):
model = EquipmentType
template_name = 'equipment/equipment_type.html' # default = <app>/<model>_<viewtype>.html
context_object_name = 'obj_list' #default = object_list
#ordering = ['date_posted'] #oldest to newest
#ordering = ['-date_posted'] #newest to oldest
ordering = ['type']
#paginate_by = 5
class EquipmentType_DetailView(LoginRequiredMixin, DetailView):
model = EquipmentItem
template_name = 'equipment/equipmenttype_detail.html'
class EquipmentType_CreateView(LoginRequiredMixin, SuccessMessageMixin, CreateView):
model = EquipmentType
template_name='equipment/equipmenttype_form.html'
fields = ['type', 'image']
success_message = "%(type)s creati"
def get_success_message(self, cleaned_data):
return self.success_message % dict(
cleaned_data,
type=self.object.type,
)
class EquipmentType_UpdateView(LoginRequiredMixin, SuccessMessageMixin, UpdateView):
model = EquipmentType
fields = ['type', 'image']
success_message = "%(type)s modificati"
def get_success_message(self, cleaned_data):
return self.success_message % dict(
cleaned_data,
type=self.object.type,
)
def test_func(self):
post = self.get_object()
if self.request.user == post.author:
return True
return False
вот мой шаблон деталей приложения:
{% extends 'equipment/0_base.html'%}
{% block content%}
<article class="media content-section">
<img class='rounded-circle article-img' src="{{ object.image.url }}" alt="">
<div class="media-body">
<div class="article-metadata">
<a class="mr-2" href="#">{{ object.type }}</a>
<!-- url 'user-posts' object.author.username %} -->
<small class="text-muted">{{ object.date_posted}}</small>
<!-- |date:'F d, Y' -->
<div class="">
<a href="{% url 'equipmentType-update' object.id %}" class='btn btn-warning btn-sm mt-1 mb-1'>Update</a>
</div>
</div>
</div>
</article>
{% endblock %}
и моя модель:
from django.db import models
from django.utils import timezone
from django.urls import reverse
from django.contrib.auth.models import User
from PIL import Image
# Create your models here.
class EquipmentType(models.Model):
type = models.CharField(max_length=100, unique=True)
date_posted = models.DateTimeField(auto_now_add=True)
# auto_now = timezone.now
image =models.ImageField(default='default.jpeg', upload_to='equipment/equipment_type')
def __str__(self):
return str(self.id) + ' - ' + self.type
def get_absolute_url(self):
return reverse('equipmentType-home')
# , kwargs={'pk': self.pk}
def save(self, *args, **kwargs):
super().save(*args, **kwargs)
img = Image.open(self.image.path)
if img.height > 300 or img.width > 300:
output_size = (300, 300)
img.thumbnail(output_size)
img.save(self.image.path)