Domanda

I am creating an application in Django. I have a model called Business_profile having User as foreign key. Now what I want is every time a user logs in the application, i want to display following hyper links in the base template:

1) If entry in Business_profile exists :

Show links:

  • HOME
  • BUSINESS PAGE

2) If entry in Business_profile does not exist:

  • HOME
  • ADD BUSINESS

Now I know query would be Business_profile.objects.filter(user=user_obj).exists()

But I want to check this when the user logs in, how to do this? Is there a way to override login view? Please help. Thanks.

È stato utile?

Soluzione

Django provides a signal user_logged_in whenever a user logs in. You could register to listen to that signal and do your stuff when you get the signal.

from django.contrib.auth.signals import user_logged_in

def do_my_stuff(sender, user, request, **kwargs):
    whatever actions you want to to go here

user_logged_in.connect(do_my_stuff)

Altri suggerimenti

This is really very easy in django with its authorization feature look at the following link:

http://www.djangobook.com/en/2.0/chapter14.html?

    if 'password' in request.POST and 'username' in request.POST:
         user = auth.authenticate(username=request.POST['username'], password=request.POST['password'])
    if user is not None and user.is_active:
        auth.login(request,user)
        #do your queries here
        return render(request,'htmlpage.html',{'data':data}

Not that sure about the thing your up to but here's what your question makes me guess.

If you point the user to a login page both with a direct link or through a @login_required decorator on a view, you can have her redirected to the URL set in your settings file under LOGIN_REDIRECT_URL or the one in the next parameter in your POST request (which takes precedence).

That said, what takes place after the POST submission is a GET request for the page under one of these URL. If your Business_profile model depends on the user being authenticated I would simply check for user authentication for showing the links HOME and ADD BUSINESS while the user is not authenticated.

When she logs in you should take care of passing your views the Business_profile object to tackle with in the rendered template. But if I correctly understood you shouldn't need to manage this in the login view, it should be arranged for in all the views for which the user has been already authenticated.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top