如何在UpdateView(Django)中获取模型实例的属性?

2024-10-02 12:34:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个模型的更新视图。我想在UpdateView中获取(新车模型的)“car_owner”属性。这是密码。在

模型.py

class Newcars(models.Model):
    shop_no = models.ForeignKey(Shop, on_delete=models.CASCADE, default=0, related_name='newcars')
    car_name = models.CharField(max_length=250)
    car_owner = models.CharField(max_length=250)

    def get_absolute_url(self):
        return reverse('carapp:index')

    def __str__(self):
        return self.car_name + ' - ' +  self.car_owner

视图.py (这是更新视图。)

^{pr2}$

网址.py(仅限urlpatterns的必要部分)

url(r'^newcars/(?P<pk>[0-9]+)/$', views.NewcarUpdate.as_view(), name='newcar-update'),

这是我打算用UpdateView来做的,但是我不明白怎么做。在

class NewcarUpdate(UpdateView):
    model = Newcars
    fields = ['car_name', 'car_owner']
    #Get the selected newcar object's 'car_owner' attribute.
    #Check if the object's 'car_owner' attribute == "sometext" or not.
    #If matches, only then go the normal update form.
    #If doesn't, redirect to a 404 page.

Tags: thenamepy模型self视图modelscar
2条回答

您可以在get_object方法中这样做:

from django.http import Http404
# ...

class NewcarUpdate(UpdateView):
    # ...
    def get_object(self, queryset=None):
        obj = super(NewcarUpdate, self).get_object(queryset)
        if obj.car_owner == "sometext":
            raise Http404
        return obj

将此方法添加到视图中:

def dispatch(self, request, *args, **kwargs):
    if self.get_object().car_owner != "sometext":
        raise Http404('Car owner does not match.')
    return super(NewcarUpdate, self).dispatch(
        request, *args, **kwargs)

您需要从django.http导入Http404

相关问题 更多 >

    热门问题