Search code examples
pythondjangorestful-architecturedjango-rest-framework

Django Rest Framework


I have a method that grabs POST data that is formated in json format like this

[{"UserName": "alexgv", "Password": "secretpassword"}]

Here is the method

def Login(request, *args):
    data = request.DATA
    return Response(data)
"""
try:
    m = User.objects.get(UserName=request.DATA['UserName'])
    if m.password == request.DATA['Password']:
        request.session['member_id'] = m.id
        return HttpResponse("Testing")
except User.DoesNotExist:
    return HttpResponse("Your username and password didn't match.")
""" 

I want to be able to take just one variable from that json POST. For example, maybe I just want to grab the UserName or Password. How would I do that? I have tried a variety of things but cant seem to get it to work, and I dont want to use request.POST.get because then that means I would have to send POST variables. BTW I am using this http://django-rest-framework.org/. I have read through the docs but cant seem to find anything in there. Any help is appreciated. What it returns right now is everything.


Solution

  • Like so...

    username = request.DATA['UserName']
    

    Incidentally, you probably shouldn't be writing session based API login views yourself as it's easy to do wrong.

    For APIs that provide AJAX style functionality the you have two good options:

    • Login using a standard Django login, performed by the user, not performed by the API client.
    • Use a credentials based authentication scheme, rather than session based, and perform the login using AJAX. For example the Djoser third party package is a great library including token-based login and other similar views... https://github.com/sunscrapers/djoser

    Update Also discovered https://github.com/JamesRitchie/django-rest-framework-sav which might be worth a look for AJAX session based authentication.