dustinfarris / ember-django-adapter Goto Github PK
View Code? Open in Web Editor NEWEmber CLI addon adapter for Django REST Framework
Home Page: http://dustinfarris.github.io/ember-django-adapter
License: MIT License
Ember CLI addon adapter for Django REST Framework
Home Page: http://dustinfarris.github.io/ember-django-adapter
License: MIT License
Ember-data 1.13 was just released with some changes that affect EDA. You can read about the details here:
http://emberjs.com/blog/2015/06/18/ember-data-1-13-released.html
The first issue I found with when trying ED 1.13.4 with EDA 0.5.6 is that RESTAdapter.ajaxError()
has been removed and EDA calls it through _super()
(https://github.com/dustinfarris/ember-django-adapter/blob/v0.5.6/addon/adapters/drf.js#L76). While ED 1.13 does call ajaxError()
on an adapter if it's present, this is a breaking change in ED 1.13 because RESTAdapter.ajaxError()
is a public method that has been removed between ED 1.0.0-beta.19.2 and 1.13.0.
I want to decide on a plan for updating to ED 1.13. Should EDA 1.0 support the latest betas (e.g. 18, 19) and run with the deprecation warnings from ED? Or should we aim for EDA 1.0 to support the new conventions in ED 1.13 which means breaking compatibility with the 0.5.x? If we go this route, there isn't an issue with the breaking change in ED 1.13. On the other hand adding RESTAdapter.ajaxError()
to EDA to maintain compatibility is easy enough.
My opinion is that EDA 1.0 should work with the new conventions in ED 1.13 but I wanted to see what you guys think before I start to work on this.
Interesting question/answer: http://discuss.emberjs.com/t/coalescing-find-requests/7076
I didn't know you could supply links to resources with Ember.
So we could, in theory, support the HyperLinkedRelatedField and possibly the HyperLinkedIdentityField.
This may "just work". I would like to add documentation if it does. I will investigate this further.
Relates to #32.
The app I'm working on right now currently uses this method, which is available in the other, non-CLI library. However, now that we're moving to the CLI and trying to use this CLI addon, it's no longer working. What would be the right approach to fixing this?
When I save a model that has a JS date (created with new Date()
) I get the error:
Date has wrong format. Use one of these formats instead: YYYY[-MM[-DD]]
The date in the post was 2015-01-05T22:08:37.838Z
. So is this:
Appreciate any help.
Using:
ember-cli 0.1.5
ember-data 1.0.0-beta.12
ember-django-adapter 0.5
django 1.7.1
djangorestframework 3.0.2
Python 3.4
It has been reported that the configuration in environment.js is not getting picked up by EDA. See end of #4.
Now the ED beta 14 and 14.1 are out, we should see if there's a way to test with multiple versions of ember and ember data. @dustinfarris Do you have any ideas on this?
So users can easily extend with:
ember generate django-adapter my-custom-adapter
or
ember generate django-serializer my-custom-serializer
Hi,
Finally got some time to investigate a little more. Here is an issue I'm having using the version 1.0 branch.
I get this error when I try to find a user:
"Error: No model was found for 'id'
at new Error (native)
at Error.EmberError (http://0.0.0.0:4200/assets/vendor.js:25594:23)
at Ember.Object.extend.modelFor (http://0.0.0.0:4200/assets/vendor.js:72988:19)
at __exports__.default.JSONSerialize.extend.extractSingle (http://0.0.0.0:4200/assets/vendor.js:66134:28)
at apply (http://0.0.0.0:4200/assets/vendor.js:30440:27)
at superWrapper [as extractSingle] (http://0.0.0.0:4200/assets/vendor.js:30014:15)
at __exports__.default.Ember.Object.extend.extractFind (http://0.0.0.0:4200/assets/vendor.js:65670:21)
at __exports__.default.Ember.Object.extend.extract (http://0.0.0.0:4200/assets/vendor.js:65539:37)
at http://0.0.0.0:4200/assets/vendor.js:73512:34
at tryCatch (http://0.0.0.0:4200/assets/vendor.js:57874:16)"
ED is using extractSingle method to handle this, because the response is
{"id": 1, "username": "pp", "email": "[email protected]", "full_name": "", "teams": [], "is_staff": true}
But, since it is expecting something like this:
{"user": {"id": 1, "username": "pp", "email": "[email protected]", "full_name": "", "teams": [], "is_staff": true}}
it's assuming the first key is the model type to search for, but of course fails to find one.
Switching to ED beta 11 shows a different error (since it now actually tries with each key before failing), but problem persists.
I tried a solution and it worked for me, which was implementing extractSingle and modify the payload to what ED expects:
extractSingle: function(store, primaryType, rawPayload, recordId) {
var payload = {};
payload[primaryType.typeKey] = rawPayload;
return this._super(store, primaryType, payload, recordId);
}
Overriding normalizedPayload won't work since we don't get passed the type, only the payload.
@dustinfarris @benkonrath do you see any problem with this approach?
Similar to issue #14 , this fails since the API is not expecting a root key (ED by default wraps the payload in a root key)
In order to make it work I added to the serializer the following method:
serializeIntoHash: function(hash, type, record, options) {
Ember.merge(hash, this.serialize(record, options));
}
@benkonrath did you encounter this issue as well? I want to open PRs both for this and #14 but waiting on your PR for adding tests, any luck with that?
I don't know if this is a failure of this adapter, or of the documentation, or of my understanding of DRF, or of my understanding of the web. But I'm posting it here so that it can be seen by others that have worked on Django/DRF/ember-cli apps.
So I followed the documentation here, and receive the following error in the console:
XMLHttpRequest cannot load http://localhost:8000/tournaments/?_=1420156338346. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access.
So I looked around, and it seems that this problem should be handled with CORS, and the DRF docs recommend: https://github.com/ottoyiu/django-cors-headers
Following instructions there, as best as I can understand, I tried to expose some response headers:
CORS_EXPOSE_HEADERS = (
'Access-Control-Allow-Origin: *',
)
But it seems that they don't make it through. So my question is: am I doing it wrong? I read in the README:
Installing the adapter and setting API_HOST should satisfy most requirements ...
which makes me wonder if I'm missing something. Am I trying to solve this in the right way, or am I shaving a yak? I would appreciate any help.
I'm using ember-cli 0.1.5, DRF 3.0.2, Python 3.4, Django 1.7.1.
Doing a pull request soon. Opening this issue to refer to it in the changelog.
The issue is that after installing the addon with ember-cli 0.4.6
I get: Cannot read property 'pkg' of null TypeError: Cannot read property 'pkg' of null
stack trace is not very helpful to me as I'm not familiar with ember-cli internals, but I did notice that it has this entry in package.json:
"after": "ember-cli-ember-data"
It appears that this was deprecated as ember-data now natively supports addons
We need to start thinking about where we want to put the documentation for the adapter. Previously, I used GitHub's wiki for the original adapter, and it worked ok. Not sure if it is the best option, but it's right there and requires zero setup.
Other options might include:
This should be considered a blocker for the 1.0 release.
@benkonrath what do you think?
Is there a build of this adapter that can be downloaded (without the need of using ember-cli)?
This is a placeholder to carry over the discussion from the legacy adapter:
See:
An EDA user reached out recently and inquired about side-loaded data support. I think we should consider this. After brain-storming how to do this in the least DRF-invasive way, I think we can specify a special key to represent the data. Since JSON API uses included
, I recommend we use a similar name-spaced key like _included_modelnames
.
Something like this:
# models
class Person(models.Model):
name = models.CharField(max_length=80)
class Animal(models.Model):
owner = models.ForeignKey(Person, related_name='pets')
name = models.CharField(max_length=80)
# serializers
class AnimalSerializer(serializers.ModelSerializer):
class Meta:
model = Animal
class PersonSerializer(serializers.ModelSerializer):
_included_animals = AnimalSerializer(many=True, read_only=True, source='pets')
class Meta:
model = Person
fields = ('name', 'pets', '_included_animals')
Here, the pets
field will use the default PrimaryKeyRelatedField, but there is an added _included_animals
field that will piggy back the nested serializer. EDA would automagically intercept any _included
keys and proxy to ED side loading. Thoughts?
Will probably take inspiration from ember-data-django-rest-adapter plus whatever enhancements are needed to make tests work for an addon package.
TLDR: determine whether and how to support optimized queries for async hasMany relationships.
In Toran's original ED adapter, hasMany records were looked up using a nested url structure (e.g. /dealerships/1/cars/
. To my knowledge this was a design decision made by Toran that is not mandated (or suggested) by either ED or DRF.
ED introduced the coalesceFindIds
option in beta.9 as its solution for getting hasMany attributes. With this option enabled, whenever the adapter needs to lookup at an async hasMany relationship, it will take the list of related ids and generate a request in the format /cars?ids[]=1&ids[]=2&ids[]=3
. This format of request is not supported by DRF by default (though it can be implemented).
ED continues to support a set of adapter methods that make it possible to direct async hasMany look ups to particular urls (see here and here. This makes it possible to cause an ED adapter to use a url structure like /dealerships/1/cars/
(like Toran's adapter).
Using DRF viewsets, an endpoint for the above url could be implement like this:
class DealershipViewset(viewsets.ModelViewset):
@detail_view(methods=['get'])
def cars(self, request):
queryset = self.get_object().cars.all()
serializer = CarSerializer(queryset, many=True)
return serializer.data
If this approach is taken, a decision would need to be made on how urls for multiword relationships should be formatted, noting that DRF currently does not support dasherized urls for @detail_view
and @list_view endpoints
.
See #19 for some other lead up discussion.
So hopefully this frames the problem well. I should mention that my interest in this is purely academic as I have switched to using a DRF side adapter and pure ember data. None the less, I am happy to stay involved in this discussion.
Hi and sorry in advance if I am doing something wrong. I am using the latest version of everything I think and need to extend the adapter. My application is working fine using the default ember data RESTAdapter. I now need to add in drf support and do the following in accordance with the docs:
ember g drf-adapter application
My application now immediately errors out in the console with a message of
Error while processing route: home Could not find module my-sample-app/adapters/drf Error: Could not find module my-sample-app/adapters/drf
A similar issue happens when I attempt to make a customer serializer, any help would be greatly appreciated. That's a bit of a snipped traceback but it seems pretty obvious what the issue is. I'm not familiar enough with all this to debug it myself, sorry.
Recently released, converges all deps to latest stable (ember 1.13 and ED 1.13.15)
I'll update this after #103 is merged and prior to an EDA 1.0-Beta1 release
PREFACE: I am a complete and total noob, so forgive me if I'm missing something, but the namespace parameter does not seem to be honored when making requests of the API.
My config:
if (environment === 'development') {
ENV.APP.API_HOST = 'http://localhost:8000';
ENV.APP.API_NAMESPACE = 'api';
}
In console:
Ember Debugger Active VM2701:161
GET http://localhost:8000/photos/?_=1406356846939 404 (NOT FOUND) vendor.js:9726
Error while processing route: photos vendor.js:17062
Notice that it is hitting the root url. Also, if I change my API itself to serve at the root, all is well.
Easy fix as it is only syntactic. Relevant methods are:
I'll take care of this PR, but @dustinfarris I want to hold on until you merge the ember-cli update to 0.2.3, sounds good?
Hi,
I installed the version-1.0 using npm.
I encountered some issues:
Uncaught TypeError: Cannot read property 'apiHost' of undefined
This coming from app/adapters/application.js, at this line
return this.get('djangoAdapterConfig').apiHost;
If I change the line wih ENV.APP:API_HOST mentioned in the item above, this gets resolved
We should be able to copy the code and maybe the tests from the old adapter.
I guess something with the deprecation warnings from ember-data beta.18 cause ember-data to fail on IE8. @dustinfarris Any chance you can make a new release soon?
While Ember-Data ajaxError returns errored jqXHR (as documented), ember-django-adapter instead returns Error(jsonErrors['detail']);
breaking contract and making any suffisticated error processing impossible due to no original error data with exception of "detail" message making it to application.
Is this correct?
extractMeta: function(store, type, payload) {
if (payload && payload.results) {
// Sets the metadata for the type.
store.metaForType(type, {
total: payload.count,
next: payload.next,
previous: payload.previous
});
// Keep ember data from trying to parse the metadata as a records.
delete payload.count;
delete payload.next;
delete payload.previous;
}
}
Placeholder for discussion on CI
Once unit + integration tests are merged in the 1.0 branch we should set a CI service to run them automatically.
The CI might also be used to automate releases (run tests + tag + upload to npm)
I recall @benkonrath mentioning circle CI, I'm not familiar with it, but with travis.
Thoughts?
I've decided that it's a better to re-write the Django adapter considering that current adapter has been developed over a long period of time and doesn't always take into account the changes in ember-data.
The goals for the new adapter are as follows:
Are you interested in doing this work in this repository? I would like to build up the adapter / serializer slowly so that we can review each other's work, ensure that the quality remains high and that we stick to the goals I mentioned above. What do you think?
I installed by running:
npm i --save-dev ember-django-adapter
The directory node_modules/ember-django-adapter
exists in my project.
In the browser DS.DjangoRESTAdapter
is undefined
.
Generating a blueprint fails:
$ ember generate django-adapter my-custom-adapter
version: 0.0.41
Unknown blueprint: django-adapter
When I place the following in app/adapters/application.js
I receive an error on ember serve
:
import DjangoAdapter from './django';
export default DjangoAdapter.extend({});
The error I see on ember serve
:
ENOENT, no such file or directory '/myproject/ember/tmp/tree_merger-tmp_dest_dir-d6SYFVCi.tmp/myproject/adapters/django.js'
...
I just notice that EDA contributes a .jshintrc blueprint. Is this correct or should we remove the .jshintrc file from the blueprints directory?
ember g --help
Available blueprints:
ember-django-adapter:
.jshintrc
drf-adapter
drf-serializer
I moved the circle config from @benkonrath over to the gh-pages branch so that it would get picked up by CircleCI at the right time only to discover that the entire branch gets overwritten every time the docs are generated.
This needs to be added as an artifact to mkdocs I think, just not sure yet how to do it.
I'm getting an error running unit tests for the DRF adapter and subclassed adapters.
See the following gist for an example:
https://gist.github.com/pkenway/9e77ca425d91fe925482
This is the error I get:
not ok 1 PhantomJS 1.9 - ApplicationAdapter: it exists
---
actual: >
null
message: >
beforeEach failed on it exists: 'undefined' is not a function (evaluating '(function () {
return ENV['default'].APP.API_HOST;
}).property()')
Log: >
...
ok 2 PhantomJS 1.9 - JSHint - unit/adapters: unit/adapters/application-test.js should pass jshint
This is with ember-cli 0.2.2.
Am I doing something wrong or is this a bug?
Hi, I installed this addon in my project with npm i --save-dev ember-django-adapter
, and now the ember
command gives me an error whenever I invoke it.
I'm using ember-cli 0.0.46. Here's the error log: http://dpaste.com/2HY7V3H
Could you create an example Django + Ember CLI project that works out of the box? Thanks!
Trying to install the adapter, and get all of these. Don't know that it causes a problem, but don't understand how to eliminate them.
wilsone123 [20:28:34] $ npm i --save-dev ember-django-adapter
npm WARN unmet dependency /Users/wilsone123/code/titlematch_web/node_modules/ember-cli/node_modules/tiny-lr/node_modules/body-parser requires qs@'2.2.4' but will load
npm WARN unmet dependency /Users/wilsone123/code/titlematch_web/node_modules/ember-cli/node_modules/tiny-lr/node_modules/qs,
npm WARN unmet dependency which is version 2.2.5
npm WARN unmet dependency /Users/wilsone123/code/titlematch_web/node_modules/ember-cli/node_modules/npm/node_modules/npm-registry-client/node_modules/concat-stream requires readable-stream@'~1.1.9' but will load
npm WARN unmet dependency /Users/wilsone123/code/titlematch_web/node_modules/ember-cli/node_modules/npm/node_modules/readable-stream,
npm WARN unmet dependency which is version 1.0.32
npm WARN unmet dependency /Users/wilsone123/code/titlematch_web/node_modules/ember-cli/node_modules/testem/node_modules/express requires commander@'0.6.1' but will load
npm WARN unmet dependency /Users/wilsone123/code/titlematch_web/node_modules/ember-cli/node_modules/testem/node_modules/commander,
npm WARN unmet dependency which is version 2.5.1
npm WARN unmet dependency /Users/wilsone123/code/titlematch_web/node_modules/ember-cli/node_modules/testem/node_modules/express requires mkdirp@'0.3.3' but will load
npm WARN unmet dependency /Users/wilsone123/code/titlematch_web/node_modules/ember-cli/node_modules/mkdirp,
npm WARN unmet dependency which is version 0.5.0
npm WARN unmet dependency /Users/wilsone123/code/titlematch_web/node_modules/ember-cli/node_modules/testem/node_modules/tap requires glob@'~3.2.1' but will load
npm WARN unmet dependency /Users/wilsone123/code/titlematch_web/node_modules/ember-cli/node_modules/testem/node_modules/glob,
npm WARN unmet dependency which is version 3.1.21
npm WARN unmet dependency /Users/wilsone123/code/titlematch_web/node_modules/ember-cli/node_modules/testem/node_modules/tap requires nopt@'~2' but will load
npm WARN unmet dependency /Users/wilsone123/code/titlematch_web/node_modules/ember-cli/node_modules/nopt,
npm WARN unmet dependency which is version 3.0.1
npm WARN unmet dependency /Users/wilsone123/code/titlematch_web/node_modules/ember-cli/node_modules/testem/node_modules/glob requires minimatch@'~0.2.11' but will load
npm WARN unmet dependency /Users/wilsone123/code/titlematch_web/node_modules/ember-cli/node_modules/minimatch,
npm WARN unmet dependency which is version 1.0.0
npm WARN unmet dependency /Users/wilsone123/code/titlematch_web/node_modules/ember-cli/node_modules/testem/node_modules/fileset requires minimatch@'0.x' but will load
npm WARN unmet dependency /Users/wilsone123/code/titlematch_web/node_modules/ember-cli/node_modules/minimatch,
npm WARN unmet dependency which is version 1.0.0
npm WARN unmet dependency /Users/wilsone123/code/titlematch_web/node_modules/ember-cli/node_modules/testem/node_modules/fireworm requires minimatch@'~0.2.9' but will load
npm WARN unmet dependency /Users/wilsone123/code/titlematch_web/node_modules/ember-cli/node_modules/minimatch,
npm WARN unmet dependency which is version 1.0.0
[email protected] node_modules/ember-django-adapter
~/code/titlematch_web
The signature of DRFSerializer.extractSingle
is:
extractSingle: function(store, type, payload, id, requestType)
requestType
is not used, and it is not present in the parent class method. Safe to remove?
When attempting to run acceptance tests, pretender will bail out rather than making a request. Possibly related to #33
I'm not sure if this is a bug or design decision, but I am unable to resolve a specific issues regarding a resource where the singular version of the name ends in 's': specifically, i'm trying to map the resource 'chorus', which creates all sort of issues: EDA seems to look for the singular version of the endpoint, but the controller then thinks it's an object and not an array, something else starts looking for 'choru' (dropped s) and all sorts of other unpleasantries.
Obviously I can change my endpoint name to whatever on the DRF side, but presumably the point of this adapter is to serve as the gateway without having to touch DRF. Anyway, would appreciate some guidance or simply a 'yep, that's the design'.
FWIW, I come down on the 'name all collections singular' side of that particular religious war, but am not so zealous as to do what I have to do to make things work... :-)
DRFAdapter.pathForType('FurryAnimals');
furry-animals
furryanimals
I'm getting undefined in the drf serializer inside extractArray
for the type.modelName variable
. I changed that to type.typeKey
and that property is what was needed.
I'm using ember 1.13.1, ember-data 1.0.0-beta.17, and ember-django-adapter 0.5.6
Our docs currently specify the requirements as follows:
We also require Ember Data >= 1.0.0-beta.12 but I don't know what this implies for the version of Ember and Ember CLI. There's some information on the Ember blog about Ember 1.7 support being dropped in 1.0.0-beta.13 and it seems to recommend Ember 1.8.
http://emberjs.com/blog/2014/11/24/ember-data-1-0-beta-12-released.html
At the very least we need to add ED 1.0.0-beta.12 to the list of requirements.
I'm attempting to load a GET
response of multiple models, type: publishable
.
The problem is, these models have nested records.
The example JSON response is:
{
"meta":{
"next":null,
"next_link":null,
"page":1,
"previous":null,
"previous_link":null,
"count":5,
"total":1
},
"publishable":[
{
"id":1,
"url":"http://localhost:8000/api/1/publishables/1/",
"category":{
"id":1,
"url":"http://localhost:8000/api/1/categories/1/",
"tree_path":"",
"title":"Test Category 1",
},
"authors":[
{
"id":1,
"url":"http://localhost:8000/api/1/authors/1/",
"user":{
"id":1,
"username":"testUserOne",
"first_name":"",
"last_name":"",
"email":"",
},
"name":"testUserOne",
}
],
"title":"testPublishableOne",
"slug":"testpublishableone",
"description":"",
},
{
"id":2,
"url":"http://localhost:8000/api/1/publishables/2/",
"category":{
"id":1,
"url":"http://localhost:8000/api/1/categories/1/",
"tree_path":"",
"title":"Test Category 1",
},
"authors":[
{
"id":1,
"url":"http://localhost:8000/api/1/authors/1/",
"user":{
"id":1,
"username":"testUserOne",
"first_name":"",
"last_name":"",
"email":"",
},
"name":"testUserOne",
}
],
"title":"testPublishableTwo",
"slug":"testpublishabletwo",
"description":"",
}
]
}
Console complains:
Error while processing route: publishables.index Assertion Failed: Ember Data expected a number or string to represent the record(s) in the `authors` relationship instead it found an object. If this is a polymorphic relationship please specify a `type` key. If this is an embedded relationship please include the `DS.EmbeddedRecordsMixin` and specify the `authors` property in your serializer's attrs object.
I have added the following:
import DRFSerializer from './drf';
import DS from 'ember-data';
export default DRFSerializer.extend(DS.EmbeddedRecordsMixin, {
attrs: {
authors: { embedded: 'always' }
}
});
to my /app/serializers/publishables.js
, yet it still complains.
Has anyone had this problem with EmbeddedRecords
?
Full error:
[Error] Error: Could not find module `wibi/application/drf` imported from `wibi/application/adapter`
end (vendor.js, line 10728)
run (vendor.js, line 10770)
join (vendor.js, line 10789)
join (vendor.js, line 26509)
(anonymous function) (vendor.js, line 26564)
fire (vendor.js, line 3345)
fireWith (vendor.js, line 3457)
ready (vendor.js, line 3669)
completed (vendor.js, line 3700)
I'm guessing this is an error with ember-cli 0.2.3
? Should ember-django-adapter/addon/adapters/drf.js have been put into the adapters folder?
This is what I see in the console when dev mode fails with the adapter. When I run as:
$ ember serve --environment production
It seems to work fine. I'll use that as my dev mode for now.
You can look at my code at https://github.com/ewilson/titlematch_web
Error while processing route: tournaments.index Could not find module ember-django-adapter/adapters/drf Error: Could not find module ember-django-adapter/adapters/drf
at requireModule (http://localhost:4200/assets/vendor.js:65:13)
at reify (http://localhost:4200/assets/vendor.js:48:30)
at requireModule (http://localhost:4200/assets/vendor.js:76:17)
at resolveOther (http://localhost:4200/assets/vendor.js:63103:20)
at apply (http://localhost:4200/assets/vendor.js:32885:27)
at superWrapper (http://localhost:4200/assets/vendor.js:32457:15)
at exports.default.EmberObject.extend.resolve (http://localhost:4200/assets/vendor.js:16818:27)
at Object.resolve as resolver
at resolve (http://localhost:4200/assets/vendor.js:14968:32)
at Object.Container.resolve (http://localhost:4200/assets/vendor.js:14548:16)ember.js:15373 logToConsoleember.js:26312 logErrorember.js:26269 defaultActionHandlers.errorember.js:26360 triggerEventember.js:46873 triggerember.js:46718 Transition.triggerember.js:46523 (anonymous function)ember.js:47307 tryCatchember.js:47319 invokeCallbackember.js:47290 publishember.js:47232 publishRejectionember.js:29435 (anonymous function)ember.js:679 DeferredActionQueues.invokeember.js:749 DeferredActionQueues.flushember.js:135 Backburner.endember.js:190 Backburner.runember.js:18223 runember.js:2542 runInitializejquery.js:3143 firejquery.js:3255 self.fireWithjquery.js:3467 jQuery.extend.readyjquery.js:3498 completed
A cut & paste from a comment in PR #18:
It turns out that Pretender doesn't work when the host is set. I ended up setting API_HOST to an empty string and overriding the default adapter creation to set 'test-host' in the unit tests.
I tried to override the host setting in the integration tests instead, but nothing I tried worked. There are some facilities for this - like overriding delegate when using moduleFor() - but it didn't work. I also tried writing my own module wrapper like moduleFor() that also didn't work. I'll post a question on the ember-discussion board to see how the host can be overridden to blank for Pretender but it would be great to get this merged as is so I can continue with the integration tests for CRUD failure.
Hi,
I'm using the browsable api interface and I able to create and update using the HTML form, but when I try to do the same using raw JSON I get this error:
"propiedad": [
"This field may not be null."
]
I've been testing several configurations on my serializers and I read the documentation, but I don't know what I'm doing wrong.
I think the problem is the nested objects.
These are my models:
class Propiedad(models.Model): # Datos
user = models.ForeignKey(User,verbose_name='Usuario')
titulo = models.CharField('Título', max_length=100)
tipo_propiedad = models.ForeignKey('tipos.Tipo_propiedad', verbose_name='Tipo de propiedad')
tipo_operacion = models.ForeignKey('tipos.Tipo_operacion',verbose_name='Tipo de operación')
descripcion = models.TextField('Descripción',blank=True, null=True)
vistas = models.IntegerField('Vistas', blank=True, null=True)
likes = models.IntegerField('Me gusta', blank=True, null=True)
precio = models.IntegerField('Precio')
moneda = models.CharField('Moneda', max_length=4,choices=MONEDA, default=MONEDA[0][0])
tipo_cobro = models.ForeignKey('tipos.Tipo_cobro',verbose_name='Tipo de cobro', blank=True, null=True)
expiracion = models.DateTimeField('Fecha de expiración', blank=True, null=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
class Meta:
verbose_name = 'Propiedad'
verbose_name_plural = 'Propiedades'
def __unicode__(self):
return self.titulo
class Datos_generales(models.Model):
propiedad = models.OneToOneField('propiedades.Propiedad',verbose_name='Propiedad',blank=True,null=True)
fraccionamiento = models.BooleanField('Fraccionamiento', default=False, blank=True)
calle = models.CharField('Calle', max_length=100)
colonia = models.CharField('Colonia', max_length=100)
numero_exterior = models.CharField('Número exterior', max_length=10, blank=True, null=True)
numero_interior = models.CharField('Número interior', max_length=10, blank=True, null=True)
codigo_postal = models.CharField('Código postal', max_length=10, blank=True, null=True)
edad = models.CharField('Edad del inmueble', max_length=20, blank=True, null=True)
estado_conservacion = models.CharField('Estado de conservación', max_length=20, choices=ESTADO_CONSERVACION,blank=True, null=True)
cuartos = models.IntegerField('Núm. Cuartos', blank=True, null=True)
banios = models.IntegerField('Núm. Baños', blank=True, null=True)
medios_banios = models.IntegerField('Núm. Medios baños', blank=True, null=True)
estacionamientos = models.IntegerField('Estacionamientos', blank=True, null=True)
ubicacion = GeopositionField()
class Meta:
verbose_name = 'Datos generales'
verbose_name_plural = 'Datos generales'
def __unicode__(self):
return 'Datos generales'
class Caracteristicas(models.Model): # Características generales
propiedad = models.OneToOneField('propiedades.Propiedad',verbose_name='Propiedad',blank=True,null=True)
vestidor = models.BooleanField('Vestidor', default=False, blank=True)
azotea = models.BooleanField('Azotea', default=False, blank=True)
jardin = models.BooleanField('Jardín', default=False, blank=True)
cocina_integral = models.BooleanField('Cocina integral', default=False, blank=True)
comedor = models.BooleanField('Comedor', default=False, blank=True)
sala = models.BooleanField('Sala', default=False, blank=True)
cuartos_servicio = models.BooleanField('Cuartos de servicio', default=False, blank=True)
cuarto_lavado = models.BooleanField('Cuarto de lavado', default=False, blank=True)
niveles_construidos = models.IntegerField('Niveles construidos', blank=True, null=True)
mascotas = models.BooleanField('Mascotas', default=False, blank=True)
acceso_discapacitados = models.BooleanField('Acceso discapacitados', default=False, blank=True)
amueblado = models.CharField('Amueblado', max_length=30, choices=AMUEBLADO, default=AMUEBLADO[0][0], blank=True, null=True)
tipo_terreno = models.CharField('Tipo de terreno', max_length=20, choices=TIPO_TERRENO, blank=True, null=True)
escuelas_cercanas = models.BooleanField('Escuelas cercanas', default=False, blank=True)
cc_cercanos = models.BooleanField('Centros Comerciales Cercanos', default=False, blank=True)
class Meta:
verbose_name = 'Caracteristicas'
verbose_name_plural = 'Caracteristicas'
def __unicode__(self):
return 'Caracteristicas'
class Amenidades(models.Model): # Amenidades
propiedad = models.OneToOneField('propiedades.Propiedad',verbose_name='Propiedad',blank=True,null=True)
desayunador = models.BooleanField('Desayunador', default=False, blank=True)
sala_tv = models.BooleanField('Sala de TV', default=False, blank=True)
terraza = models.BooleanField('Terraza', default=False, blank=True)
alberca = models.BooleanField('Alberca', default=False, blank=True)
jacuzzi = models.BooleanField('Jacuzzi', default=False, blank=True)
salon_juegos = models.BooleanField('Salón de juegos', default=False, blank=True)
salon_fiestas = models.BooleanField('Salón de fiestas', default=False, blank=True)
estudio = models.BooleanField('Estudio', default=False, blank=True)
bodegas = models.IntegerField('Bodega(s)', default=0, blank=True, null=True)
vista_panoramica = models.BooleanField('Vista panorámica', default=False, blank=True)
class Meta:
verbose_name = 'Amenidades'
verbose_name_plural = 'Amenidades'
def __unicode__(self):
return 'Amenidades'
class Servicios(models.Model): # Servicios
propiedad = models.OneToOneField('propiedades.Propiedad',verbose_name='Propiedad',blank=True,null=True)
cisterna = models.BooleanField('Cisterna', default=False, blank=True)
aire_acondicionado = models.IntegerField('Aire acondicionado', default=0, blank=True, null=True)
alarma = models.BooleanField('Alarma', default=False, blank=True)
gimnasio = models.BooleanField('Gimnasio', default=False, blank=True)
asador = models.BooleanField('Asador/Parrila', default=False, blank=True)
calefaccion = models.BooleanField('Calefacción', default=False, blank=True)
seguridad_privada = models.BooleanField('Seguridad privada', default=False, blank=True)
servicios_basicos = models.BooleanField('Servicios básicos (agua/luz)', default=False, blank=True)
gas = models.BooleanField('Gas', default=False, blank=True)
linea_telefonica = models.BooleanField('Línea telefónica', default=False, blank=True)
internet = models.BooleanField('Internet', default=False, blank=True)
class Meta:
verbose_name = 'Servicios'
verbose_name_plural = 'Servicios'
def __unicode__(self):
return 'Servicios'
My serializers.py file:
class Datos_generalesSerializer(serializers.ModelSerializer):
class Meta:
model = Datos_generales
fields = (
"id",
"fraccionamiento",
"calle",
"colonia",
"numero_exterior",
"numero_interior",
"codigo_postal",
"edad",
"estado_conservacion",
"cuartos",
"banios",
"medios_banios",
"estacionamientos",
"ubicacion",
)
class CaracteristicasSerializer(serializers.ModelSerializer):
class Meta:
model = Caracteristicas
fields = (
"id",
"vestidor",
"azotea",
"jardin",
"cocina_integral",
"comedor",
"sala",
"cuartos_servicio",
"cuarto_lavado",
"niveles_construidos",
"mascotas",
"acceso_discapacitados",
"amueblado",
"tipo_terreno",
"escuelas_cercanas",
"cc_cercanos",
)
My views.py file
class PropiedadViewSet(viewsets.ModelViewSet):
serializer_class = PropiedadSerializer
queryset = Propiedad.objects.all()
def perform_create(self, serializer):
serializer.save(user=self.request.user)
My configuration in settings file
REST_FRAMEWORK = {
'PAGINATE_BY': 10,
'PAGINATE_BY_PARAM': 'page_size',
'MAX_PAGINATE_BY': 100,
'DEFAULT_PAGINATION_SERIALIZER_CLASS':
'rest_framework_ember.pagination.PaginationSerializer',
'DEFAULT_PARSER_CLASSES': (
'rest_framework_ember.parsers.JSONParser',
'rest_framework.parsers.FormParser',
'rest_framework.parsers.MultiPartParser'
),
'DEFAULT_RENDERER_CLASSES': (
'rest_framework_ember.renderers.JSONRenderer',
'rest_framework.renderers.BrowsableAPIRenderer',
),
}
(Nothing different comparing with your example code)
Thanks in advance.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.