Esempio n. 1
0
def saveNewInstrumentData(request, instrumentName, jsonResult=False):
    errors = None
    if request.method == 'POST':
        form = BasaltInstrumentDataForm(request.POST, request.FILES)
        if form.is_valid():
            if request.user.is_authenticated():
                user = request.user
            else:
                user = None
            instrument = form.cleaned_data["instrument"]
            messages.success(request, 'Instrument data is successfully saved.' )
            importFxn = lookupImportFunctionByName(settings.XGDS_INSTRUMENT_IMPORT_MODULE_PATH, 
                                                   instrument.dataImportFunctionName)
            object_id = None
            if 'object_id' in request.POST:
                object_id = int(request.POST['object_id'])
            result = importFxn(instrument=instrument, 
                               portableDataFile=request.FILES.get("portableDataFile", None),
                               manufacturerDataFile=request.FILES.get("manufacturerDataFile", None),
                               utcStamp=form.cleaned_data["dataCollectionTime"], 
                               timezone=form.getTimezone(), 
                               vehicle=form.getVehicle(),
                               name=form.cleaned_data['name'],
                               description=form.cleaned_data['description'],
                               minerals=form.cleaned_data['minerals'],
                               user=user,
                               latitude=form.cleaned_data['lat'],
                               longitude=form.cleaned_data['lon'],
                               altitude=form.cleaned_data['alt'],
                               collector=form.cleaned_data['collector'],
                               object_id=object_id)
            if result['status'] == 'success':
                if 'relay' in request.POST:
                    theModel = getModelByName(settings.XGDS_MAP_SERVER_JS_MAP[result['modelName']]['model'])
                    theInstance = theModel.objects.get(pk=result['pk'])
                    deletePostKey(request.POST, 'relay')
                    addRelay(theInstance, request.FILES, json.dumps(request.POST), request.get_full_path())

                if jsonResult:
                    return HttpResponse(json.dumps(result), content_type='application/json')
                else:
                    return HttpResponseRedirect(reverse('search_map_single_object', kwargs={'modelPK':result['pk'],
                                                                                            'modelName':result['modelName']}))
            else:
                errors = result['message']
        else:
            errors = str(form.errors)
            print 'form errors in receiving instrument data'
        
        if jsonResult:
            return HttpResponse(json.dumps({'status': 'error', 'message': errors}), content_type='application/json', status=httplib.NOT_ACCEPTABLE)
        else:
            messages.error(request, 'Errors %s' % errors)
            return render(request,
                          'xgds_instrument/importBasaltInstrumentData.html',
                          {'form': form,
                           'errors': form.errors,
                           'instrumentDataImportUrl': reverse('save_instrument_data', kwargs={'instrumentName': instrumentName}),
                           'instrumentType': instrumentName},
                          status=httplib.NOT_ACCEPTABLE)      
Esempio n. 2
0
def editInstrumentData(request, instrument_name, pk):
    """
    Renders instrument data edit page -- if data exists, displays the existing data.
    """
    mapDict = settings.XGDS_MAP_SERVER_JS_MAP[instrument_name]
    INSTRUMENT_MODEL = LazyGetModelByName(mapDict['model'])
    dataProduct = INSTRUMENT_MODEL.get().objects.get(pk=pk)
    jsonDict = dataProduct.toMapDict()

    # get existing data.
    if 'edit_form_class' in mapDict:
        form = getFormByName(mapDict['edit_form_class'])(initial=jsonDict)
    else:
        form = BasaltInstrumentDataForm(initial=jsonDict)

    form.editingSetup(dataProduct)

    # convert to local time.
    utcTime = dataProduct.acquisition_time
    timezone = dataProduct.acquisition_timezone
    acquisitionTime = utcToTimeZone(utcTime, timezone)
    acquisitionTime = acquisitionTime.strftime('%m/%d/%Y %H:%M')

    form.fields['dataCollectionTime'].initial = acquisitionTime
    form.fields['timezone'].initial = timezone

    # hide the two file fields
    #     form.fields['portableDataFile'].widget = forms.HiddenInput()
    #     form.fields['manufacturerDataFile'].widget = forms.HiddenInput()
    #
    updateInstrumentDataUrl = reverse('instrument_data_update',
                                      kwargs={
                                          'instrument_name': instrument_name,
                                          'pk': pk
                                      })
    return render(
        request,
        'xgds_instrument/editInstrumentData.html',
        {
            'form': form,
            'instrument_name': instrument_name,
            'dataProductJson': json.dumps(jsonDict, cls=DatetimeJsonEncoder),
            'updateInstrumentDataUrl': updateInstrumentDataUrl,
            'manufacturer_data_file_url':
            dataProduct.manufacturer_data_file_url,
            'portable_data_file_url': dataProduct.portable_data_file_url
        },
    )
Esempio n. 3
0
def getInstrumentDataImportPage(request, instrumentName):
    form = BasaltInstrumentDataForm()
    instrument = ScienceInstrument.getInstrument(instrumentName)
    form.fields['instrument'].initial = instrument.id
    errors = ""
         
    instrumentDataImportUrl = reverse('save_instrument_data', kwargs={'instrumentName': instrumentName})
    return render(request,
                  'xgds_instrument/importBasaltInstrumentData.html',
                  {'form': form,
                   'errors': errors,
                   'instrumentDataImportUrl': instrumentDataImportUrl,
                   'instrumentType': instrumentName})
Esempio n. 4
0
def saveUpdatedInstrumentData(request, instrument_name, pk):
    """
    Updates instrument data on save.
    """

    if request.method == 'POST':
        mapDict = settings.XGDS_MAP_SERVER_JS_MAP[instrument_name]
        INSTRUMENT_MODEL = LazyGetModelByName(mapDict['model'])
        dataProduct = INSTRUMENT_MODEL.get().objects.get(pk=pk)

        # get existing data.
        if 'edit_form_class' in mapDict:
            form = getFormByName(mapDict['edit_form_class'])(request.POST,
                                                             request.FILES)
        else:
            form = BasaltInstrumentDataForm(request.POST, request.FILES)

        try:
            form.is_valid()
        except:
            pass

        for key in form.changed_data:
            value = form.cleaned_data[key]
            if not hasattr(value, 'read'):
                if not isinstance(value, datetime.datetime):
                    setattr(dataProduct, key, value)
            else:
                form.handleFileUpdate(dataProduct, key)
        # save the update info into the model.


#         postDict = request.POST.dict()
#         dataProduct.name = postDict['name']
#         dataProduct.description = postDict['description']
#         dataProduct.minerals = postDict['minerals']
#         resourceId = postDict['resource']
#         if resourceId:
#             resource = BasaltResource.objects.get(id=resourceId)
#             dataProduct.resource = resource

        dataProduct.acquisition_time = form.cleaned_data['dataCollectionTime']

        if (('lat' in form.cleaned_data) and
            ('lon' in form.cleaned_data)) or ('alt' in form.cleaned_data):
            editInstrumentDataPosition(dataProduct, form.cleaned_data['lat'],
                                       form.cleaned_data['lon'],
                                       form.cleaned_data['alt'])
        dataProduct.save()

        messages.success(request, 'Instrument data successfully saved!')

        return HttpResponseRedirect(
            reverse('search_map_single_object',
                    kwargs={
                        'modelPK': pk,
                        'modelName': instrument_name
                    }))