模型保存时出现Django类型错误

时间:2016-03-09 13:43:24

标签: python django

我有一个Document的模型(名为FileField)。如果我尝试创建所述模型的实例,则在尝试保存时会得到TypeError exception

models.py

class Document(CompanyModel):

    def __unicode__(self):
        return self.name

    file = models.FileField()
    issue = models.ForeignKey(Issue)
    name = models.CharField(max_length=50)


class CompanyModel(models.Model):

    id_number = models.PositiveIntegerField(blank=True)
    company = models.ForeignKey(Company)

    def get_next_nr(self):
        current_max = self.__class__.objects.filter(company=self.company)\
            .aggregate(models.Max('id_number'))['id_number__max'] or 0
        return current_max + 1

    def save(self, *args, **kwargs):
        if self.id_number is None:
            # Model is being created
            self.id_number = self.get_next_nr()
        super(CompanyModel, self).save(*args, **kwargs)

    class Meta:
        abstract = True
        unique_together = ('id_number', 'company')

views.py

@csrf_exempt
@login_required
def image_upload(request):
    upload_to = getattr(settings, 'FROALA_UPLOAD_PATH', 'editor/images/')
    if 'image' in request.POST:
        data = request.POST['image']  # Getting the object from the post request
        decoded_data = data.split(',')[1].decode('base64')
        path = default_storage.save(
            os.path.join(upload_to, 'pasted_image'), ContentFile(decoded_data))
        link = getattr(settings, 'SITE_URL') + default_storage.url(path)
        company = request.user.employee.company
        return HttpResponse(
            json.dumps({'link': link}), content_type="application/json")

    if 'file' in request.FILES:
        the_file = request.FILES['file']
        allowed_types = [
            'image/jpeg', 'image/jpg', 'image/pjpeg',
            'image/x-png', 'image/png', 'image/gif']
        if not the_file.content_type in allowed_types:
            return HttpResponse(
                json.dumps({'error': _('You can only upload images.')}),
                content_type="application/json")
        # Other data on the request.FILES dictionary:
        # filesize = len(file['content'])
        # filetype = file['content-type']
        path = default_storage.save(
            os.path.join(upload_to, the_file.name), the_file)
        link = getattr(settings, 'SITE_URL') + default_storage.url(path)
        # return JsonResponse({'link': link})
        company = request.user.employee.company

        url_path = default_storage.url(path)

        doc_id = 0

        try:
            doc = Document.objects.create(
                file=url_path[1:],
                issue=Issue.objects.get(
                    company=company,
                    id_number=int(request.POST.get('issue_id', None))),
                name=the_file.name,
                company=company)
            doc_id = doc.id_number
        except:
            pass

        return HttpResponse(
            json.dumps({'link': link, 'doc_id': doc_id}),
            content_type="application/json")

这是我尝试保存实例时获得的异常的堆栈跟踪:

堆栈跟踪

File "/Library/Python/2.7/site-packages/django/core/handlers/base.py" in get_response
  132.                     response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Library/Python/2.7/site-packages/django/views/decorators/csrf.py" in wrapped_view
  58.         return view_func(*args, **kwargs)
File "/Library/Python/2.7/site-packages/django/contrib/auth/decorators.py" in _wrapped_view
  22.                 return view_func(request, *args, **kwargs)
File "/Users/alejandrodejesus/Projects/NeosGoal/froala_editor/views.py" in image_upload
  57.             company=company)
File "/Library/Python/2.7/site-packages/django/db/models/manager.py" in manager_method
  127.                 return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/Library/Python/2.7/site-packages/django/db/models/query.py" in create
  348.         obj.save(force_insert=True, using=self.db)
File "/Users/alejandrodejesus/Projects/NeosGoal/NeosGoal/models.py" in save
  19.         super(CompanyModel, self).save(*args, **kwargs)
File "/Library/Python/2.7/site-packages/django/db/models/base.py" in save
  710.                        force_update=force_update, update_fields=update_fields)
File "/Library/Python/2.7/site-packages/django/db/models/base.py" in save_base
  747.                                    update_fields=update_fields, raw=raw, using=using)
File "/Library/Python/2.7/site-packages/django/dispatch/dispatcher.py" in send
  201.             response = receiver(signal=self, sender=sender, **named)
File "/Users/alejandrodejesus/Projects/NeosGoal/NeosGoal/signals.py" in send_socket
  11.     publish_event(event_name, connection.tenant, instance=instance)
File "/Users/alejandrodejesus/Projects/NeosGoal/NeosGoal/sockets.py" in publish_event
  34.         model_to_json = json.dumps(instance_data, cls=DjangoJSONEncoder)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/__init__.py" in dumps
  250.         sort_keys=sort_keys, **kw).encode(obj)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/encoder.py" in encode
  207.         chunks = self.iterencode(o, _one_shot=True)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/encoder.py" in iterencode
  270.         return _iterencode(o, 0)
File "/Library/Python/2.7/site-packages/django/core/serializers/json.py" in default
  112.             return super(DjangoJSONEncoder, self).default(o)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/encoder.py" in default
  184.         raise TypeError(repr(o) + " is not JSON serializable")

Exception Type: TypeError at /froala_editor/image_upload/
Exception Value: <FieldFile: uploads/editor/images/Screen%20Shot%202016-03-02%20at%202.39.12%20PM.png> is not JSON serializable

我在Django文档(https://docs.djangoproject.com/es/1.9/ref/models/fields/#filefield)中读到,如果我尝试使用FileField作为主键,我会收到类型错误,但我不认为是这种情况。我错了吗?

对我缺少的东西有任何想法吗?

0 个答案:

没有答案