【问题标题】:Django rest unsuccessful request from client来自客户端的 Django 休息不成功请求
【发布时间】:2016-07-24 05:36:08
【问题描述】:

我的 django 模型如下所示:

class ExhibitionSurveyObject(models.Model):
    owner = models.ForeignKey(User, verbose_name="Owner of this Survey object", blank=False,)
    name = models.CharField(max_length=15, blank=False, verbose_name="Survey Object name", help_text="Please give a single word name for your farm",)
    farmer_email = models.EmailField(max_length=254, blank=False, verbose_name="Email of the farmer", )
    farmer_name = models.CharField(max_length=25, blank=False, verbose_name="Name of the farmer", )
    address = models.TextField(help_text="Please provide the address without the postal code", blank=True,)
    postal_code = models.CharField(max_length=5, blank=True, default='12043')
    size = models.DecimalField(max_digits=9, decimal_places=6, blank=False, )
    path = models.CharField(max_length=1000, blank=False)
    def setpath(self, x):
        self.path = json.dumps(x)

    def getpath(self, x):
        return json.loads(self.path)

    OBJECT_TYPES = (
        ('FARM', 'Farm'),
        ('SOLARPANEL', 'Solarpanel'),
        ('PLAIN', 'plain')
        )
    object_type = models.CharField(max_length=100, choices=OBJECT_TYPES)
    CYCLES = (
        ('ONCE', 'once'),
        ('WEEKLY', 'weekly'),
        ('MONTHLY', 'monthly')
        )
    cycle = models.CharField(max_length=100, choices=CYCLES)

    #To add user's full name in the admin interface for better readability
    def get_owner_full_name(self):
        return self.owner.get_full_name()

    #Works like a verbose_name but for a method
    get_owner_full_name.short_description = 'Owners full name'

我有一个序列化程序:

class ExhibitionSurveyObjectSerializer(serializers.ModelSerializer):

    class Meta:
        model = ExhibitionSurveyObject
        fields = '__all__'

    def create(self, validated_data):
        return ExhibitionSurveyObject.objects.create(**validated_data)

    def update(self, instance, validated_data):
        instance.name = validated_data.get('name', instance.name)
        instance.farmer_email = validated_data.get('farmer_email', instance.farmer_email)
        instance.farmer_name = validated_data.get('farmer_name', instance.farmer_name)
        instance.address = validated_data.get('address', instance.address)
        instance.postal_code = validated_data.get('postal_code', instance.postal_code)
        instance.size = validated_data.get('size', instance.size)
        instance.path = validated_data.get('path', instance.path)
        instance.object_type = validated_data.get('object_type', instance.object_type)
        instance.cycle = validated_data.get('cycle', instance.cycle)
        instance.save()
        return instance

我的表格:

class ExhibitionSurveyObjectForm(forms.ModelForm):
    owner = CustomUserChoiceField(queryset=User.objects.all())
    class Meta:
        model = ExhibitionSurveyObject
        fields = "__all__"

我的看法:

class ExhibitionSurveyObjectList(generics.ListCreateAPIView):
    queryset = ExhibitionSurveyObject.objects.all()
    serializer_class = ExhibitionSurveyObjectSerializer

    def perform_create(self, serializer):
    serializer.save(owner=self.request.user) 

我有一个 Ionic2 前端,我的服务具有以下功能来保存上述模型的实例:

addObject(

    name: string, 
    farmer_email: string,
    farmer_name: string,
    size: string,
    path: Array<google.maps.LatLngLiteral>, 
    cycle: string, 
    object_type: string) {
    let obj = new ExhibitionSurveyObjectModel(name, farmer_email, farmer_name, size, path, cycle, object_type);

    let body = JSON.stringify(obj);
    let headers = new Headers({ 'Content-Type': 'application/json; charset=utf-8', 'Authorization': 'Token ' + localStorage.getItem('auth_token') });
    let options = new RequestOptions({ headers: headers });
    console.log(body);
    return this.http.post(this._exhibitionSurveyObjectURL, body, options)
                    .map(this.extractData)
                    .catch(this.handleError)
  }

我的客户端也有一个模型:

export class ExhibitionSurveyObjectModel {
  constructor(
    public name: string, 
    public farmer_email: string,
    public farmer_name: string,
    public size: string,
    public path: Array<google.maps.LatLngLiteral>, 
    public cycle: string, 
    public object_type: string, 
    public owner: string
    ){}
}

我可以看到令牌被发送到后端,但是我收到了一个回复说{"owner":["This field is required."]}

发送令牌还不够吗?如果我还必须从我的服务请求中传递 'owner' 应该是什么价值(但是,我想令牌应该足够了)?

或者我在后端遗漏了什么?

【问题讨论】:

    标签: django angular django-rest-framework


    【解决方案1】:

    我的猜测是问题在于您错误地创建了序列化程序。您特别指示使用 __all__ 字段,这意味着所有字段。与此无关,但您不应该真的需要在 Model serielizer 上创建或更新。

    相反,尝试这样的事情

    class ExhibitionSurveyObjectSerializer(serializers.ModelSerializer):
        class Meta:
            model = ExhibitionSurveyObject
            fields = ('name', 'farmer_email', 'farmer_name', 'address', 
                      'postal_code', 'size', 'path', 'object_type', 
                      'cycle')
            read_only_fields = ('owner', )
    

    这应该就是你所需要的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-04-04
      • 2021-09-11
      • 1970-01-01
      • 1970-01-01
      • 2017-09-28
      • 2017-05-17
      • 1970-01-01
      相关资源
      最近更新 更多