Reputation: 311
I'm trying to save on model using POST which has foreign key. Until I set 'add', 'modify' permissions to related model it returns 401 unauthorized. Simple example: models.py
class AnotherModel(models.Model):
field = models.TextField()
class MyModel(models.Model):
foreign_key = models.ForeignKey(AnotherModel)
resources.py
class AnoterResource(ModelResource):
class Meta:
queryset = AnoterModel.objects.all()
resource_name = 'another'
authorization = DjangoAuthorization()
authentication = ApiKeyAuthentication()
class MyModelResource(ModelResource):
foreign = fields.ToOneField(AnoterResource, 'foreign_key')
class Meta:
queryset = MyModel.objects.all()
authorization = DjangoAuthorization()
authentication = ApiKeyAuthentication()
allowed_methods = ['get', 'post', 'patch', 'put']
So, Do I need to allow 'add', 'modify' permissions for AnotherModel as well, to save MyModelResource or Did I mistake somewhere?
Upvotes: 2
Views: 930
Reputation: 3443
For that you need to first check if you have granted proper permission to the User. For more details, please refer this link.
Also Following setup works for me. So my models.py
looks something like:
class AnotherModel(models.Model):
id = models.Integerfield()
another_field = models.TextField()
class MyModel(models.Model):
foreign_key = models.ForeignKey(AnotherModel)
mymodel_field = models.TextField()
and resource.py
is as :
class AnotherResource(ModelResource):
class Meta:
queryset = AnotherModel.objects.all()
resource_name = 'another'
authorization = Authorization()
class MyModelResource(ModelResource):
another = fields.ToOneField(AnotherResource, 'another', full=True)
class Meta:
queryset = MyModel.objects.all()
resource_name = 'myresource'
authorization = Authorization()
Now to save any new data using POST
on Model. I can do following CURL
request.
curl --dump-header - -H "Content-Type: application/json" -X POST --data { "mymodel_field" : "Some text value": "another" : { "id" : 1243 } }' http://localhost/api/v1/myresource/
Hopefully, this should help you in resolving your issue. :)
Upvotes: 1