Exemple #1
0
def map_metadata(request, mapid, template='maps/cread_map_metadata.html'):

    map_obj = _resolve_map(request, mapid, 'base.change_resourcebase_metadata',
                           _PERMISSION_MSG_VIEW)

    cmapqs = CReadResource.objects.filter(resource=map_obj)

    if len(cmapqs) == 0:
        logger.info('cread_resource does not exist for map %r', map_obj)
        cread_resource = None
    else:
        logger.debug('cread_resource found for map %r (%d)', map_obj,
                     len(cmapqs))
        cread_resource = cmapqs[0]

    poc = map_obj.poc
    metadata_author = map_obj.metadata_author
    topic_category = map_obj.category
    cread_subcategory = cread_resource.subcategory if cread_resource else None

    if request.method == "POST":
        baseinfo_form = CReadBaseInfoForm(request.POST, prefix="baseinfo")
        map_form = CReadMapForm(
            #map_form = MapForm(
            request.POST,
            instance=map_obj,
            prefix="resource")
        category_form = CategoryForm(
            request.POST,
            prefix="category_choice_field",
            initial=int(request.POST["category_choice_field"])
            if "category_choice_field" in request.POST else None)
        cread_subcategory_form = CReadSubCategoryForm(
            request.POST,
            prefix="cread_subcategory_choice_field",
            initial=int(request.POST["cread_subcategory_choice_field"])
            if "cread_subcategory_choice_field" in request.POST else None)
    else:
        baseinfo_form = CReadBaseInfoForm(prefix="baseinfo",
                                          initial={
                                              'title': map_obj.title,
                                              'abstract': map_obj.abstract
                                          })
        map_form = CReadMapForm(instance=map_obj, prefix="resource")
        category_form = CategoryForm(
            prefix="category_choice_field",
            initial=topic_category.id if topic_category else None)
        cread_subcategory_form = CReadSubCategoryForm(
            prefix="cread_subcategory_choice_field",
            initial=cread_subcategory.id if cread_subcategory else None)

    if request.method == "POST" \
            and baseinfo_form.is_valid() \
            and map_form.is_valid() \
            and cread_subcategory_form.is_valid():

        new_title = strip_tags(baseinfo_form.cleaned_data['title'])
        new_abstract = strip_tags(baseinfo_form.cleaned_data['abstract'])

        new_poc = map_form.cleaned_data['poc']
        new_author = map_form.cleaned_data['metadata_author']
        new_keywords = map_form.cleaned_data['keywords']

        if new_poc is None:
            if poc is None:
                poc_form = ProfileForm(request.POST,
                                       prefix="poc",
                                       instance=poc)
            else:
                poc_form = ProfileForm(request.POST, prefix="poc")
            if poc_form.has_changed and poc_form.is_valid():
                new_poc = poc_form.save()

        if new_author is None:
            if metadata_author is None:
                author_form = ProfileForm(request.POST,
                                          prefix="author",
                                          instance=metadata_author)
            else:
                author_form = ProfileForm(request.POST, prefix="author")
            if author_form.has_changed and author_form.is_valid():
                new_author = author_form.save()

        # CRead category
        # note: call to is_valid is needed to compute the cleaned data
        if (cread_subcategory_form.is_valid()):
            logger.info("Checking CReadLayer record %r ",
                        cread_subcategory_form.is_valid())
            cread_subcat_id = cread_subcategory_form.cleaned_data[
                'cread_subcategory_choice_field']
            new_creadsubcategory = CReadSubCategory.objects.get(
                id=cread_subcat_id)
            new_creadcategory = new_creadsubcategory.category
            logger.debug("Selected cread cat/subcat: %s : %s / %s",
                         new_creadcategory.identifier, new_creadcategory.name,
                         new_creadsubcategory.identifier)

            if cread_resource:
                logger.info("Update CReadResource record")
            else:
                logger.info("Create new CReadResource record")
                cread_resource = CReadResource()
                cread_resource.resource = map_obj

            cread_resource.category = new_creadcategory
            cread_resource.subcategory = new_creadsubcategory
            cread_resource.save()
        else:
            new_creadsubcategory = None
            logger.info("CRead subcategory form is not valid")
        # End cread category

        # Update original topic category according to cread category
        if category_form.is_valid():
            new_category = TopicCategory.objects.get(
                id=category_form.cleaned_data['category_choice_field'])
        elif new_creadsubcategory:
            logger.debug("Assigning default ISO category from CREAD category")
            new_category = TopicCategory.objects.get(
                id=new_creadsubcategory.relatedtopic.id)

        if new_poc is not None and new_author is not None:
            the_map = map_form.save()
            the_map.poc = new_poc
            the_map.metadata_author = new_author
            the_map.title = new_title
            the_map.abstract = new_abstract
            the_map.save()
            the_map.keywords.clear()
            the_map.keywords.add(*new_keywords)
            the_map.category = new_category
            the_map.save()

            if getattr(settings, 'SLACK_ENABLED', False):
                try:
                    from geonode.contrib.slack.utils import build_slack_message_map, send_slack_messages
                    send_slack_messages(
                        build_slack_message_map("map_edit", the_map))
                except:
                    print "Could not send slack message for modified map."

            return HttpResponseRedirect(
                reverse('map_detail', args=(map_obj.id, )))

    if poc is None:
        poc_form = ProfileForm(request.POST, prefix="poc")
    else:
        if poc is None:
            poc_form = ProfileForm(instance=poc, prefix="poc")
        else:
            map_form.fields['poc'].initial = poc.id
            poc_form = ProfileForm(prefix="poc")
            poc_form.hidden = True

    if metadata_author is None:
        author_form = ProfileForm(request.POST, prefix="author")
    else:
        if metadata_author is None:
            author_form = ProfileForm(instance=metadata_author,
                                      prefix="author")
        else:
            map_form.fields['metadata_author'].initial = metadata_author.id
            author_form = ProfileForm(prefix="author")
            author_form.hidden = True

    # creates cat - subcat association
    categories_struct = []
    for category in CReadCategory.objects.all():
        subcats = []
        for subcat in CReadSubCategory.objects.filter(category=category):
            subcats.append(subcat.id)
        categories_struct.append((category.id, category.description, subcats))

    return render_to_response(
        template,
        RequestContext(
            request, {
                "map": map_obj,
                "map_form": map_form,
                "poc_form": poc_form,
                "author_form": author_form,
                "category_form": category_form,
                "baseinfo_form": baseinfo_form,
                "cread_sub_form": cread_subcategory_form,
                "cread_categories": categories_struct
            }))
