gpt4 book ai didi

python - Django Rest Framework 用户身份验证

转载 作者:行者123 更新时间:2023-11-28 19:29:47 34 4
gpt4 key购买 nike

我有以下代码。

我正在使用 django 休息框架。

我基本上是想让用户注册。我通过 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)

最佳答案

首先阅读关于 Working with forms 的 Django 文档.您可以为所有表单字段创建一个类,Django 将从中创建一个 HTML 表单,解析 POST 参数,并帮助处理错误消息。

关于python - Django Rest Framework 用户身份验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16452285/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com