I wrote an api with django rest and I want to post data and photo with requests package.
When I want to send data like this ->
data = {
'name':'data',
'price':'123',
'category':1 }
everything works correctly and the data is saved in the database, but when I want to send a photo along with the data, I get this error->
Traceback (most recent call last):
File "F:\New folder (6)\PyQt5\app.py", line 58, in <module>
window = MainWindow()
File "F:\New folder (6)\PyQt5\app.py", line 48, in __init__
r = requests.post(url, data=json.dumps(data) , headers=headers)
File "C:\Users\PC\AppData\Local\Programs\Python\Python39\lib\json\__init__.py", line 231, in dumps
return _default_encoder.encode(obj)
File "C:\Users\PC\AppData\Local\Programs\Python\Python39\lib\json\encoder.py", line 199, in encode
chunks = self.iterencode(o, _one_shot=True)
File "C:\Users\PC\AppData\Local\Programs\Python\Python39\lib\json\encoder.py", line 257, in iterencode
return _iterencode(o, 0)
File "C:\Users\PC\AppData\Local\Programs\Python\Python39\lib\json\encoder.py", line 179, in default
raise TypeError(f'Object of type {o.__class__.__name__} '
TypeError: Object of type BufferedReader is not JSON serializable
this is my django rest:
models.py
class Menu(models.Model):
image = models.ImageField(upload_to="img", blank=True, null=True)
name = models.CharField(max_length=100)
price = models.IntegerField()
category = models.IntegerField()
availability = models.BooleanField(default=False)
serializers.py
class MenuSerializer(serializers.ModelSerializer):
class Meta:
model = Menu
fields = ('id', 'image', 'name', 'price',
'category','availability')
views.py
class MenuViewset(ListCreateAPIView):
queryset = Menu.objects.all()
serializer_class = MenuSerializer
and this is my post request with the requests package that I wrote in PyQt:
class MainWindow(QMainWindow):
def __init__(self, *args, **kwargs):
super(MainWindow, self).__init__()
url = 'http://127.0.0.1:8000/api/upload/'
headers = {'Content-Type': 'multipart/form-data'}
data = {'image':('chat2.png', open('chat2.png','rb'),"multipart/form-data"),
'name':'data',
'price':'123',
'category':1 }
r = requests.post(url, data=json.dumps(data) , headers=headers)
if __name__ == '__main__':
app = QApplication([])
window = MainWindow()
app.exec_()
you are blocking the eventloop on requests.post use QNetworkAccessManager or something (open is also blocking).
You haven't called read() on open
open is intended to use as a context-manager
so if you want to use open do it like this:
with open("chat2.png", "rb") as image_fh:
data = {
"image": ("chat2.png", image_fh.read(), "multipart/form-data"),
"name": "data",
"price": "123",
"category": 1,
}
Related
I have several functional views that are passed parameters. I'm trying to write tests to check the url, status, etc. So far I'm starting with just testing the URL name. I have some querysets in the view and it looks from the traceback that I need to define objects for the queries in my setUp
urls
app_name = 'gradebook'
urlpatterns = [
path('updatesinglegrade/<int:assess_pk>/<int:class_pk>/<int:grade_pk>/',
views.updatesinglegrade, name='updatesinglegrade'),
]
view
def updatesinglegrade(request, assess_pk, class_pk, grade_pk):
grade = Grade.objects.get(id=grade_pk)
gradescale = GradeBookSetup.objects.get(user=request.user)
scale_choice = grade_scale_choice(gradescale.scale_mode)
form = UpdateGradeForm(gradescale=scale_choice)
context = {'form': form}
context['grade'] = grade
if request.method == 'POST':
form = UpdateGradeForm(
request.POST, gradescale=scale_choice)
if form.is_valid():
cd = form.cleaned_data
grade.score = cd['score']
grade.save()
return redirect('gradebook:assessdetail', assess_pk, class_pk)
else:
return render(request, "gradebook/grade_single_form.html", context)
else:
return render(request, "gradebook/grade_single_form.html", context)
test
class UpdateSingleGradeTests(TestCase):
def setUp(self):
self.user = CustomUser.objects.create_user(
username='tester',
email='tester#email.com',
password='tester123'
)
login = self.client.login(username='tester', password='tester123')
def test_updatesinglegrade_url_name(self):
response = self.client.get(reverse('gradebook:updatesinglegrade', kwargs={
'assess_pk': 1, 'class_pk': 2, 'grade_pk': 3}))
self.assertEqual(response.status_code, 200)
traceback
======================================================================
ERROR: test_updatesinglegrade_url_name (gradebook.tests.UpdateSingleGradeTests)
----------------------------------------------------------------------
Traceback (most recent call last):
File "C:\Users\Doug\OneDrive\django\gradebook\gradebook\tests.py", line 102, in test_updatesinglegrade_url_name
response = self.client.get(reverse('gradebook:updatesinglegrade', kwargs={
File "C:\Users\Doug\.virtualenvs\gradebook-6RQSg7dk\lib\site-packages\django\test\client.py", line 742, in get
response = super().get(path, data=data, secure=secure, **extra)
File "C:\Users\Doug\.virtualenvs\gradebook-6RQSg7dk\lib\site-packages\django\test\client.py", line 396, in get
return self.generic('GET', path, secure=secure, **{
File "C:\Users\Doug\.virtualenvs\gradebook-6RQSg7dk\lib\site-packages\django\test\client.py", line 473, in generic
return self.request(**r)
File "C:\Users\Doug\.virtualenvs\gradebook-6RQSg7dk\lib\site-packages\django\test\client.py", line 719, in request
self.check_exception(response)
File "C:\Users\Doug\.virtualenvs\gradebook-6RQSg7dk\lib\site-packages\django\test\client.py", line 580, in check_exception
raise exc_value
File "C:\Users\Doug\.virtualenvs\gradebook-6RQSg7dk\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
response = get_response(request)
File "C:\Users\Doug\.virtualenvs\gradebook-6RQSg7dk\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\Doug\.virtualenvs\gradebook-6RQSg7dk\lib\site-packages\django\contrib\auth\decorators.py", line 21, in _wrapped_view
return view_func(request, *args, **kwargs)
File "C:\Users\Doug\.virtualenvs\gradebook-6RQSg7dk\lib\site-packages\django\contrib\auth\decorators.py", line 21, in _wrapped_view
return view_func(request, *args, **kwargs)
File "C:\Users\Doug\OneDrive\django\gradebook\gradebook\views.py", line 1030, in updatesinglegrade
grade = Grade.objects.get(id=grade_pk)
File "C:\Users\Doug\.virtualenvs\gradebook-6RQSg7dk\lib\site-packages\django\db\models\manager.py", line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "C:\Users\Doug\.virtualenvs\gradebook-6RQSg7dk\lib\site-packages\django\db\models\query.py", line 435, in get
raise self.model.DoesNotExist(
gradebook.models.Grade.DoesNotExist: Grade matching query does not exist.
----------------------------------------------------------------------
Ran 6 tests in 1.527s
FAILED (errors=1)
I can create a Grade object as the traceback indicates, but my Grade model depends on five ForeignKeys, one of which has another ForeignKey:
model
class Grade(models.Model):
score = models.CharField(max_length=3, blank=True, default="INC")
user = models.ForeignKey(CustomUser, on_delete=models.CASCADE)
assessment = models.ForeignKey(
Assessment, on_delete=models.CASCADE, null=True, blank=True)
objective = models.ForeignKey(
Objective, on_delete=models.CASCADE, blank=True)
student = models.ForeignKey(Student, on_delete=models.CASCADE)
cblock = models.ForeignKey(Classroom, on_delete=models.CASCADE, default=1)
time_created = models.DateField(
auto_now=False, auto_now_add=False, default=timezone.now)
working test
from .models import CustomUser, Grade, Student, Course, Classroom, Objective, Assessment, GradeBookSetup
class UpdateSingleGradeTests(TestCase):
def setUp(self):
self.user = CustomUser.objects.create_user(
username='tester',
email='tester#email.com',
password='tester123',
is_teacher=True,
)
studentuser = CustomUser.objects.create(
username='student_test'
)
stud = Student.objects.create(
user=studentuser,
student_number='111222'
)
course = Course.objects.create(
user=self.user
)
classroom = Classroom.objects.create(
user=self.user,
course=course
)
# classroom.students.set(stud)
objective = Objective.objects.create(
user=self.user,
course=course
)
assessment = Assessment.objects.create(
user=self.user,
course=course
)
# assessment.objectives.set(objective)
login = self.client.login(username='tester', password='tester123')
grade = Grade.objects.create(
id=3,
user=self.user,
student=stud,
objective=objective,
cblock=classroom,
assessment=assessment
)
gbs = GradeBookSetup.objects.create(
id=1,
user=self.user
)
def test_updatesinglegrade_url_name(self):
response = self.client.get(reverse('gradebook:updatesinglegrade', kwargs={
'assess_pk': 1, 'class_pk': 2, 'grade_pk': 3}))
self.assertEqual(response.status_code, 200)
Does this mean that I need to create 6 objects in the setUp? I got it work for this test, and I'm wondering if this is something I will have to add to many of my class TestCase (which have similar objects/models involved)? Or perhaps there is a more efficient way of doing this?
The short answer is, yes, non-null ForeignKey fields must be populated in tests because they are non-null.
There are several ways to do this:
Call objects.create() on each model. This can be very tedious and time consuming.
Use a fixture. Creating the JSON files can also be tedious, but fortunately, you can use the Django admin to do data entry and then ./manage.py dumpdata to generate the JSON.
Use a 3rd party library such as factory-boy or model-bakery. These libraries can generate random data for fields that don't really matter for testing other than that they have a value. If you need a specific value for a certain test, then you can provide it.
You can create fixture and use it in your TestCase class
docs on subject: https://docs.djangoproject.com/en/3.2/topics/testing/tools/#fixture-loading
class UpdateSingleGradeTests(TestCase):
fixtures = ['fixture.json']
I am attempting to create a POST endpoint using DRF ListSerializer to create a list of LogLevel objects.
I have tried to serialize the foreign key using PrimaryKeyRelatedField without success.
models.py
relevant fields for LogLevel model. note foreign key to node model
#associated node
node = models.ForeignKey(Node, on_delete=models.DO_NOTHING,
related_name="log_levels")
#logger name
name = models.CharField(max_length=32, choices=LOGGERS)
# Current log level
level = models.IntegerField(default=INFO,
choices=LOG_LEVELS)
# Timestamps
created_datetime = models.DateTimeField(auto_now_add=True)
updated_datetime = models.DateTimeField(auto_now=True,
blank=True, null=True)
serializers.py
class LogLevelListSerializer(serializers.ListSerializer):
def create(self, validated_data):
log_levels = [LogLevel(**item) for item in validated_data]
levels = LogLevel.objects.bulk_create(log_levels)
return levels
class LogLevelCreateUpdateSerializer(serializers.ModelSerializer):
class Meta:
model = LogLevel
fields = "__all__"
list_serializer_class = LogLevelListSerializer
LogLevel view
class LogLevelList(MethodSerializerMixin,
generics.ListCreateAPIView):
"""
Log Level list API Endpoint.
"""
method_serializer_classes = {
("POST",): LogLevelCreateUpdateSerializer
}
def get_queryset(self):
"""
Queryset to use for endpoint.
"""
return LogLevel.objects.all()
def get_serializer(self, *args, **kwargs):
"""
Return the serializer instance that should be used for validating and
deserializing input, and for serializing output.
"""
serializer_class = self.get_serializer_class()
kwargs['context'] = self.get_serializer_context()
# check if many is required
if "data" in kwargs:
data = kwargs["data"]
# check if many is required
if isinstance(data, list):
kwargs["many"] = True
return serializer_class(*args, **kwargs)
MethodSerializerMixin
from rest_framework import exceptions
class MethodSerializerMixin(object):
"""
Utility class to apply a different serializer class depending
on the request method.
For example:
method_serializer_classes = {
("GET", ): MyModelListViewSerializer,
("PUT", "PATCH"): MyModelCreateUpdateSerializer
}
"""
method_serializer_classes = None
def get_serializer_class(self):
assert self.method_serializer_classes is not None, (
f"Expected view {self.__class__.__name__} should contain "
f"method_serializer_classes to get right serializer class."
)
for methods, serializer_cls in self.method_serializer_classes.items():
if self.request.method in methods:
return serializer_cls
raise exceptions.MethodNotAllowed(self.request.method)
Im passing in a json list of simple objects in the request. node is the foreign key id:
[{
"name": "logger1",
"level": 2,
"node": 1
},
{
"name": "logger2",
"level": 3,
"node": 1
}]
I expect the objects to be created and displayed to the client with success status. Currently, the objects are created in the db successfully but a 500: Server Error is returned and this is the stacktrace I see on Django server:
Internal Server Error: /api/clustering/loglevel/set/
Traceback (most recent call last):
File "/opt/cisco/env/iris/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner
response = get_response(request)
File "/opt/cisco/env/iris/lib/python3.6/site-packages/django/core/handlers/base.py", line 145, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/opt/cisco/env/iris/lib/python3.6/site-packages/django/core/handlers/base.py", line 143, in _get_response
response = response.render()
File "/opt/cisco/env/iris/lib/python3.6/site-packages/django/template/response.py", line 106, in render
self.content = self.rendered_content
File "/opt/cisco/env/iris/lib/python3.6/site-packages/rest_framework/response.py", line 72, in rendered_content
ret = renderer.render(self.data, accepted_media_type, context)
File "/opt/cisco/env/iris/lib/python3.6/site-packages/rest_framework/renderers.py", line 724, in render
context = self.get_context(data, accepted_media_type, renderer_context)
File "/opt/cisco/env/iris/lib/python3.6/site-packages/rest_framework/renderers.py", line 697, in get_context
'post_form': self.get_rendered_html_form(data, view, 'POST', request),
File "/opt/cisco/env/iris/lib/python3.6/site-packages/rest_framework/renderers.py", line 520, in get_rendered_html_form
return self.render_form_for_serializer(serializer)
File "/opt/cisco/env/iris/lib/python3.6/site-packages/rest_framework/renderers.py", line 528, in render_form_for_serializer
serializer.data,
File "/opt/cisco/env/iris/lib/python3.6/site-packages/rest_framework/serializers.py", line 765, in data
ret = super(ListSerializer, self).data
File "/opt/cisco/env/iris/lib/python3.6/site-packages/rest_framework/serializers.py", line 266, in data
self._data = self.get_initial()
File "/opt/cisco/env/iris/lib/python3.6/site-packages/rest_framework/serializers.py", line 600, in get_initial
return self.to_representation(self.initial_data)
File "/opt/cisco/env/iris/lib/python3.6/site-packages/rest_framework/serializers.py", line 683, in to_representation
self.child.to_representation(item) for item in iterable
File "/opt/cisco/env/iris/lib/python3.6/site-packages/rest_framework/serializers.py", line 683, in <listcomp>
self.child.to_representation(item) for item in iterable
File "/opt/cisco/env/iris/lib/python3.6/site-packages/rest_framework/serializers.py", line 527, in to_representation
ret[field.field_name] = field.to_representation(attribute)
File "/opt/cisco/env/iris/lib/python3.6/site-packages/rest_framework/relations.py", line 257, in to_representation
return value.pk
AttributeError: 'int' object has no attribute 'pk'
python==3.6
django==2.2.2
drf==3.8.2
The serializer.data property is only valid if you have a saved an instance to the serializer.
Either call serializer.save() or use serializer.validated_data to access data prior to saving.
Checkout this link for further information.
Had to handle this error by updating to_representation method on the PrimaryKeyRelatedField class
class NodePrimaryKeyField(serializers.PrimaryKeyRelatedField):
"""
Custom DRF serializer field for proper handling of
Node Foreign Key by ListSerializer on validation error
"""
def to_representation(self, value):
"""
Return pk value of serialized Node object
if available else return given ID value
"""
if self.pk_field is not None:
return self.pk_field.to_representation(value.pk)
return getattr(value, 'pk', value)
I have this model:
class Notification(BaseTimestampableModel):
# TYPES CONSTANTS HERE
# TYPE_CHOICES DICT HERE
sender = models.ForeignKey(User, related_name='sender_notifications')
receivers = models.ManyToManyField(User, related_name='receiver_notifications')
type = models.PositiveSmallIntegerField(choices=TYPE_CHOICES)
data = models.TextField()
sent = models.BooleanField(default=False)
class Meta:
verbose_name = _('Notification')
verbose_name_plural = _('Notifications')
def send(self):
# Logic for sending notification here
self.sent = True
self.save()
For other hand, I've this "static" class:
class ChatNotifications:
#staticmethod
def message_created(message, chat):
"""
Send a notification when a chat message is created
to all users in chat except to the message's sender.
"""
sender = message.user
data = {
'text': message.text,
'phone': str(sender.phone_prefix) + str(sender.phone),
'chatid': chat.uuid.hex,
'time': timezone.now().timestamp(),
'type': 'text',
'msgid': message.uuid.hex
}
notification = Notification(
sender=sender,
receivers=chat.get_other_users(sender),
type=Notification.TYPE_CHAT_MESSAGE,
data=json.dumps(data)
)
notification.send()
But when I call ChatNotifications.message_created(msg, chat) (message and chat are previusly saved), I get this error:
ValueError: "<Notification: Notification object>" needs to have a value for field "notification" before this many-to-many relationship can be used.
Researching on Google, I try do this, but this don't solved my problem.
With debug, I checked the error is throwing when Model constructor is called.
This is the trace:
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "/home/vagrant/petycash/apps/chats/notifications.py", line 45, in message_created
data=json.dumps(data)
File "/usr/local/lib/python3.5/dist-packages/django/db/models/base.py", line 550, in __init__
setattr(self, prop, kwargs[prop])
File "/usr/local/lib/python3.5/dist-packages/django/db/models/fields/related_descriptors.py", line 499, in __set__
manager = self.__get__(instance)
File "/usr/local/lib/python3.5/dist-packages/django/db/models/fields/related_descriptors.py", line 476, in __get__
return self.related_manager_cls(instance)
File "/usr/local/lib/python3.5/dist-packages/django/db/models/fields/related_descriptors.py", line 783, in __init__
(instance, self.source_field_name))
ValueError: "<Notification: Notification object>" needs to have a value for field "notification" before this many-to-many relationship can be used.
You can’t associate Notification with a User until it’s been saved.
So you have to save Notification first then you can add receivers
notification = Notification(
sender=sender,
type=Notification.TYPE_CHAT_MESSAGE,
data=json.dumps(data)
).save()
# If chat.get_other_users(sender) return a queryset
receivers = chat.get_other_users(sender)
for receiver in receivers:
notification.receivers.add(receiver)
# or you can also simply assign the whole list as it's already empty after new create
# >>> notification.receivers = recievers
notification.send()
I'm getting a strange 500 error when issuing an OPTION request to an endpoint in my API built with Django Rest Framework. GET, POST, PUT all work fine and DELETE is not allowed.
When issuing an OPTION request to the endpoint, I get the following error and traceback:
Traceback:
File "/Users/awwester/Sites/django/rlg/lib/python3.4/site-packages/django/core/handlers/base.py" in get_response
111. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Users/awwester/Sites/django/rlg/lib/python3.4/site-packages/django/views/decorators/csrf.py" in wrapped_view
57. return view_func(*args, **kwargs)
File "/Users/awwester/Sites/django/rlg/lib/python3.4/site-packages/rest_framework/viewsets.py" in view
85. return self.dispatch(request, *args, **kwargs)
File "/Users/awwester/Sites/django/rlg/lib/python3.4/site-packages/rest_framework/views.py" in dispatch
452. response = self.handle_exception(exc)
File "/Users/awwester/Sites/django/rlg/lib/python3.4/site-packages/rest_framework/views.py" in dispatch
449. response = handler(request, *args, **kwargs)
File "/Users/awwester/Sites/django/rlg/lib/python3.4/site-packages/rest_framework/views.py" in options
463. data = self.metadata_class().determine_metadata(request, self)
File "/Users/awwester/Sites/django/rlg/lib/python3.4/site-packages/rest_framework/metadata.py" in determine_metadata
63. actions = self.determine_actions(request, view)
File "/Users/awwester/Sites/django/rlg/lib/python3.4/site-packages/rest_framework/metadata.py" in determine_actions
89. actions[method] = self.get_serializer_info(serializer)
File "/Users/awwester/Sites/django/rlg/lib/python3.4/site-packages/rest_framework/metadata.py" in get_serializer_info
106. for field_name, field in serializer.fields.items()
File "/Users/awwester/Sites/django/rlg/lib/python3.4/site-packages/rest_framework/metadata.py" in <listcomp>
106. for field_name, field in serializer.fields.items()
File "/Users/awwester/Sites/django/rlg/lib/python3.4/site-packages/rest_framework/metadata.py" in get_field_info
129. if hasattr(field, 'choices'):
File "/Users/awwester/Sites/django/rlg/lib/python3.4/site-packages/rest_framework/relations.py" in choices
382. for item in iterable
Exception Type: TypeError at /v1/powerChatSessions
Exception Value: 'NoneType' object is not iterable
Here is the model, serializer, and view:
# models.py - error happens when issuing OPTIONS /powerChatSession
class VideoConversation(models.Model):
"""
Capture data about a video chat session
SO note: this is inherited by other classes besides PowerChat
"""
created = models.DateTimeField(auto_now_add=True)
end = models.DateTimeField(null=True, blank=True)
users = models.ManyToManyField(User)
class PowerChat(VideoConversation):
"""
power chat session
"""
start = models.DateTimeField(null=True, blank=True)
extended = models.BooleanField(default=False)
active = models.BooleanField(default=False)
# serializers.py
class PowerChatSerializer(serializers.ModelSerializer):
class Meta:
model = PowerChat
read_only_fields = ('users', 'start', 'extended',)
# views.py
class PowerChatViewSet(ModelViewSet):
queryset = PowerChat.objects.all()
permission_classes = (PowerChatPermission,)
serializer_class = PowerChatSerializer
resource_name = "powerChatSession"
Any ideas why this is happening? It has something to do with the users field, and it seems that it could be a bug with Django Rest Framework? It's checking if the field has the choices kwarg, which it doesn't, but apparently DRF thinks it does?
I think this issue was addressed by:
https://github.com/tomchristie/django-rest-framework/issues/3115
The gist is that "At the moment, self.action is None in viewsets if I get an OPTIONS request."
This issue ceased for me after I upgraded to djangorestframework-3.2.3
I am trying to upload files via a Multipart/Form-Data form and Tastypie API and am running into some issues:
My Model:
class Client(models.Model):
account = models.ForeignKey(Account)
client_image = models.FileField(upload_to=client_image_path, default="/assets/img/default-user-image.png", blank=True, null=True)
client_image_thumb = models.FileField(upload_to=client_image_thumb_path, default="/assets/img/default-user-image.png", blank=True, null=True)
I am using a custom deserialize method as outlined in Tastypie Issue#42:
class MultipartResource(object):
def deserialize(self, request, data, format=None):
if not format:
format = request.META.get('CONTENT_TYPE', 'application/json')
if format == 'application/x-www-form-urlencoded':
return request.POST
if format.startswith('multipart'):
data = request.POST.copy()
data.update(request.FILES)
return data
return super(MultipartResource, self).deserialize(request, data, format)
def put_detail(self, request, **kwargs):
if request.META.get('CONTENT_TYPE').startswith('multipart') and \
not hasattr(request, '_body'):
request._body = ''
return super(MultipartResource, self).put_detail(request, **kwargs)
And here is my corresponding ModelResource:
class ClientResource(MultipartResource, ModelResource):
account = fields.ForeignKey(AccountResource, 'account')
class Meta():
queryset = Client.objects.all()
always_return_data = True
resource_name = 'account/clients/client-info'
authorization = AccountLevelAuthorization()
list_allowed_methods = ['get','post','put','delete','patch']
detail_allowed_methods = ['get', 'post', 'put', 'delete','patch']
authentication = ApiKeyAuthentication()
filtering = {
'username': ALL,
}
If I do a POST with content-type application/JSON and dont include the client_image field, it will successfully create a new Client Object. This indicates that the models/resources are working as they should.
However, when I try to use a Multipart/Form-Data content type I can see that it gets through my deserializer appropriately with this payload:
------WebKitFormBoundaryp0Q7Q9djlsvVGwbb
Content-Disposition: form-data; name="{%0D%0A%22account%22"
"/api/v1/account/account-info/21/",
------WebKitFormBoundaryp0Q7Q9djlsvVGwbb
Content-Disposition: form-data; name="client_image"; filename="donavan.jpg"
Content-Type: image/jpeg
------WebKitFormBoundaryp0Q7Q9djlsvVGwbb--
I am also seeing this QueryDict while debugging, which shows the InMemoryUploadedFile correctly:
<QueryDict: {u'client_image': [<InMemoryUploadedFile: donavan.jpg (image/jpeg)>], u'{%0D%0A%22account%22': [u'"/api/v1/account/account-info/21/"']}>
but I keep getting this error:
{ error_message: "" traceback: "Traceback (most recent call last):
File
"/Users/stevewirig/Documents/www/vu/venv/lib/python2.7/site-packages/tastypie/resources.py",
line 202, in wrapper response = callback(request, *args, **kwargs)
File
"/Users/stevewirig/Documents/www/vu/venv/lib/python2.7/site-packages/tastypie/resources.py",
line 440, in dispatch_list return self.dispatch('list', request,
**kwargs) File "/Users/stevewirig/Documents/www/vu/venv/lib/python2.7/site-packages/tastypie/resources.py",
line 472, in dispatch response = method(request, **kwargs) File
"/Users/stevewirig/Documents/www/vu/venv/lib/python2.7/site-packages/tastypie/resources.py",
line 1328, in post_list updated_bundle = self.obj_create(bundle,
**self.remove_api_resource_names(kwargs)) File "/Users/stevewirig/Documents/www/vu/venv/lib/python2.7/site-packages/tastypie/resources.py",
line 2104, in obj_create bundle = self.full_hydrate(bundle) File
"/Users/stevewirig/Documents/www/vu/venv/lib/python2.7/site-packages/tastypie/resources.py",
line 890, in full_hydrate value = field_object.hydrate(bundle) File
"/Users/stevewirig/Documents/www/vu/venv/lib/python2.7/site-packages/tastypie/fields.py",
line 732, in hydrate value = super(ToOneField, self).hydrate(bundle)
File
"/Users/stevewirig/Documents/www/vu/venv/lib/python2.7/site-packages/tastypie/fields.py",
line 165, in hydrate elif self.attribute and getattr(bundle.obj,
self.attribute, None): File
"/Users/stevewirig/Documents/www/vu/venv/lib/python2.7/site-packages/django/db/models/fields/related.py",
line 343, in get raise self.field.rel.to.DoesNotExist DoesNotExist
" }
Any ideas where this could be broken? Thanks in advance!
This happened to me when I post a data without providing necessary fields. Those fields that cannot be null must be provided while posting.
Initialize the serializer as follows:
serializer = Serializer(formats=['json'])