Exemple #2
0
def layer_metadata_create(request,
                          layername,
                          template='layers/cread_layer_metadata.html',
                          publish=False):
    logger.debug("*** ENTER CREAD:layer_metadata_create (pub=%s)", publish)

    layer = _resolve_layer(request, layername,
                           'base.change_resourcebase_metadata',
                           _PERMISSION_MSG_METADATA)

    clayerqs = CReadResource.objects.filter(resource=layer)

    if len(clayerqs) == 0:
        logger.info('cread_resource does not exist for layer %r', layer)
        cread_resource = None
    else:
        logger.debug('cread_resource found for layer %r (%d)', layer,
                     len(clayerqs))
        cread_resource = clayerqs[0]

    layer_attribute_set = inlineformset_factory(
        Layer,
        Attribute,
        extra=0,
        form=LayerAttributeForm,
    )

    topic_category = layer.category
    cread_subcategory = cread_resource.subcategory if cread_resource else None

    poc = layer.poc
    metadata_author = layer.metadata_author

    if request.method == "POST":
        baseinfo_form = CReadBaseInfoForm(request.POST, prefix="baseinfo")
        layer_form = CReadLayerForm(request.POST,
                                    instance=layer,
                                    prefix="resource")
        attribute_form = layer_attribute_set(
            request.POST,
            instance=layer,
            prefix="layer_attribute_set",
            queryset=Attribute.objects.order_by('display_order'))
        category_form = CategoryForm(
            request.POST,
            prefix="category_choice_field",
            initial=int(request.POST["category_choice_field"])
            if "category_choice_field" in request.POST else None)
        #cread_category_form = CReadCategoryForm(
        #request.POST,
        #prefix="cread_category_choice_field",
        #initial=int(
        #request.POST["cread_category_choice_field"]) if "cread_category_choice_field" in request.POST else None)
        cread_subcategory_form = CReadSubCategoryForm(
            request.POST,
            prefix="cread_subcategory_choice_field",
            initial=int(request.POST["cread_subcategory_choice_field"])
            if "cread_subcategory_choice_field" in request.POST else None)
    else:
        baseinfo_form = CReadBaseInfoForm(prefix="baseinfo",
                                          initial={
                                              'title': layer.title,
                                              'abstract': layer.abstract
                                          })
        layer_form = CReadLayerForm(instance=layer, prefix="resource")
        #_preprocess_fields(layer_form)

        attribute_form = layer_attribute_set(
            instance=layer,
            prefix="layer_attribute_set",
            queryset=Attribute.objects.order_by('display_order'))
        category_form = CategoryForm(
            prefix="category_choice_field",
            initial=topic_category.id if topic_category else None)
        #cread_category_form = CReadCategoryForm(
        #prefix="cread_category_choice_field",
        #initial=cread_category.id if cread_category else None)
        cread_subcategory_form = CReadSubCategoryForm(
            prefix="cread_subcategory_choice_field",
            initial=cread_subcategory.id if cread_subcategory else None)

    if request.method == "POST" \
        and baseinfo_form.is_valid() \
        and layer_form.is_valid() \
        and attribute_form.is_valid() \
        and cread_subcategory_form.is_valid():

        new_poc = layer_form.cleaned_data['poc']
        new_author = layer_form.cleaned_data['metadata_author']
        new_keywords = layer_form.cleaned_data['keywords']

        if new_poc is None:
            if poc is None:
                poc_form = ProfileForm(request.POST,
                                       prefix="poc",
                                       instance=poc)
            else:
                poc_form = ProfileForm(request.POST, prefix="poc")
            if poc_form.has_changed and poc_form.is_valid():
                new_poc = poc_form.save()

        if new_author is None:
            if metadata_author is None:
                author_form = ProfileForm(request.POST,
                                          prefix="author",
                                          instance=metadata_author)
            else:
                author_form = ProfileForm(request.POST, prefix="author")
            if author_form.has_changed and author_form.is_valid():
                new_author = author_form.save()

        # CRead category
        # note: call to is_valid is needed to compute the cleaned data
        if (cread_subcategory_form.is_valid()):
            logger.info("Checking CReadLayer record %r ",
                        cread_subcategory_form.is_valid())
            #cread_cat_id = cread_category_form.cleaned_data['cread_category_choice_field']
            #cread_cat_id = cread_cat_id if cread_cat_id else 1
            #new_creadcategory = CReadCategory.objects.get(id=cread_cat_id)
            cread_subcat_id = cread_subcategory_form.cleaned_data[
                'cread_subcategory_choice_field']
            new_creadsubcategory = CReadSubCategory.objects.get(
                id=cread_subcat_id)
            new_creadcategory = new_creadsubcategory.category
            logger.debug("Selected cread cat/subcat: %s : %s / %s",
                         new_creadcategory.identifier, new_creadcategory.name,
                         new_creadsubcategory.identifier)

            if cread_resource:
                logger.info("Update CReadResource record")
            else:
                logger.info("Create new CReadResource record")
                cread_resource = CReadResource()
                cread_resource.resource = layer

            cread_resource.category = new_creadcategory
            cread_resource.subcategory = new_creadsubcategory
            cread_resource.save()
            # End cread category
        else:
            new_creadsubcategory = None
            logger.info("CRead subcategory form is not valid")

        if category_form.is_valid():
            new_category = TopicCategory.objects.get(
                id=category_form.cleaned_data['category_choice_field'])
        elif new_creadsubcategory:
            logger.debug("Assigning default ISO category")
            new_category = TopicCategory.objects.get(
                id=new_creadsubcategory.relatedtopic.id)

        for form in attribute_form.cleaned_data:
            la = Attribute.objects.get(id=int(form['id'].id))
            la.description = form["description"]
            la.attribute_label = form["attribute_label"]
            la.visible = form["visible"]
            la.display_order = form["display_order"]
            la.save()

        if new_poc is not None and new_author is not None:
            new_keywords = layer_form.cleaned_data['keywords']
            layer.keywords.clear()
            layer.keywords.add(*new_keywords)
            the_layer = layer_form.save()
            the_layer.poc = new_poc
            the_layer.metadata_author = new_author
            Layer.objects.filter(id=the_layer.id).update(
                category=new_category,
                title=baseinfo_form.cleaned_data['title'],
                abstract=baseinfo_form.cleaned_data['abstract'])

            if publish is not None:
                logger.debug("Setting publish status to %s for layer %s",
                             publish, layername)

                Layer.objects.filter(id=the_layer.id).update(
                    is_published=publish)

            return HttpResponseRedirect(
                reverse('layer_detail', args=(layer.service_typename, )))

    logger.debug("baseinfo valid %s ", baseinfo_form.is_valid())
    logger.debug("layer valid %s ", layer_form.is_valid())
    logger.debug("attribute valid %s ", attribute_form.is_valid())
    logger.debug("subcat valid %s ", cread_subcategory_form.is_valid())

    if poc is None:
        poc_form = ProfileForm(instance=poc, prefix="poc")
    else:
        layer_form.fields['poc'].initial = poc.id
        poc_form = ProfileForm(prefix="poc")
        poc_form.hidden = True

    if metadata_author is None:
        author_form = ProfileForm(instance=metadata_author, prefix="author")
    else:
        layer_form.fields['metadata_author'].initial = metadata_author.id
        author_form = ProfileForm(prefix="author")
        author_form.hidden = True

    # creates cat - subcat association
    categories_struct = []
    for category in CReadCategory.objects.all():
        subcats = []
        for subcat in CReadSubCategory.objects.filter(category=category):
            subcats.append(subcat.id)
        categories_struct.append((category.id, category.description, subcats))

    return render_to_response(
        template,
        RequestContext(
            request,
            {
                "layer": layer,
                "baseinfo_form": baseinfo_form,
                "layer_form": layer_form,
                "poc_form": poc_form,
                "author_form": author_form,
                "attribute_form": attribute_form,
                "category_form": category_form,
                "cread_form": None,  # read_category_form,
                "cread_sub_form": cread_subcategory_form,
                "cread_categories": categories_struct
            }))
