开发者

Trouble with Django, request and logging in?

开发者 https://www.devze.com 2023-01-28 11:42 出处:网络
Hey All- I\'m completely new to Django/python and am going through a tutorial for a class, located here. I\'ve got most of this working, but I\'m having trouble. I can register a user, but seemingly c

Hey All-

I'm completely new to Django/python and am going through a tutorial for a class, located here. I've got most of this working, but I'm having trouble. I can register a user, but seemingly cannot login. For t开发者_如何学Gohe relevant part of the tutorial, search for the line We’ll need one more form, a login form: which explains how to implement the login form. I did this and the form works and I can "login" and I do get a session cookie on the client.

The problem is, if you scroll down a little more, you'll see We should add a welcome message and login/logout links to our templates: which explains how to show a user a welcome message if they're logged in, or a login link if they're not. Problem is, after logging in, I still get a login link!

Now, the tutorial explains this. It says I need to do two things: 1) Put the following code in my settings.py file

TEMPLATE_CONTEXT_PROCESSORS = [
    "django.core.context_processors.request"
]

2) Create a file called middleware.py which will set the request.user value. I've done this and restarted my server but I still have my same problem. (The code is in the tutorial, but I'll paste here too for simplicity):

from users.models import User
class UserMiddleware(object):
    def process_request(self, request):
        user_id = request.session.get("user_id")
        if user_id is not None:
            request.user = User.objects.get(pk=user_id)
        else:
            request.user = None

I tried changing the syntax on that first part a bit to the below:

TEMPLATE_CONTEXT_PROCESSORS = (
    "django.core.context_processors.request",
)

which better matched the other lines in settings.py, but this didn't help either.

I know this is a huge wall of text, but can someone point me in the right direction? This itself is not an assignment, just a tutorial for a later assignment, so help is really appreciated!


Have you added your new middleware class to the MIDDLEWARE_CLASSES list in settings.py?


In real life, you'd use django.contrub.auth for login/authentication.

It looks you don't set request.session["user_id"] to user.pk. As I see, this is done in the login view in the tutorial. Is your login view exactly the same as in tutorial? Do you have method="post" in your login form?

0

精彩评论

暂无评论...
验证码 换一张
取 消