我有一个模型的UpdateView。我想在UpdateView中获取(Newcars模型的)“ car_owner”属性。这是代码。
models.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
views.py
(这是UpdateView。)
class NewcarUpdate(UpdateView):
model = Newcars
fields = ['car_name', 'car_owner']
urls.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.
最佳答案
将此方法添加到您的视图:
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)
您将需要从
Http404
导入django.http
关于python - 如何在UpdateView(Django)中获取模型实例的属性?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/39496041/