Douche Tholi Douche Tholi - 11 months ago 53
Python Question

How to get model instance's attribute in UpdateView (Django)?

I have an UpdateView for a model. I want to get the 'car_owner' attribute (of the Newcars model) in the UpdateView. Here's the code.

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
(Here's the UpdateView.)

class NewcarUpdate(UpdateView):
model = Newcars
fields = ['car_name', 'car_owner'] (only the necessary part of the urlpatterns)

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

This is what I intend to do with the UpdateView, but cannot understand how.

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.

Answer Source

add this method to your view:

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)

You will need to import Http404 from django.http