def create(self, request, note_id, *args, **kwargs): note = get_object_or_404(CommunicationNote, id=note_id) if not note.author.id == request.user.id: return Response([{ 'non_field_errors': 'You must be owner of the note to attach a file.' }], status=status.HTTP_403_FORBIDDEN) # Validate attachment. attachment_formset = None if request.FILES: data = request.POST.copy() data.update({ 'form-TOTAL_FORMS': len([k for k in request.FILES if k.endswith('-attachment')]), 'form-INITIAL_FORMS': 0, 'form-MAX_NUM_FORMS': comm.MAX_ATTACH }) if data['form-TOTAL_FORMS'] > comm.MAX_ATTACH: # TODO: use formset validate_max=True in Django 1.6. return Response([{ 'non_field_errors': 'Maximum of %s files can be attached.' }], status=status.HTTP_400_BAD_REQUEST) attachment_formset = forms.CommAttachmentFormSet( data=data, files=request.FILES or None) if not attachment_formset.is_valid(): return Response(attachment_formset.errors, status=status.HTTP_400_BAD_REQUEST) else: return Response([{ 'non_field_errors': 'No files were attached.' }], status=status.HTTP_400_BAD_REQUEST) # Create attachment. if attachment_formset: create_attachments(note, attachment_formset) return Response(NoteSerializer(note, context={ 'request': request }).data, status=status.HTTP_201_CREATED)
def create(self, request, note_id, *args, **kwargs): note = get_object_or_404(CommunicationNote, id=note_id) if not note.author.id == request.amo_user.id: return Response( [{'non_field_errors': 'You must be owner of the note to attach a file.'}], status=status.HTTP_403_FORBIDDEN) # Validate attachment. attachment_formset = None if request.FILES: data = request.POST.copy() data.update({ 'form-TOTAL_FORMS': len([k for k in request.FILES if k.endswith('-attachment')]), 'form-INITIAL_FORMS': 0, 'form-MAX_NUM_FORMS': comm.MAX_ATTACH }) if data['form-TOTAL_FORMS'] > comm.MAX_ATTACH: # TODO: use formset validate_max=True in Django 1.6. return Response( [{'non_field_errors': 'Maximum of %s files can be attached.'}], status=status.HTTP_400_BAD_REQUEST) attachment_formset = forms.CommAttachmentFormSet( data=data, files=request.FILES or None) if not attachment_formset.is_valid(): return Response(attachment_formset.errors, status=status.HTTP_400_BAD_REQUEST) else: return Response([{'non_field_errors': 'No files were attached.'}], status=status.HTTP_400_BAD_REQUEST) # Create attachment. if attachment_formset: create_attachments(note, attachment_formset) return Response( NoteSerializer(note, context={'request': request}).data, status=status.HTTP_201_CREATED)