Member of a CBV in Django
<p>I'm, trying to implement a LoginRequiredMixin. For example, if user goes to /post/6 and he isn't logged in, he is redirected to /auth/login/?next=/post/6. I'm trying to make a function that will redirect user either to /post/* (according to next in the url) or to the / if there is no next in the url. I tried to get a url param in GET request, save it to CBV member and then use it in post. But for some reasons it isn't actually saved. Here is a piece of my code:</p>

<pre><code>class LoginView(View):
    redirect_to = ''

    def post(self, request, *args, **kwargs):
        user = authenticate(username=request.POST['login'], password=request.POST['password'])
        print(self.redirect_to) # It's equal to '' here

        if user is not None:
            login(request, user)
        else:
            print("Account doesn't exists!")
        return HttpResponseRedirect(reverse('blog:index'))


    def get(self, request, *args, **kwargs):
        self.redirect_to = 'edited'

        form = RegistrationForm()
        return render(request, 'authorization/login.html', {
            'form': form
        })
</code></pre>

<p>Maybe there is any other solutions? Thanks in advance!</p>

<p>I think your safest bet is to use <a href="https://django-braces.readthedocs.io/" rel="nofollow"><code>braces</code></a>:</p>

<h2>Installation</h2>

<pre><code>$ pip install braces
</code></pre>

<h2>Usage</h2>

<p>The <a href="https://django-braces.readthedocs.io/en/latest/access.html#loginrequiredmixin" rel="nofollow"><code>LoginRequiredMixin</code></a> pretty much aims to replicate the <code>login_required</code> decorator functionality for CBVs:</p>

<pre><code>from django.views.generic import TemplateView

from braces.views import LoginRequiredMixin


class SomeSecretView(LoginRequiredMixin, TemplateView):
    template_name = "path/to/template.html"
    login_url = "/login/"

    def get(self, request):
        return self.render_to_response({})
</code></pre>

python django django-views