Django Rest Framework 用户认证

3
我有以下代码。
我正在使用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@example.com',
        list(email_address))

serializer = UserSerializer(user)
return Response(serializer.data)
2个回答

0

首先阅读Django文档中关于处理表单的部分。你可以为所有的表单字段创建一个类,Django会根据它自动生成一个HTML表单,并解析POST参数,并提供错误信息的帮助。


-1
class UserRegistrationSerializer(serializers.Serializer):
    email = serilaizers.EmailField()
    username = serializers.CharField(max_length=255) # max_length is optional if you give it validate the length of character's set
    password = serializers.CharField(max_length=255, write_only=True)

    def validate(attrs): # attrs is dictionary such as {'email':'example@m.com', 'username':'tom', 'password': 'test_password'}
        # process your required validation here such as checking unique, etc
        return attrs

    def create(self, validated_data):
        password = validated_data.pop('password')
        instance = User(**validated_data)
        instance.set_password(password)
        instance.save() # before saving you can do any data manipulation
        return instance

在视图中:

serializer = UserRegistrationSerializer(data=request.data)
serializer.is_valid(raise_exception=True/False)
serializer.save()
return Response(serilaizer.data, status.201) # here you should import Response and status from rest-framework path and you can return anything

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接