我有一个模型的UpdateView。我想得到'car_owner' UpdateView中的属性(Newcars模型)。这是代码。
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.
答案 0 :(得分:1)
将此方法添加到您的视图中:
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
答案 1 :(得分:1)
您可以使用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