Make view accessible only through redirect and from only one view in Django
<p>How do I make a view to be only accessible through <em>redirect</em> and from a only a particular <em>view</em>?</p>

<p><strong>urls.py</strong>:</p>

<pre><code>#Assuming namespace = 'myApp'

url(r'^redarekt/$', views.redarekt, name='redarekt'),
url(r'^reciva/$', views.reciva, name='reciva'),
</code></pre>

<p><strong>views.py</strong>:</p>

<pre><code>@login_required()
def redarekt(request):
    if request.user.is_authenticated() and request.user.is_active:
        return HttpResponseRedirect(reverse('myApp:reciva'))


@login_required()
def reciva(request):
    if request.user.is_authenticated() and request.user.is_active:
        #CHECK IF IT IS A REDIRECT AND COMING FROM redarekt
            execute(request)
        raise Http404
    raise Http404
</code></pre>

<p>How do I make <code>reciva</code> to be only accessible through <em>redirect</em> and from a only <code>redarekt</code>?</p>

<p>You can use <a href="https://docs.djangoproject.com/en/1.10/topics/http/sessions/#using-sessions-in-views" rel="nofollow"><code>request.session</code></a></p>

<pre><code>@login_required()
def redarekt(request):
    if request.user.is_authenticated() and request.user.is_active:
        request.session['pp_redarekt'] = True
        return HttpResponseRedirect(reverse('myApp:reciva'))


@login_required()
def reciva(request):
    if request.user.is_authenticated() and request.user.is_active:
        if 'pp_redarekt' in request.session:
            execute(request)
            del request.session['pp_redarekt']
        raise Http404
    raise Http404
</code></pre>

<p><code>'pp_redarekt'</code> stands for Previous Page 'redarekt'</p>

<p>So basically, before redirecting to <code>reciva(request)</code> view you're setting adding session key, that says that previous page was <code>redarekt</code>. When you handle your request in <code>reciva</code> view, you are deleting that key, so user won't be able to enter <code>reciva</code> twice or more.</p>

<p>But for doing so, you need to setup your sessions. <a href="https://docs.djangoproject.com/en/1.10/topics/http/sessions/" rel="nofollow">Guide and docs</a></p>

python django