How django LoginRequiredMixin takes templates. I cound not find anything how it is taking the templates.
I had added account folder inside templates and then LoginRequiredMixin is taking my template but how it is wokring and how can i pass a context data to the template of login form
CodePudding user response:
LoginRequiredMixin does not render anythings. This mixin just redirect to LOGIN_URL set in settings by default. You can ovveride the url directly in class with this mixin like this:
class MyView(LoginRequiredMixin, View):
login_url = '...'
By default, login_url settings go to LoginView from django.contrib.auth.views and use the registration/login.html. So you can create a login.html in a registration directory in your templates dir for overriding just the default template used if you want
CodePudding user response:
What I had done is to pass context data to LoginRequiredMixin Template is shown below. Whether is it a right approach?.
urls.py
path('login_url/', views.CustomLogin.as_view(),name='login'),
views.py
class SettingsPage(LoginRequiredMixin, TemplateView):
login_url = '/login_url/'
class CustomLogin(TemplateView):
template_name = 'login.html'
def get_context_data(self, **kwargs):
context = super(CustomLogin, self).get_context_data(**kwargs)
context['redirect_field_name'] = 'next'
context['redirect_field_value'] = self.request.get_full_path().split('=')[1]
return context
login.html
<form method="POST" action="/accounts/login/">
{% csrf_token %}
<input type="hidden" name="{{ redirect_field_name }}" value="{{redirect_field_value}}">
<h4 >Login</h4>
<input type="text" name="login" id="id_login">
<input type="password" name="password" id="id_password">
<button type="submit" >Login</button>
</form>
Here it will automatically redirect to the redirect_field_value
after login