I am making a web application with Django 2.0 and I need to control that when displaying a template it only does so if the user is logged in, because currently without being logged in I can access the system by writing the URLs by hand.
I understand that it is to check if the request request has an associated user, but I don't know in which method to do it.
My views.py :
class CoinsPageView(TemplateView):
template_name = 'coins.html'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
return context
def post(self, request, *args, **kwargs):
pass
def actualice(self):
coinmarketcap = Market()
for coin in Coin.objects.all():
data = coinmarketcap.ticker(coin.cid, convert='EUR')
coin.price = float(data['data']['quotes']['EUR']['price'])
coin.market_cap = int(data['data']['quotes']['EUR']['market_cap'])
coin.volume = int(data['data']['quotes']['EUR']['volume_24h'])
coin.circulating = int(data['data']['circulating_supply'])
coin.change = float(data['data']['quotes']['EUR']['percent_change_1h'])
coin.save()
return HttpResponse('OK')
It is very simple. You simply have to inherit from
LoginRequiredMixin
in your view:By using this mixin you ensure that all requests validate that the user is authenticated. If they are not, then they are redirected to login to start their session. By default, redirection is used using what you have defined in
settings.LOGIN_URL
but it is possible to override it usinglogin_url
in your view:Django recommends several ways to do this, it is necessary to tell each view that it will need a user to display the content, or else it will default to the login page in order to see the content. These are some of them:
This is another:
This is another:
Another way is to create your own mixin and have all your views inherit from that mixin. This only applies when we talk about classes, when your views are functions, it's similar, the decorator goes directly to the function