2013-05-09 137 views
3

我有以下代碼。Django Rest Framework用戶認證

我正在使用django rest框架。

我基本上想讓用戶註冊。 我通過POST發送電子郵件地址,密碼,用戶名。

我只是覺得我沒有正確使用django rest框架。

你們可以幫我一下嗎?

構建它以遵循django rest框架原則的最佳方式是什麼?

另外,下面的表格是無效的...我如何發佈錯誤信息回來?

@api_view(['POST']) 
def user_login(request): 

profile = request.POST 

if ('id' not in profile or 'email_address' not in profile or 'oauth_secret' not in profile): 
    return Response(
     status=status.HTTP_204_NO_CONTENT) 

identifier = profile['id'] 
email_address = profile['email_address'] 
oauth_secret = profile['oauth_secret'] 

firstname = None 
if 'first_name' in profile: 
    firstname = profile['first_name'] 

lastname = None 
if 'last_name' in profile: 
    lastname = profile['last_name'] 

bio = None 
if 'bio' in profile: 
    bio = profile['bio'] 

oauth_token = None 
if 'oauth_token' in profile: 
    oauth_token = profile['oauth_token'] 

investor = None 
if 'investor' in profile: 
    investor = profile['investor'] 

user_form = dict() 
user_form['username'] = 'l' + identifier 
user_form['password1'] = oauth_secret 
user_form['password2'] = oauth_secret 
user_form['email'] = email_address 

photo = None 
noConnections = 0 

if 'pictureUrl' in profile: 
    photo = profile['pictureUrl'] 

if 'numConnections' in profile: 
    noConnections = profile['numConnections'] 

try: 
    user = User.objects.get(username=identifier) 
except User.DoesNotExist: 
    serializer = UserRegisterSerializer(data=user_form) 

    if serializer.is_valid(): 
     user = serializer.save() 

     user.first_name = firstname 
     user.last_name = lastname 
     user.save() 

     # Save our permanent token and secret for later. 
     userprofile = user.get_profile() 
     userprofile.bio = bio 
     userprofile.photo = photo 
     userprofile.no_linked_con = noConnections 
     userprofile.oauth_token = oauth_token 
     userprofile.oauth_secret = oauth_secret 
     userprofile.save() 
    else: 
     return Response(
      serializer.errors, 
      status=status.HTTP_400_BAD_REQUEST) 

user = authenticate(username=identifier, password=oauth_secret) 
login(request, user) 

if not investor: 
    send_mail(
     'Please complete your startup profile', 
     'Here is the message.', 
     'from[email protected]', 
     list(email_address)) 

serializer = UserSerializer(user) 
return Response(serializer.data) 

回答

0

首先閱讀關於Working with forms的Django文檔。您可以爲所有表單字段創建一個類,並且Django將從它創建一個HTML表單,解析POST參數並幫助處理錯誤消息。

相關問題