Milano
Milano

Reputation: 18735

How to allow only one User to see "UpdateView"?

I have a Users and Jobs. If some User creates a Job, then and only then he/she can edit some information of this Job.

So he visits the url .../job/update/<id>. If the Job is created by him (the User is a ForeignKey in Job, then he can modify data. Otherwise he gets 404 error.

In view function, I would probably get current Users id and compare this id to Jobs ForeignKey.

But there are many patterns and shortcuts in class views so I'm curious how to do that this way.

class EditOrderView(UpdateView):
    model = Job
    fields = ['language_from','language_to','level','short_description','notes',
              'text_to_translate','file']
    template_name = 'auth/jobs/update-order.html'


class Job(models.Model):
    customer = models.ForeignKey(User, related_name='orders', help_text=u"Zákazník")
    translator = models.ForeignKey(User, related_name='jobs', null=True, blank=True, help_text=u"Prekladateľ")
    price = models.FloatField(null=True, blank=True, help_text=u"Cena")

    language_from = models.ForeignKey(Language, related_name='jobs_from', null=True)
    language_to = models.ForeignKey(Language, related_name='jobs_to', null=True)
    ...

Upvotes: 3

Views: 53

Answers (1)

Ozgur Vatansever
Ozgur Vatansever

Reputation: 52163

It looks like you can override .get_object() method and include your own logic:

from django.shortcuts import get_object_or_404

class EditOrderView(UpdateView):
    model = Job
    ...

    def get_object(self, queryset=None):
        return get_object_or_404(self.model, pk=self.kwargs["pk"], customer=self.request.user)

Upvotes: 4

Related Questions