使用HTTP请求向Django Rest框架发布离子框架

时间:2017-12-08 09:49:10

标签: python django ionic-framework

我尝试使用Django作为后端在我的Ionic应用中创建新用户。到目前为止,我可以使用Postman创建用户没有问题,但是当我尝试通过我的应用程序发出HTTP post请求时,我收到以下错误:{"password":["This field is required."],"username":["This field is required."]}。我将usernamepassword字段传递给我的Django应用程序,但由于某种原因它没有注册它。我的电话是错的吗?

DJANGO APP CODE

serializers.py

class UserSerializer(serializers.ModelSerializer):
    password = serializers.CharField(write_only=True)
    languages = serializers.ListField(child=serializers.CharField(max_length=30, allow_blank=True), source="userprofile.languages")

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

    def create(self, validated_data, instance=None):
        profile_data = validated_data.pop('userprofile')
        user = User.objects.create(**validated_data)
        user.set_password(validated_data['password'])
        user.save()
        UserProfile.objects.update_or_create(user=user, **profile_data)
        return user

views.py

@api_view(['POST'])
@permission_classes((AllowAny,))
def create_user(request):
    serialized = UserSerializer(data=request.data)
    if serialized.is_valid():
        serialized.save()
        return Response(serialized.data, status=status.HTTP_201_CREATED)
    else:
        return Response(serialized._errors, status=status.HTTP_400_BAD_REQUEST)

IONIC APP CODE

http.ts

  register(username, password, email, first_name, last_name, languages) {
    let url = "https://www.example.com/api/create_user/";
    let headers = new Headers()
    headers.append("Content-Type", "application/x-www-form-urlencoded");

    return this.http.post(url,
      {"first_name": first_name,
        "last_name": last_name,
        "email": email,
        "username": username,
        "password": password,
        "languages": languages
      }, {headers: headers})
      .map(res => res.json());
  }

register.ts

import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';

import { HttpProvider } from "../../providers/http/http";

@IonicPage()
@Component({
  selector: 'page-register',
  templateUrl: 'register.html',
})
export class RegisterPage {

  //basic info
  username:any;
  email:any;
  fname:any;
  lname:any;
  password:any;
  passwordConfirm:any;
  languages:any = [];
  cantonese:any;
  french:any;
  german:any;
  italian:any;
  japanese:any;
  korean:any;
  mandarin:any;
  portuguese:any;
  russian:any;
  spanish:any;

  constructor(public navCtrl: NavController, public navParams: NavParams, private http: HttpProvider) {
  }

  ionViewDidLoad() {
    console.log('ionViewDidLoad RegisterPage');
  }

  register() {
    if(this.cantonese) {
      this.languages.push("Cantonese")
    }
    if(this.french) {
      this.languages.push("French")
    }
    if(this.german) {
      this.languages.push("German")
    }
    if(this.italian) {
      this.languages.push("Italian")
    }
    if(this.japanese) {
      this.languages.push("Japanese")
    }
    if(this.korean) {
      this.languages.push("Korean")
    }
    if(this.mandarin) {
      this.languages.push("Mandarin")
    }
    if(this.portuguese) {
      this.languages.push("Portuguese")
    }
    if(this.russian) {
      this.languages.push("Russian")
    }
    if(this.spanish) {
      this.languages.push("Spanish")
    }
    alert(this.username+" "+this.password);
    this.http.register(this.username,
      this.password,
      this.email,
      this.fname,
      this.lname,
      this.languages).subscribe((stuff) => {
      console.log(stuff);
    });
  }

}

的package.json

{
  "name": "project_name",
  "version": "0.0.1",
  "author": "Ionic Framework",
  "homepage": "http://ionicframework.com/",
  "private": true,
  "scripts": {
    "clean": "ionic-app-scripts clean",
    "build": "ionic-app-scripts build",
    "lint": "ionic-app-scripts lint",
    "ionic:build": "ionic-app-scripts build",
    "ionic:serve": "ionic-app-scripts serve"
  },
  "dependencies": {
    "@angular/common": "5.0.1",
    "@angular/compiler": "5.0.1",
    "@angular/compiler-cli": "5.0.1",
    "@angular/core": "5.0.1",
    "@angular/forms": "5.0.1",
    "@angular/http": "5.0.1",
    "@angular/platform-browser": "5.0.1",
    "@angular/platform-browser-dynamic": "5.0.1",
    "@ionic-native/core": "4.4.0",
    "@ionic-native/splash-screen": "4.4.0",
    "@ionic-native/status-bar": "4.4.0",
    "@ionic/storage": "2.1.3",
    "ionic-angular": "3.9.2",
    "ionicons": "3.0.0",
    "rxjs": "5.5.2",
    "sw-toolbox": "3.6.0",
    "zone.js": "0.8.18"
  },
  "devDependencies": {
    "@ionic/app-scripts": "3.1.2",
    "typescript": "2.4.2"
  },
  "description": "An Ionic project"
}

1 个答案:

答案 0 :(得分:0)

您想将django视图中的request.data更改为request.POST

详细信息:http://www.django-rest-framework.org/tutorial/2-requests-and-responses/

特别是

request.POST  # Only handles form data.  Only works for 'POST' method.
request.data  # Handles arbitrary data.  Works for 'POST', 'PUT' and 'PATCH' methods.