Django错误:'DetailView'对象没有属性'_ meta'

lsmd5eda  于 2022-11-18  发布在  Go
关注(0)|答案(1)|浏览(159)

这让我很震惊。我正在用Django & REST API构建一个模型,我在向浏览器呈现单个汽车的DetailView时遇到了麻烦。ListView工作正常,但我也会包括代码,因为它们是相互关联的。
特别是,我无法使get_object()函数正常工作。
这是我使用的第一种方法

查看次数.py

class CarDetailView(generics.RetrieveUpdateDestroyAPIView):
    renderer_classes = [TemplateHTMLRenderer]
    template_name = 'car-detail.html'
    queryset = Car.objects.all()
    lookup_field = Car.id
    
    @action(detail=True, renderer_classes=[TemplateHTMLRenderer])
    def get(self, request, *args, **kwargs):
        car = self.get_object()
        return Response({
            'car': car,
        })

虽然页面正确呈现且没有错误,但模板标记都不起作用。只有{{ car.model }}返回None
所以我修改了代码以使用self.get_object()

class CarDetailView(generics.GenericAPIView):
        renderer_classes = [TemplateHTMLRenderer]
        template_name = 'car-detail.html'
    
        queryset = Car.objects.all()
        lookup_field = Car.id
    
        def get(self, request, id):
            serializer_class = CarSerializer
            car = self.get_object()
            id = Car.id
    
            return Response({
                'car': car,
            })

但这会引发错误:

“属性错误位于/rentals/car/43 c9 b 98 d-9 f2 d-473 f-9 c34 - 7 b2 e25630278”汽车详细信息视图“对象没有属性”_meta“"

你能帮我解决这个问题吗?我已经看过了前面的大部分问题(这就是我学习将self传递到get函数等的地方...),但我仍然卡住了。
代码如下:

查看次数.py

class CarListView(generics.ListCreateAPIView):
    renderer_classes = [TemplateHTMLRenderer]
    template_name = 'car-list.html'

    def get(self, request):
        car_list = Car.objects.all()
        serializer_class = CarSerializer

        return Response({
            'car_list': car_list,
        })

class CarDetailView(generics.GenericAPIView):
    renderer_classes = [TemplateHTMLRenderer]
    template_name = 'car-detail.html'

    queryset = Car.objects.all()
    lookup_field = Car.id

    def get(self, request, id):
        serializer_class = CarSerializer
        car = self.get_object()
        id = Car.id

        return Response({
            'car': car,
        })

序列化程序.py

class CarSerializer(serializers.ModelSerializer):
    url = serializers.HyperlinkedIdentityField(view_name='rental:car-detail', format='html')

    class Meta:
        model = Car
        fields = ['url', 'id', 'manufacturer', 'model', 'owner', 'color', 'year']

模型.py

class Car(models.Model):
    manufacturer = models.ForeignKey(Manufacturer, on_delete=models.SET_NULL, null=True)
    model = models.ForeignKey(CarModel, on_delete=models.SET_NULL, null=True)
    # Model year. Validator ensures that no model year  can be set in the future. 
    year = models.IntegerField(validators=[MaxValueValidator(int(datetime.date.today().year) + 1)], null=True, default=2022)

    ...
    Other fields for drivetrain, engine etc
    ...

    # Fields for individual car in database
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, help_text="Automatically generated unique ID. Do not change.")
    mileage = models.IntegerField(null=True)
    
    insurance = models.ForeignKey(Insurance, on_delete=models.RESTRICT, null=True)

    daily_rate = models.IntegerField(default=3500, help_text="Daily rate in Kenyan Shillings")

    def __str__(self):
        return f'{ self.manufacturer } { self.model }'

    @property
    def insurance_expired(self):
        """Determines if insurance is expired based on due date and current date."""
        return bool(self.insurance.expiry_date and datetime.date.today() > self.insurance.expiry_date)

    class Meta:
        ordering = []
        permissions = (("can_change_availability", "Set car as rented"),)

    def get_absolute_url(self):
        return reverse('rental:car-detail', args=[str(self.id)])

网址.py

from django.urls import path, include 
from . import views

app_name = 'rental'

# API endpoints
urlpatterns = [
    path('', views.IndexView.as_view(), name='index'),
    path('cars/', views.CarListView.as_view(), name='car-list'),
    path('car/<uuid:id>', views.CarDetailView.as_view(), name='car-detail'),
]

错误代码

AttributeError at /rentals/car/43c9b98d-9f2d-473f-9c34-7b2e25630278
'CarDetailView' object has no attribute '_meta'
Request Method: GET
Request URL:    http://localhost:8000/rentals/car/43c9b98d-9f2d-473f-9c34-7b2e25630278
Django Version: 4.1.3
Exception Type: AttributeError
Exception Value:    
'CarDetailView' object has no attribute '_meta'
4zcjmb1e

4zcjmb1e1#

通常你 * 不 * 应该自己实现get()方法,这通常是Django(API)视图的任务,然后将它传递给正确的渲染器和模板。

class CarDetailView(generics.RetrieveAPIView):
    renderer_classes = [TemplateHTMLRenderer]
    template_name = 'car-detail.html'
    serializer_class = CarSerializer
    queryset = Car.objects.all()

然后,您可以在模板中使用汽车的字段,因此:{{ url }}{{ model }}{{ owner }}等等。
但是如果你打算渲染一个模板,使用**DetailView**[Django-doc]可能更有意义:

from django.views.generic.detail import DetailView

class CarDetailView(DetailView):
    model = Car
    template_name = 'car-detail.html'

在模板中,您可以使用{{ object.url }}{{ object.model }}等,也可以“遵循”关系。

相关问题