user1496093
user1496093

Reputation: 189

Django createview permissions

I have a createview for a model. The object it creates is based on a previous model having been entered.

How can I query the existence of that previous model prior to allowing the createview to be available please?

Many thanks

Upvotes: 1

Views: 1011

Answers (2)

user1496093
user1496093

Reputation: 189

Thanks for your reply. That does work, but was hoping to prevent the user submitting the form so as to not waste their time.

Have come up with this mixin that seems to do the job:

class CompanyTest(object):
    def dispatch(self, request, *args, **kwargs):
        if not Company.objects.filter(account=request.user).exists():
            return redirect('company-list')
        return super(CompanyTest, self).dispatch(request, *args, **kwargs)

Upvotes: 1

AlexW
AlexW

Reputation: 2591

Add form_valid to your view and check if the record exits before saving

class CreateObject(CreateView):
    ...
    def form_valid(self, form):
        # prevent initial save   
        self.object = form.save(commit=False)
        #query for existing record
        existing_record = Record.objects.filter(...)
        if existing_record:
            # send error message and redirect back to 
            messages.add_message(request, messages.ERROR, 'need existing objects...')
            return redirect('app:view') 
        else
            self.object.save()
            return HttpResponseRedirect(self.get_success_url())  

Upvotes: 1

Related Questions