2012-01-17 12 views
18
私のコードは以下のちょっと作品

は、それがユーザーオブジェクトを作成し、保存しますが、それは、パスワードは保存されません:私はメタフィールドに「パスワード」を追加した場合django-tastypie APIを使用してプログラムでユーザーを登録または登録する方法は?

class CreateUserResource(ModelResource): 
    class Meta: 
     allowed_methods = ['post'] 
     object_class = User 
     authentication = Authentication() 
     authorization = Authorization() 
     include_resource_uri = False 
     fields = ['username'] 

    def obj_create(self, bundle, request=None, **kwargs): 
     try: 
      bundle = super(CreateUserResource, self).obj_create(bundle, request, **kwargs) 
     except IntegrityError: 
      raise BadRequest('That username already exists') 
     return bundle 

を、それが生のパスワードを保存しないではなく、それをハッシングする。私は間違って何をしていますか?


は、これが私の仕事です:

def obj_create(self, bundle, request=None, **kwargs): 
    username, password = bundle.data['username'], bundle.data['password'] 
    try: 
     bundle.obj = User.objects.create_user(username, '', password) 
    except IntegrityError: 
     raise BadRequest('That username already exists') 
    return bundle 
+1

最初にユーザーを作成せずに認証を行う方法は? – Burak

+0

RESTの原則を遵守するには、CreateUserResourceの代わりにクラスUserResourceを呼び出す必要があります。それが作成にのみ使用されているという事実はすでにallowed_methods属性で述べられており、クラス名の上にあるdocstringに追加することができます。 –

+0

@DavidW。作成とリスティングに異なる認証方法が必要な場合はどうすればよいでしょうか? – antonagestam

答えて

21

ユーザーを作成しますが、使用方法のどちらかがuser.set_password(bundle.data.get('password'))をset_passwordまたはユーザーオブジェクトのCREATE_USERメソッドを使用する必要があります。

user = User.objects.create_user(bundle.data.get('username'), bundle.data.get('email'), bundle.data.get('password')) 

だから、このようなものはあなたのために働くだろう:私は同じような状況にあったとの両方のソリューションは参考になりましたが、完了しないことが判明

def obj_create(self, bundle, request=None, **kwargs): 
    try: 
     bundle = super(CreateUserResource, self).obj_create(bundle, request, **kwargs) 
     bundle.obj.set_password(bundle.data.get('password')) 
     bundle.obj.save() 
    except IntegrityError: 
     raise BadRequest('That username already exists') 
    return bundle 
+0

私はこのhttp://www.psjinx.com/programming/2013/06/07/so-you-want-toのブログ記事を書いています-create-users-using-djangotastypie/ – pankaj28843

4

。両方とも、空のユーザー名でユーザーを作成することができました。私はそのようなリークを望んでいなかったのでここに私がしたことがあります。 UserResource

validation = FormValidation(form_class=UserForm) 

def obj_create(self, bundle, request=None, **kwargs): 
    bundle = super(UserResource, self).obj_create(bundle, request, **kwargs) 
    bundle.obj.set_password(bundle.data.get('password')) 
    bundle.obj.save() 

    return bundle 

の内側に、私は私の解決策は、他の開発者に役立つことを願って、その後

from django import forms 
from django.forms import ModelForm 
from django.contrib.auth.models import User 

class UserForm(forms.ModelForm): 
def __init__(self, *args, **kwargs): 
    super(UserForm, self).__init__(*args, **kwargs) 

    self.fields['username'].error_messages = {'required': "Please enter username"} 
    self.fields['username'].max_length = 30 
    self.fields['password'].error_messages = {'required': 'Please enter password'} 
    self.fields['password'].max_length = 30 

    self.fields['email'].required = False 

def clean_username(self): 
    username = self.cleaned_data['username'] 
    if len(username) < 4: 
     raise forms.ValidationError("Username has to be longer than 4 characters") 
    return username 

def clean_password(self): 
    password = self.cleaned_data['password'] 
    if len(password) < 5: 
     raise forms.ValidationError("Password has to be longer than 5 characters") 
    return password 

class Meta: 
    model = User 
    fields = ('username', 'email', 'password') 

まず、私は、検証フォームを作成しました。ハッピーコーディング!

2

私はdjango-tastypie == 0.9.12で同様のコードを使用しようとしていましたが、obj_createのクエリーセットと引数の数が不足しているというエラーが発生しました。次のコードを使用すると、私の仕事:

from django.contrib.auth.models import User 
from django.db import IntegrityError 

from tastypie.resources import ModelResource 
from tastypie.authorization import Authorization 
from tastypie.authentication import Authentication 
from tastypie import fields 
from tastypie.exceptions import BadRequest 

class UserSignUpResource(ModelResource): 
    class Meta: 
     object_class = User 
     resource_name = 'register' 
     fields = ['username', 'first_name', 'last_name', 'email'] 
     allowed_methods = ['post'] 
     include_resource_uri = False 
     authentication = Authentication() 
     authorization = Authorization() 
     queryset = User.objects.all() 

    def obj_create(self, bundle, request=None, **kwargs): 
     try: 
      bundle = super(UserSignUpResource, self).obj_create(bundle) 
      bundle.obj.set_password(bundle.data.get('password')) 
      bundle.obj.save() 
     except IntegrityError: 
      raise BadRequest('Username already exists') 

     return bundle 

いくつかのテストコードは次のようになります。

from django.contrib.auth.models import User 
from django.contrib.auth.hashers import check_password 

from tastypie.test import ResourceTestCase 

class UserSignUpResourceTest(ResourceTestCase): 
    def test_post_list(self): 
     post_arguments = { 
      "email": "[email protected]", 
      "first_name": "John", 
      "last_name": "Doe", 
      "username": "test-user", 
      "password": "idiotic-pwd" 
     } 
     # Check how many are there 
     self.assertEqual(User.objects.count(), 0) 
     self.assertHttpCreated(self.api_client.post('/api/register/', 
     format='json', data=post_arguments)) 
     # Check how many are there. Should be one more 
     self.assertEqual(User.objects.count(), 1) 
     # Check attributes got saved correctly 
     user = User.objects.get(username='test-user') 
     for atr in post_arguments: 
      if atr == 'password': 
       check_password(post_arguments[atr], getattr(user, atr)) 
      else: 
       self.assertEqual(post_arguments[atr], getattr(user, atr)) 
+0

この投稿には本当にありがとうございました.9.12用に作成したユーザーサインアップリソースを取得するのに非常に役立ちました –

関連する問題