Exemple #3
0
def document_metadata(request,
                      docid,
                      template='documents/cread_document_metadata.html'):

    document = None
    try:
        document = _resolve_document(request, docid,
                                     'base.change_resourcebase_metadata',
                                     _PERMISSION_MSG_METADATA)

    except Http404:
        return HttpResponse(loader.render_to_string(
            '404.html', RequestContext(request, {})),
                            status=404)

    except PermissionDenied:
        return HttpResponse(loader.render_to_string(
            '401.html',
            RequestContext(request, {
                'error_message':
                _("You are not allowed to edit this document.")
            })),
                            status=403)

    if document is None:
        return HttpResponse('An unknown error has occured.',
                            mimetype="text/plain",
                            status=401)

    cdocumentqs = CReadResource.objects.filter(resource=document)

    if len(cdocumentqs) == 0:
        logger.info('cread_resource does not exist for document %r', document)
        cread_resource = None
    else:
        logger.debug('cread_resource found for document %r (%d)', document,
                     len(cdocumentqs))
        cread_resource = cdocumentqs[0]

    poc = document.poc
    metadata_author = document.metadata_author
    topic_category = document.category
    cread_subcategory = cread_resource.subcategory if cread_resource else None

    if request.method == "POST":
        baseinfo_form = CReadBaseInfoForm(request.POST, prefix="baseinfo")
        document_form = CReadDocumentForm(request.POST,
                                          instance=document,
                                          prefix="resource")
        category_form = CategoryForm(
            request.POST,
            prefix="category_choice_field",
            initial=int(request.POST["category_choice_field"])
            if "category_choice_field" in request.POST else None)
        cread_subcategory_form = CReadSubCategoryForm(
            request.POST,
            prefix="cread_subcategory_choice_field",
            initial=int(request.POST["cread_subcategory_choice_field"])
            if "cread_subcategory_choice_field" in request.POST else None)
    else:
        baseinfo_form = CReadBaseInfoForm(prefix="baseinfo",
                                          initial={
                                              'title': document.title,
                                              'abstract': document.abstract
                                          })

        document_form = CReadDocumentForm(instance=document, prefix="resource")
        category_form = CategoryForm(
            prefix="category_choice_field",
            initial=topic_category.id if topic_category else None)
        cread_subcategory_form = CReadSubCategoryForm(
            prefix="cread_subcategory_choice_field",
            initial=cread_subcategory.id if cread_subcategory else None)

    if request.method == "POST" \
            and baseinfo_form.is_valid() \
            and document_form.is_valid() \
            and cread_subcategory_form.is_valid():

        new_poc = document_form.cleaned_data['poc']
        new_author = document_form.cleaned_data['metadata_author']
        new_keywords = document_form.cleaned_data['keywords']
        #new_category = TopicCategory.objects.get(
        #    id=category_form.cleaned_data['category_choice_field'])

        if new_poc is None:
            if poc.user is None:
                poc_form = ProfileForm(request.POST,
                                       prefix="poc",
                                       instance=poc)
            else:
                poc_form = ProfileForm(request.POST, prefix="poc")
            if poc_form.has_changed and poc_form.is_valid():
                new_poc = poc_form.save()

        if new_author is None:
            if metadata_author is None:
                author_form = ProfileForm(request.POST,
                                          prefix="author",
                                          instance=metadata_author)
            else:
                author_form = ProfileForm(request.POST, prefix="author")
            if author_form.has_changed and author_form.is_valid():
                new_author = author_form.save()

        # CRead category
        # note: call to is_valid is needed to compute the cleaned data
        if (cread_subcategory_form.is_valid()):
            logger.info("Checking CReadLayer record %r ",
                        cread_subcategory_form.is_valid())
            cread_subcat_id = cread_subcategory_form.cleaned_data[
                'cread_subcategory_choice_field']
            new_creadsubcategory = CReadSubCategory.objects.get(
                id=cread_subcat_id)
            new_creadcategory = new_creadsubcategory.category
            logger.debug("Selected cread cat/subcat: %s : %s / %s",
                         new_creadcategory.identifier, new_creadcategory.name,
                         new_creadsubcategory.identifier)

            if cread_resource:
                logger.info("Update CReadResource record")
            else:
                logger.info("Create new CReadResource record")
                cread_resource = CReadResource()
                cread_resource.resource = document

            cread_resource.category = new_creadcategory
            cread_resource.subcategory = new_creadsubcategory
            cread_resource.save()
            # End cread category
        else:
            new_creadsubcategory = None
            logger.info("CRead subcategory form is not valid")

        if category_form.is_valid():
            new_category = TopicCategory.objects.get(
                id=category_form.cleaned_data['category_choice_field'])
        elif new_creadsubcategory:
            logger.debug("Assigning default ISO category")
            new_category = TopicCategory.objects.get(
                id=new_creadsubcategory.relatedtopic.id)

        if new_poc is not None and new_author is not None:
            the_document = document_form.save()
            the_document.poc = new_poc
            the_document.metadata_author = new_author
            the_document.keywords.add(*new_keywords)
            Document.objects.filter(id=the_document.id).update(
                category=new_category,
                title=baseinfo_form.cleaned_data['title'],
                abstract=baseinfo_form.cleaned_data['abstract'])
            return HttpResponseRedirect(
                reverse('document_detail', args=(document.id, )))

    logger.debug("subcat valid %s ", cread_subcategory_form.is_valid())

    # etj: CHECKME: this block seems wrong, but it's copied from the original documents/views
    if poc is None:
        poc_form = ProfileForm(request.POST, prefix="poc")
    else:
        if poc is None:
            poc_form = ProfileForm(instance=poc, prefix="poc")
        else:
            document_form.fields['poc'].initial = poc.id
            poc_form = ProfileForm(prefix="poc")
            poc_form.hidden = True

    if metadata_author is None:
        author_form = ProfileForm(request.POST, prefix="author")
    else:
        if metadata_author is None:
            author_form = ProfileForm(instance=metadata_author,
                                      prefix="author")
        else:
            document_form.fields[
                'metadata_author'].initial = metadata_author.id
            author_form = ProfileForm(prefix="author")
            author_form.hidden = True

    # creates cat - subcat association
    categories_struct = []
    for category in CReadCategory.objects.all():
        subcats = []
        for subcat in CReadSubCategory.objects.filter(category=category):
            subcats.append(subcat.id)
        categories_struct.append((category.id, category.description, subcats))

    return render_to_response(
        template,
        RequestContext(
            request, {
                "document": document,
                "baseinfo_form": baseinfo_form,
                "document_form": document_form,
                "poc_form": poc_form,
                "author_form": author_form,
                "category_form": category_form,
                "cread_sub_form": cread_subcategory_form,
                "cread_categories": categories_struct
            }))
