How to get model instance's attribute in UpdateView (Django)?
<p>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.</p>

<p><strong><em>models.py</em></strong></p>

<pre><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
</code></pre>

<p><strong><em>views.py</em></strong>
(Here's the UpdateView.)</p>

<pre><code>class NewcarUpdate(UpdateView):
    model = Newcars
    fields = ['car_name', 'car_owner']
</code></pre>

<p><strong><em>urls.py</em></strong> (only the necessary part of the urlpatterns)</p>

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

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

<pre><code>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.
</code></pre>

<p>You could that in the <a href="https://docs.djangoproject.com/en/1.10/ref/class-based-views/mixins-single-object/#django.views.generic.detail.SingleObjectMixin.get_object" rel="nofollow">get_object</a> method:</p>

<pre><code>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
</code></pre>

python django python-2.7 python-3.x