Python Angular 4中的过账表单数据在Django中以字节形式接收
我正在尝试在前端使用Angular 4,在后端使用Django构建一个完整的堆栈web应用程序。我在Angular中创建了一个被动表单,并将其提交到一个后端API,该API链接在Django URL.py中。完整代码在我的GitHub repo上: 角度分量代码有:Python Angular 4中的过账表单数据在Django中以字节形式接收,python,django,angular,Python,Django,Angular,我正在尝试在前端使用Angular 4,在后端使用Django构建一个完整的堆栈web应用程序。我在Angular中创建了一个被动表单,并将其提交到一个后端API,该API链接在Django URL.py中。完整代码在我的GitHub repo上: 角度分量代码有: newCompanyForm: FormGroup = new FormGroup({ 'name': this.name, 'headquarters': this.headquarters, 'address': t
newCompanyForm: FormGroup = new FormGroup({
'name': this.name,
'headquarters': this.headquarters,
'address': this.address,
'company_website': this.company_website,
'established_year': this.established_year
});
addCompany() {
console.log(this.newCompanyForm.value);
this.http.post(this.apiBaseURL + 'new-company',
JSON.stringify(this.newCompanyForm.value)).subscribe(
response => {
console.log(response);
},
errors => {
console.log(errors);
}
);
}
其中,使用表单的ngSubmit调用addCompany()。角度形式是Django模型的镜像,即:
class Company(models.Model):
name = models.CharField(default='Google', max_length=200)
headquarters = models.CharField(default='San Jose, California', max_length=200)
address = models.CharField(default='123 River Drive, San Jose, California', \
max_length=500, blank=True, null=True)
company_website = models.URLField(default='http://www.google.com', \
blank=True, null=True)
established_year = models.IntegerField(default=2000, blank=True, null=True)
def __str__(self):
return str(self.name) + " in " + str(self.headquarters)
def __unicode__(self):
return str(self.name) + " in " + str(self.headquarters)
我创建了一个简单的基于类的视图来接收表单数据:
@method_decorator(csrf_exempt, name='dispatch')
class NewCompany(View):
def get(self, request):
return JsonResponse({"message": "Hello world"})
def post(self, request):
new_company_data = json.loads(request.body.decode('utf-8'))
new_company = Company(**new_company_data)
new_company.save()
return HttpResponse("Done");
目前,我并不担心CSRF令牌,我还分别运行Angular和Django服务器。问题是post数据在Django中以字节字符串的形式出现,并且仅出现在request.body中。request.POST是。我使用JSON.stringify()只是将其转换为嵌入字符串中的JSON。为了将其插入模型实例,我使用decode,然后使用json.loads()将其转换为json数据
我做错什么了吗?是否有一种方法可以更方便地提取POST数据。我以前使用Django模板,但自从我学习Angular 4后,我尝试将它们混合使用。我认为您可能从Angular方面做错了。。。您使用的是表单而不是对象?但我不太熟悉angular…我至少会检查Django接收的请求是否具有
内容类型
:应用程序/json
。我尝试检查内容类型,但它给了我一个方法列表。我检查了request.META,但它也没有内容类型。我看到了这个帖子。这和我面临的问题完全一样。看起来这是获取表单数据的唯一方法。