0

我正在使用 django rest API。

这是代码:

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

if ('user_name' not in profile or 'email_address' not in profile or 'oauth_secret' not in profile):
    return Response(
        {'error': 'No data'},
        status=status.HTTP_400_BAD_REQUEST)

username = 'l' + profile['user_name']
email_address = profile['email_address']
oauth_secret = profile['oauth_secret']
password = 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'] = username
user_form['password1'] = password
user_form['password2'] = password
user_form['email'] = email_address
user_form['first_name'] = firstname
user_form['last_name'] = lastname

photo = None
noConnections = 0

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

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

try:
    user = User.objects.get(username=username)
except User.DoesNotExist:
    usercreate = UserCreateForm(user_form)

    if usercreate.is_valid():
        usernamet = usercreate.clean_username()
        passwordt = usercreate.clean_password2()
        user = usercreate.save()
        userprofile = user.get_profile()

        p_form = dict()

        if bio:
            p_form['bio'] = bio

        if photo:
            p_form['photo_url'] = photo

        if noConnections:
            p_form['noConnections'] = noConnections

        if oauth_token:
            p_form['oauth_token'] = oauth_token

        if oauth_secret:
            p_form['oauth_secret'] = oauth_secret

        profileform = UserProfileForm(p_form, instance=userprofile)

        if profileform.is_valid():
            profileform.save()

        user = authenticate(username=usernamet, password=passwordt)

        if user is not None:
            login(request, user)
        else:
            return Response(
                None,
                status=status.HTTP_400_BAD_REQUEST)

    else:
        return Response(
            usercreate.errors,
            status=status.HTTP_400_BAD_REQUEST)

# if Investor: #send_mail( #'请填写您的创业资料', #'这是消息。', #'from@example.com', #list(email_address))

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

每当我向该代码部分发送帖子时,都会收到以下错误:CSRF 失败:未设置 CSRF cookie。

我能做些什么?

4

1 回答 1

3

你看过关于它的文档吗?这里 !.

也许你忘了写{% csrf_token %}表单后的 html 标签:

例如表单文档:

<form action="." method="post">{% csrf_token %}
于 2013-05-09T13:16:30.417 回答