Micah Pearce
Micah Pearce

Reputation: 1965

Django: redirect from page if model field is certain value

I have a Class-based-view that sends a user to a webpage to view an item. The user can click on the edit button to edit the page, however, I don't want the user to always be able to edit the page. Once a field ('status') in a model has been set to 'completed', I'd like the user to no longer be able to update the page. I have a class based view. How do I redirect the user to a different url, (e.g. the view url) if the status=completed? My current approach is to have a form that errors if the field status is set to completed. It's not ideal since the person still sees the edit an may wonder why it is erroring out.

urls.py

url(r'^update/(?P<status_id>[0-9A-Za-z]+)/$', ThingUpdateView.as_view(), name='update'),

class based view

class ThingUpdateView(LoginRequiredMixin, UpdateView):
    model      = Thing
    form_class = ThingChangeForm
    template_name = 'thing/thing_update.html'

Upvotes: 0

Views: 320

Answers (2)

neverwalkaloner
neverwalkaloner

Reputation: 47374

Try to override render_to_response method to handle GET requests and form_valid to handle POST and PUT:

from django.shortcuts import redirect

class ThingUpdateView(LoginRequiredMixin, UpdateView):
    model      = Thing
    form_class = ThingChangeForm
    template_name = 'thing/thing_update.html'

    def render_to_response(self, context, **response_kwargs):
        if self.object.status == 'completed':
            return redirect('some-view-name') 
        return super().render_to_response(context, **response_kwargs) 

    def form_valid(self, form):
        if self.object.status == 'completed':
            return redirect('some-view-name') 
        return super().form_valid(form)

Upvotes: 3

Rajat Jain
Rajat Jain

Reputation: 1415

One approach can be that you use Javascript for this purpose. Set the value of the form element to "completed" and run the JS function window.location() to redirect the user if the value is set to "completed".

Upvotes: 0

Related Questions