def layer_metadata_create(request, layername, template='layers/cread_layer_metadata.html', publish=False):
    logger.debug("*** ENTER CREAD:layer_metadata_create (pub=%s)", publish)

    layer = _resolve_layer(
        request,
        layername,
        'base.change_resourcebase_metadata',
        _PERMISSION_MSG_METADATA)

    clayerqs = CReadResource.objects.filter(resource=layer)

    if len(clayerqs) == 0:
        logger.info('cread_resource does not exist for layer %r', layer)
        cread_resource = None
    else:
        logger.debug('cread_resource found for layer %r (%d)', layer, len(clayerqs))
        cread_resource = clayerqs[0]

    layer_attribute_set = inlineformset_factory(
        Layer,
        Attribute,
        extra=0,
        form=LayerAttributeForm,
    )

    topic_category = layer.category
    cread_subcategory = cread_resource.subcategory if cread_resource else None

    poc = layer.poc
    metadata_author = layer.metadata_author

    if request.method == "POST":
        baseinfo_form = CReadBaseInfoForm(request.POST, prefix="baseinfo")
        layer_form = CReadLayerForm(request.POST, instance=layer, prefix="resource")
        attribute_form = layer_attribute_set(
            request.POST,
            instance=layer,
            prefix="layer_attribute_set",
            queryset=Attribute.objects.order_by('display_order'))
        category_form = CategoryForm(
            request.POST,
            prefix="category_choice_field",
            initial=int(
                request.POST["category_choice_field"]) if "category_choice_field" in request.POST else None)
        #cread_category_form = CReadCategoryForm(
            #request.POST,
            #prefix="cread_category_choice_field",
            #initial=int(
                #request.POST["cread_category_choice_field"]) if "cread_category_choice_field" in request.POST else None)
        cread_subcategory_form = CReadSubCategoryForm(
            request.POST,
            prefix="cread_subcategory_choice_field",
            initial=int(
                request.POST["cread_subcategory_choice_field"]) if "cread_subcategory_choice_field" in request.POST else None)
    else:
        baseinfo_form = CReadBaseInfoForm(
            prefix="baseinfo",
            initial={'title': layer.title,
                     'abstract': layer.abstract})
        layer_form = CReadLayerForm(instance=layer, prefix="resource")
        #_preprocess_fields(layer_form)

        attribute_form = layer_attribute_set(
            instance=layer,
            prefix="layer_attribute_set",
            queryset=Attribute.objects.order_by('display_order'))
        category_form = CategoryForm(
            prefix="category_choice_field",
            initial=topic_category.id if topic_category else None)
        #cread_category_form = CReadCategoryForm(
            #prefix="cread_category_choice_field",
            #initial=cread_category.id if cread_category else None)
        cread_subcategory_form = CReadSubCategoryForm(
            prefix="cread_subcategory_choice_field",
            initial=cread_subcategory.id if cread_subcategory else None)

    if request.method == "POST" \
        and baseinfo_form.is_valid() \
        and layer_form.is_valid() \
        and attribute_form.is_valid() \
        and cread_subcategory_form.is_valid():

        new_poc = layer_form.cleaned_data['poc']
        new_author = layer_form.cleaned_data['metadata_author']
        new_keywords = layer_form.cleaned_data['keywords']

        if new_poc is None:
            if poc is None:
                poc_form = ProfileForm(
                    request.POST,
                    prefix="poc",
                    instance=poc)
            else:
                poc_form = ProfileForm(request.POST, prefix="poc")
            if poc_form.has_changed and poc_form.is_valid():
                new_poc = poc_form.save()

        if new_author is None:
            if metadata_author is None:
                author_form = ProfileForm(request.POST, prefix="author",
                                          instance=metadata_author)
            else:
                author_form = ProfileForm(request.POST, prefix="author")
            if author_form.has_changed and author_form.is_valid():
                new_author = author_form.save()

        # CRead category
        # note: call to is_valid is needed to compute the cleaned data
        if(cread_subcategory_form.is_valid()):
            logger.info("Checking CReadLayer record %r ", cread_subcategory_form.is_valid())
            #cread_cat_id = cread_category_form.cleaned_data['cread_category_choice_field']
            #cread_cat_id = cread_cat_id if cread_cat_id else 1
            #new_creadcategory = CReadCategory.objects.get(id=cread_cat_id)
            cread_subcat_id = cread_subcategory_form.cleaned_data['cread_subcategory_choice_field']
            new_creadsubcategory = CReadSubCategory.objects.get(id=cread_subcat_id)
            new_creadcategory = new_creadsubcategory.category
            logger.debug("Selected cread cat/subcat: %s : %s / %s",
                new_creadcategory.identifier,
                new_creadcategory.name,
                new_creadsubcategory.identifier)

            if cread_resource:
                logger.info("Update CReadResource record")
            else:
                logger.info("Create new CReadResource record")
                cread_resource = CReadResource()
                cread_resource.resource = layer

            cread_resource.category = new_creadcategory
            cread_resource.subcategory = new_creadsubcategory
            cread_resource.save()
            # End cread category
        else:
            new_creadsubcategory = None
            logger.info("CRead subcategory form is not valid")

        if category_form.is_valid():
            new_category = TopicCategory.objects.get(
                id=category_form.cleaned_data['category_choice_field'])
        elif new_creadsubcategory:
            logger.debug("Assigning default ISO category")
            new_category = TopicCategory.objects.get(
                id=new_creadsubcategory.relatedtopic.id)

        for form in attribute_form.cleaned_data:
            la = Attribute.objects.get(id=int(form['id'].id))
            la.description = form["description"]
            la.attribute_label = form["attribute_label"]
            la.visible = form["visible"]
            la.display_order = form["display_order"]
            la.save()

        if new_poc is not None and new_author is not None:
            new_keywords = layer_form.cleaned_data['keywords']
            layer.keywords.clear()
            layer.keywords.add(*new_keywords)
            the_layer = layer_form.save()
            the_layer.poc = new_poc
            the_layer.metadata_author = new_author
            Layer.objects.filter(id=the_layer.id).update(
                category=new_category,
                title=baseinfo_form.cleaned_data['title'],
                abstract=baseinfo_form.cleaned_data['abstract']
                )

            if publish is not None:
                logger.debug("Setting publish status to %s for layer %s", publish, layername)

                Layer.objects.filter(id=the_layer.id).update(
                    is_published=publish
                    )

            return HttpResponseRedirect(
                reverse(
                    'layer_detail',
                    args=(
                        layer.service_typename,
                    )))

    logger.debug("baseinfo valid %s ", baseinfo_form.is_valid())
    logger.debug("layer valid %s ", layer_form.is_valid())
    logger.debug("attribute valid %s ", attribute_form.is_valid())
    logger.debug("subcat valid %s ", cread_subcategory_form.is_valid())

    if poc is None:
        poc_form = ProfileForm(instance=poc, prefix="poc")
    else:
        layer_form.fields['poc'].initial = poc.id
        poc_form = ProfileForm(prefix="poc")
        poc_form.hidden = True

    if metadata_author is None:
        author_form = ProfileForm(
            instance=metadata_author,
            prefix="author")
    else:
        layer_form.fields['metadata_author'].initial = metadata_author.id
        author_form = ProfileForm(prefix="author")
        author_form.hidden = True

    # creates cat - subcat association
    categories_struct = []
    for category in CReadCategory.objects.all():
        subcats = []
        for subcat in CReadSubCategory.objects.filter(category=category):
            subcats.append(subcat.id)
        categories_struct.append((category.id, category.description, subcats))

    return render_to_response(template, RequestContext(request, {
        "layer": layer,
        "baseinfo_form": baseinfo_form,
        "layer_form": layer_form,
        "poc_form": poc_form,
        "author_form": author_form,
        "attribute_form": attribute_form,
        "category_form": category_form,
        "cread_form": None,  # read_category_form,
        "cread_sub_form": cread_subcategory_form,
        "cread_categories": categories_struct
    }))
