I am running this exact example:
http://www.django-rest-framework.org/api-guide/serializers
But when I get to this part
serializer = CommentSerializer(data=data)
serializer.is_valid()
# True
serializer.object
# <Comment object at 0x10633b2d0>
Instead of a 'Comment' object I am getting a 'dict' with the values.
Is this a bug? Or am I missing something?
Iam using: djangorestframework-2.3.12 and django1.6.1
Thanks!
This was actually my bad. I copy-pasted the code and the function 'restore_object' was left outside the CommentSerializer class. The default 'restore_object' deserializes to a dict.
Very sorry
Related
Sorry if this seems like a really stupid question. I am building an app using Django, and at some point I am accessing the db using db.objects.get(var = val)
But my question is what type object does this method return? And hw can I access the data in it?
Like as a dict, list or sth else?
When I use this:
a = db.objects.get(var=val)
print(a["id"])
It returns:
'db' object is not subscriptable
When I use this:
a = db.objects.get(var=val)
print(a)
I get:
db object (1)
I cannot use the data in this form.
It will return a object. See the docs for details.
Use . operator to access values inside object.
print(a.field_name)
It would return the object of your model on which you are querying.
If nothing matches and no rows is returned, it would through a Model.DoesNotExists exception.
I'm trying to pass some data about a user as JSON, and because the User object has many-to-many relationships, serializing a user as JSON seems to only include the primary key of the m-n object.
(e.g. each user has hobbies, but in the JSON it will only have the PK of the hobbies)
Anyway, I tried constructing a schema to solve this as such:
[[{user}, [hobbies]], [{user}, [hobbies]],...]
But whenever I try to serialize this (in Python it's basically an array with an object and another array in it), I get the error:
'list' object has no attribute '_meta'
Why is this happening and how can I fix it?
EDIT:
Here's the code for it:
for u in allUsers:
if searchedHobby in u.hobbies.all():
user = [u]
userHobbies = []
for hobby in u.hobbies.all():
userHobbies.append(hobby.name)
user.append(userHobbies)
response.append(user)
data = serializers.serialize('json', response)
As seen in the django github repository the serialize method expects a queryset.
What you could do is to do a json.dumps(response) and return that in the HttpResponse.
I have a form with several fields. I have separate validation checks for each field, done via the forms validation. I however also need to check if few fields are filled in before redirecting the user to a different view. I was hoping I could somehow append the error to forms.non_field_errors as it is not for a particular field , but I am not sure what the right syntax for this would be. I have checked online and found..
form.errors['__all__'] = form.error_class(["error msg"])
This displays the error message, but it seems to mess up the other pages as well and displyas the error message if I click on anything else.
I tried
form._errors[NON_FIELD_ERRORS] = form.error_class()
This causes a 'NoneType' object has no attribute 'setdefault' error for me.
I have tried
form.non_field_errors().append("Please complete your profile in order to access the content.")
This doesn't seem to do anything and I cant see the error message on the view.
What would be the best way to do this? Ideally I dont' want to do it in the form's clean method. I feel like I should be able to append an error to the form in the view.
Call full_clean(), this should initialize form._errors. This step is critical, if you don't do it, it won't work.
Make the error list, it takes a list of messages, instanciate it as such: error_list = form.error_class(['your error messages'])
Assign the error list to NON_FIELD_ERRORS, you have to import NON_FIELD_ERRORS from django.forms.forms, then assign as such: form._errors[NON_FIELD_ERRORS] = error_list
Here is a demonstration from a shell:
In [1]: from bet.forms import BetForm
In [2]: from django.forms.forms import NON_FIELD_ERRORS
In [3]: form = BetForm()
In [4]: form.full_clean()
In [5]: form._errors[NON_FIELD_ERRORS] = form.error_class(['your error messages'])
In [6]: form.non_field_errors()
Out[6]: [u'your error messages']
This is a bit out-dated but i recently ran into the same question and wanted to shed some further light on this for future readers.
As of Django 1.6+ the errors dictionary is stored as form.errors and not form._errors
If you instantiate form.is_valid(), it is the equivalent of running full_clean()
NON_FIELD_ERRORS isn't necessary to import, you can simply refer to its default dictionary key of __all__
Example:
if form.is_valid():
form.errors['__all__'] = form.error_class(['Your Error Here!'])
On form there is method add_error.
class ExampleForm(forms.Form) :
def clean(self) :
self.add_error(None, "The __all__ error message")
return super().clean()
The first param of add_error() function is about the refered fields.
If the field is None the add_error() function will considere that the error is a form_error.
The clean() method is a hook called by _clean_form().
Then the _clean_form() function is called by full_clean(). See more: full_clean() source
self._errors.setdefault('__all__', ErrorList()).extend([""])
I'm trying to gat the value of a form field in django, now
xxx = request.POST[u'a1']
gives me a value, but
xxx = request.POST.get(u'a1')
gives me nothing
what am I doing wrong?
Update:
Using the first method, request.method = POST,
using the second method changes it to GET,
all I am doing is replacing one line of code.
Ingmar, yes this does return true.
Shawn, first method produces DEBUG:root:[(u'a1', u'A1_6')],
second method produces DEBUG:root:[]
The get method takes two parameters: key and a return value for where there's no match for the key (defaults to None).
Maybe the first example worked only in cases where the form had a value in the field 'a1'.
Either set a return value for the get method (e.g. xxx = request.POST.get(u'a1', 'something')) or check in advance whether you have that field in the form (if u'a1' in request.POST ...)
A bit confusing question, but the way I understand you, you have a request that at one point contains a QueryDict with data in request.POST, but at a later point in the code cointains an empty QueryDict: {} in request.POST, and you are looking for the reason why and where the data disappears.
The Django docs say the QueryDict in HttpRequest is immutable, and cannot be changed. So you probably shouldn't be looking for code changing the value of the request.POST QueryDict, but some code that replaces the whole request.POST QueryDict with another one.
My guess is that you are assigning the value 'GET' to request.method at some point in the code, since you say that in function number two, request.method is changed to GET
When tinkering with a response of the type PUT some time ago I discovered that django actually applies logic to the HttpResponse object if response.method is changed, resulting in a changed request.POST QueryDict.
I am trying to make Django view that will give JSON responce with earliest and latest objects. But unfotunately it fails to work with this error.
'str' object has no attribute '_meta'
I have other serialization and it works.
Here is the code.
def get_calendar_limits(request):
result = serializers.serialize("json", Session.objects.aggregate(Max('date'), Min('date')), ensure_ascii=False)
return HttpResponse(result, mimetype="application/javascript")
Thanks a lot beforehand.
I get the same error when trying to serialize an object that is not derived from Django's Model
Python has "json" module. It can 'dumps' and 'loads' function. They can serialize and deserialize accordingly.
Take a look at the following:
objects= Session.objects.aggregate(Max('date'), Min('date'))
print [ type[o] for o in objects ]
result = serializers.serialize("json", objects, ensure_ascii=False)
You might want to just run the above in interactive Python as an experiment.
What type are your objects? Is that type serializable?