使用POSt访问django API代码时出现CSRF错误

时间:2013-05-09 13:08:48

标签: python django django-rest-framework

我正在使用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投资者:         #发邮件(             #'请填写您的启动资料',             #'这是留言。',             #'from@example.com”,             #list(EMAIL_ADDRESS))

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

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

我该怎么办?

1 个答案:

答案 0 :(得分:3)

你看到有关它的文件了吗? Here !

也许你忘记在表格html标签后写{% csrf_token %}

e.g。表单文档:

<form action="." method="post">{% csrf_token %}