def map_metadata(request, mapid, template="maps/cread_map_metadata.html"):

    map_obj = _resolve_map(request, mapid, "base.change_resourcebase_metadata", _PERMISSION_MSG_VIEW)

    cmapqs = CReadResource.objects.filter(resource=map_obj)

    if len(cmapqs) == 0:
        logger.info("cread_resource does not exist for map %r", map_obj)
        cread_resource = None
    else:
        logger.debug("cread_resource found for map %r (%d)", map_obj, len(cmapqs))
        cread_resource = cmapqs[0]

    poc = map_obj.poc
    metadata_author = map_obj.metadata_author
    topic_category = map_obj.category
    cread_subcategory = cread_resource.subcategory if cread_resource else None

    if request.method == "POST":
        baseinfo_form = CReadBaseInfoForm(request.POST, prefix="baseinfo")
        map_form = CReadMapForm(
            # map_form = MapForm(
            request.POST,
            instance=map_obj,
            prefix="resource",
        )
        category_form = CategoryForm(
            request.POST,
            prefix="category_choice_field",
            initial=int(request.POST["category_choice_field"]) if "category_choice_field" in request.POST else None,
        )
        cread_subcategory_form = CReadSubCategoryForm(
            request.POST,
            prefix="cread_subcategory_choice_field",
            initial=int(request.POST["cread_subcategory_choice_field"])
            if "cread_subcategory_choice_field" in request.POST
            else None,
        )
    else:
        baseinfo_form = CReadBaseInfoForm(
            prefix="baseinfo", initial={"title": map_obj.title, "abstract": map_obj.abstract}
        )
        map_form = CReadMapForm(instance=map_obj, prefix="resource")
        category_form = CategoryForm(
            prefix="category_choice_field", initial=topic_category.id if topic_category else None
        )
        cread_subcategory_form = CReadSubCategoryForm(
            prefix="cread_subcategory_choice_field", initial=cread_subcategory.id if cread_subcategory else None
        )

    if (
        request.method == "POST"
        and baseinfo_form.is_valid()
        and map_form.is_valid()
        and cread_subcategory_form.is_valid()
    ):

        new_title = strip_tags(baseinfo_form.cleaned_data["title"])
        new_abstract = strip_tags(baseinfo_form.cleaned_data["abstract"])

        new_poc = map_form.cleaned_data["poc"]
        new_author = map_form.cleaned_data["metadata_author"]
        new_keywords = map_form.cleaned_data["keywords"]

        if new_poc is None:
            if poc is None:
                poc_form = ProfileForm(request.POST, prefix="poc", instance=poc)
            else:
                poc_form = ProfileForm(request.POST, prefix="poc")
            if poc_form.has_changed and poc_form.is_valid():
                new_poc = poc_form.save()

        if new_author is None:
            if metadata_author is None:
                author_form = ProfileForm(request.POST, prefix="author", instance=metadata_author)
            else:
                author_form = ProfileForm(request.POST, prefix="author")
            if author_form.has_changed and author_form.is_valid():
                new_author = author_form.save()

        # CRead category
        # note: call to is_valid is needed to compute the cleaned data
        if cread_subcategory_form.is_valid():
            logger.info("Checking CReadLayer record %r ", cread_subcategory_form.is_valid())
            cread_subcat_id = cread_subcategory_form.cleaned_data["cread_subcategory_choice_field"]
            new_creadsubcategory = CReadSubCategory.objects.get(id=cread_subcat_id)
            new_creadcategory = new_creadsubcategory.category
            logger.debug(
                "Selected cread cat/subcat: %s : %s / %s",
                new_creadcategory.identifier,
                new_creadcategory.name,
                new_creadsubcategory.identifier,
            )

            if cread_resource:
                logger.info("Update CReadResource record")
            else:
                logger.info("Create new CReadResource record")
                cread_resource = CReadResource()
                cread_resource.resource = map_obj

            cread_resource.category = new_creadcategory
            cread_resource.subcategory = new_creadsubcategory
            cread_resource.save()
        else:
            new_creadsubcategory = None
            logger.info("CRead subcategory form is not valid")
        # End cread category

        # Update original topic category according to cread category
        if category_form.is_valid():
            new_category = TopicCategory.objects.get(id=category_form.cleaned_data["category_choice_field"])
        elif new_creadsubcategory:
            logger.debug("Assigning default ISO category from CREAD category")
            new_category = TopicCategory.objects.get(id=new_creadsubcategory.relatedtopic.id)

        if new_poc is not None and new_author is not None:
            the_map = map_form.save()
            the_map.poc = new_poc
            the_map.metadata_author = new_author
            the_map.title = new_title
            the_map.abstract = new_abstract
            the_map.save()
            the_map.keywords.clear()
            the_map.keywords.add(*new_keywords)
            the_map.category = new_category
            the_map.save()

            if getattr(settings, "SLACK_ENABLED", False):
                try:
                    from geonode.contrib.slack.utils import build_slack_message_map, send_slack_messages

                    send_slack_messages(build_slack_message_map("map_edit", the_map))
                except:
                    print "Could not send slack message for modified map."

            return HttpResponseRedirect(reverse("map_detail", args=(map_obj.id,)))

    if poc is None:
        poc_form = ProfileForm(request.POST, prefix="poc")
    else:
        if poc is None:
            poc_form = ProfileForm(instance=poc, prefix="poc")
        else:
            map_form.fields["poc"].initial = poc.id
            poc_form = ProfileForm(prefix="poc")
            poc_form.hidden = True

    if metadata_author is None:
        author_form = ProfileForm(request.POST, prefix="author")
    else:
        if metadata_author is None:
            author_form = ProfileForm(instance=metadata_author, prefix="author")
        else:
            map_form.fields["metadata_author"].initial = metadata_author.id
            author_form = ProfileForm(prefix="author")
            author_form.hidden = True

    # creates cat - subcat association
    categories_struct = []
    for category in CReadCategory.objects.all():
        subcats = []
        for subcat in CReadSubCategory.objects.filter(category=category):
            subcats.append(subcat.id)
        categories_struct.append((category.id, category.description, subcats))

    return render_to_response(
        template,
        RequestContext(
            request,
            {
                "map": map_obj,
                "map_form": map_form,
                "poc_form": poc_form,
                "author_form": author_form,
                "category_form": category_form,
                "baseinfo_form": baseinfo_form,
                "cread_sub_form": cread_subcategory_form,
                "cread_categories": categories_struct,
            },
        ),
    )
