我正在尝试向我的django rest api提交帖子,但我得到一个误导性的400 Bad Request。当我查看django rest api文档http://www.django-rest-framework.org/api-guide/relations/时,似乎他们不允许该模型不允许Post请求提交外键。但是,我在snapcapsule模型中发布链接到的用户。我尝试提交用户喜欢成功用户帖子请求的链接。
在制作relatedHyperLink字段Snapcapsule时,UserSerializing中也出现错误。错误说,"用户对象没有属性snapcapsule。"同样,引用早期的文档链接,Album没有Track的属性。
models.py
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
def user_directory_path(instance, filename):
# file will be uploaded to MEDIA_ROOT/user_<id>/<filename>
return 'images/user_{0}/{1}'.format(instance.user.id, filename)
class SnapCapsule(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
dateToPost = models.DateTimeField()
image = models.FileField(upload_to=user_directory_path)
def delete(self, *args, **kwargs):
# You have to prepare what you need before delete the model
storage, path = self.song.storage, self.song.path
# Delete the model before the file
super(SnapCapsule, self).delete(*args, **kwargs)
# Delete the file after the model
storage.delete(path)
Serializers.py
class UserSerializer(serializers.HyperlinkedModelSerializer):
snapcapsules = serializers.HyperlinkedRelatedField(
many=True,
read_only=True,
view_name='snapcapsules-detail'
)
class Meta:
model = User
fields = ('snapcapsules', 'url', 'username', 'email', 'password')
write_only_fields = ('password',)
def create(self, validated_data):
user = User.objects.create(
username=validated_data['username'],
email=validated_data['email'],
)
user.set_password(validated_data['password'])
user.save()
return user
class SnapCapsuleSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = SnapCapsule
fields = ('user', 'dateToPost', 'image')