def document_metadata(
        request,
        docid,
        template='documents/cread_document_metadata.html'):

    document = None
    try:
        document = _resolve_document(
            request,
            docid,
            'base.change_resourcebase_metadata',
            _PERMISSION_MSG_METADATA)

    except Http404:
        return HttpResponse(
            loader.render_to_string(
                '404.html', RequestContext(
                    request, {
                        })), status=404)

    except PermissionDenied:
        return HttpResponse(
            loader.render_to_string(
                '401.html', RequestContext(
                    request, {
                        'error_message': _("You are not allowed to edit this document.")})), status=403)

    if document is None:
        return HttpResponse(
            'An unknown error has occured.',
            mimetype="text/plain",
            status=401
        )

    cdocumentqs = CReadResource.objects.filter(resource=document)

    if len(cdocumentqs) == 0:
        logger.info('cread_resource does not exist for document %r', document)
        cread_resource = None
    else:
        logger.debug('cread_resource found for document %r (%d)', document, len(cdocumentqs))
        cread_resource = cdocumentqs[0]

    poc = document.poc
    metadata_author = document.metadata_author
    topic_category = document.category
    cread_subcategory = cread_resource.subcategory if cread_resource else None

    if request.method == "POST":
        baseinfo_form = CReadBaseInfoForm(request.POST, prefix="baseinfo")
        document_form = CReadDocumentForm(
            request.POST,
            instance=document,
            prefix="resource")
        category_form = CategoryForm(
            request.POST,
            prefix="category_choice_field",
            initial=int(
                request.POST["category_choice_field"]) if "category_choice_field" in request.POST else None)
        cread_subcategory_form = CReadSubCategoryForm(
            request.POST,
            prefix="cread_subcategory_choice_field",
            initial=int(
                request.POST["cread_subcategory_choice_field"]) if "cread_subcategory_choice_field" in request.POST else None)
    else:
        baseinfo_form = CReadBaseInfoForm(
            prefix="baseinfo",
            initial={'title': document.title,
                     'abstract': document.abstract})

        document_form = CReadDocumentForm(instance=document, prefix="resource")
        category_form = CategoryForm(
            prefix="category_choice_field",
            initial=topic_category.id if topic_category else None)
        cread_subcategory_form = CReadSubCategoryForm(
            prefix="cread_subcategory_choice_field",
            initial=cread_subcategory.id if cread_subcategory else None)

    if request.method == "POST" \
            and baseinfo_form.is_valid() \
            and document_form.is_valid() \
            and cread_subcategory_form.is_valid():

        new_poc = document_form.cleaned_data['poc']
        new_author = document_form.cleaned_data['metadata_author']
        new_keywords = document_form.cleaned_data['keywords']
        #new_category = TopicCategory.objects.get(
        #    id=category_form.cleaned_data['category_choice_field'])

        if new_poc is None:
            if poc.user is None:
                poc_form = ProfileForm(
                    request.POST,
                    prefix="poc",
                    instance=poc)
            else:
                poc_form = ProfileForm(request.POST, prefix="poc")
            if poc_form.has_changed and poc_form.is_valid():
                new_poc = poc_form.save()

        if new_author is None:
            if metadata_author is None:
                author_form = ProfileForm(request.POST, prefix="author",
                                          instance=metadata_author)
            else:
                author_form = ProfileForm(request.POST, prefix="author")
            if author_form.has_changed and author_form.is_valid():
                new_author = author_form.save()

        # CRead category
        # note: call to is_valid is needed to compute the cleaned data
        if(cread_subcategory_form.is_valid()):
            logger.info("Checking CReadLayer record %r ", cread_subcategory_form.is_valid())
            cread_subcat_id = cread_subcategory_form.cleaned_data['cread_subcategory_choice_field']
            new_creadsubcategory = CReadSubCategory.objects.get(id=cread_subcat_id)
            new_creadcategory = new_creadsubcategory.category
            logger.debug("Selected cread cat/subcat: %s : %s / %s",
                    new_creadcategory.identifier,
                    new_creadcategory.name,
                    new_creadsubcategory.identifier)

            if cread_resource:
                logger.info("Update CReadResource record")
            else:
                logger.info("Create new CReadResource record")
                cread_resource = CReadResource()
                cread_resource.resource = document

            cread_resource.category = new_creadcategory
            cread_resource.subcategory = new_creadsubcategory
            cread_resource.save()
            # End cread category
        else:
            new_creadsubcategory = None
            logger.info("CRead subcategory form is not valid")

        if category_form.is_valid():
            new_category = TopicCategory.objects.get(
                id=category_form.cleaned_data['category_choice_field'])
        elif new_creadsubcategory:
            logger.debug("Assigning default ISO category")
            new_category = TopicCategory.objects.get(
                            id=new_creadsubcategory.relatedtopic.id)

        if new_poc is not None and new_author is not None:
            the_document = document_form.save()
            the_document.poc = new_poc
            the_document.metadata_author = new_author
            the_document.keywords.add(*new_keywords)
            Document.objects.filter(id=the_document.id).update(
                category=new_category,
                title=baseinfo_form.cleaned_data['title'],
                abstract=baseinfo_form.cleaned_data['abstract']
                )
            return HttpResponseRedirect(
                reverse(
                    'document_detail',
                    args=(
                        document.id,
                    )))

    logger.debug("subcat valid %s ", cread_subcategory_form.is_valid())

    # etj: CHECKME: this block seems wrong, but it's copied from the original documents/views
    if poc is None:
        poc_form = ProfileForm(request.POST, prefix="poc")
    else:
        if poc is None:
            poc_form = ProfileForm(instance=poc, prefix="poc")
        else:
            document_form.fields['poc'].initial = poc.id
            poc_form = ProfileForm(prefix="poc")
            poc_form.hidden = True

    if metadata_author is None:
        author_form = ProfileForm(request.POST, prefix="author")
    else:
        if metadata_author is None:
            author_form = ProfileForm(
                instance=metadata_author,
                prefix="author")
        else:
            document_form.fields['metadata_author'].initial = metadata_author.id
            author_form = ProfileForm(prefix="author")
            author_form.hidden = True

    # creates cat - subcat association
    categories_struct = []
    for category in CReadCategory.objects.all():
        subcats = []
        for subcat in CReadSubCategory.objects.filter(category=category):
            subcats.append(subcat.id)
        categories_struct.append((category.id, category.description, subcats))

    return render_to_response(template, RequestContext(request, {
        "document": document,
        "baseinfo_form": baseinfo_form,
        "document_form": document_form,
        "poc_form": poc_form,
        "author_form": author_form,
        "category_form": category_form,
        "cread_sub_form": cread_subcategory_form,
        "cread_categories": categories_struct
    }))