Exemplo n.º 1
0
def approve_protein(request, slug=None):
    if not request.is_ajax():
        return HttpResponseNotAllowed([])

    try:
        P = Protein.objects.get(slug=slug)
        if not P.status == "pending":
            return JsonResponse({})

        # get rid of previous unapproved version
        try:
            if P.versions.first().field_dict["status"] == "pending":
                P.versions.first().delete()
        except Exception:
            pass

        with reversion.create_revision():
            reversion.set_user(request.user)
            reversion.set_comment("%s approved current version" % request.user)
            P.status = "approved"
            P.save()
            try:
                uncache_protein_page(P.slug, request)
            except Exception:
                pass

        return JsonResponse({})
    except Exception:
        pass
Exemplo n.º 2
0
def add_or_remove(request):
    if not request.is_ajax():
        return HttpResponseNotAllowed([])
    user = request.user
    try:
        app_model = request.POST["target_model"]
        obj_id = int(request.POST["target_object_id"])
    except (KeyError, ValueError):
        return HttpResponseBadRequest()
    fav = Favorite.objects.get_favorite(user, obj_id, model=app_model)
    if fav is None:
        Favorite.objects.create(user, obj_id, app_model)
        status = "added"
    else:
        fav.delete()
        status = "deleted"
    response = {
        "status": status,
        "fav_count": Favorite.objects.for_object(obj_id, app_model).count(),
    }

    if str(app_model) == "proteins.Protein":
        try:
            slug = apps.get_model(app_model).objects.get(id=obj_id).slug
            uncache_protein_page(slug, request)
        except Exception as e:
            import logging

            logger = logging.getLogger(__name__)
            logger.error("failed to uncache protein: {}".format(e))

    return JsonResponse(response)
Exemplo n.º 3
0
def add_protein_excerpt(request, slug=None):
    try:
        with reversion.create_revision():
            doi = request.POST.get("excerpt_doi").lower()
            P = Protein.objects.get(slug=slug)
            content = request.POST.get("excerpt_content")
            if content:
                ref, created = Reference.objects.get_or_create(doi=doi)
                P.references.add(ref)
                excerpt = Excerpt.objects.create(reference=ref,
                                                 content=strip_tags(content),
                                                 created_by=request.user)
                excerpt.proteins.add(P)
                if not request.user.is_staff:
                    msg = "User: {}\nProtein: {}\nReference: {}, {}\nExcerpt: {}\n{}".format(
                        request.user.username,
                        P,
                        ref,
                        ref.title,
                        strip_tags(content),
                        request.build_absolute_uri(P.get_absolute_url()),
                    )
                    mail_managers("Excerpt Added", msg, fail_silently=True)
                P.save()
                reversion.set_user(request.user)
                reversion.set_comment("Added Excerpt from {}".format(ref))
                try:
                    uncache_protein_page(slug, request)
                except Exception as e:
                    logger.error("failed to uncache protein: {}".format(e))
        return JsonResponse({"status": "success"})
    except Exception as e:
        return JsonResponse({"status": "failed", "msg": e})
Exemplo n.º 4
0
 def save_model(self, request, obj, form, change):
     if not obj.created_by:
         obj.created_by = request.user
     obj.updated_by = request.user
     # obj.status = 'approved'
     obj.save()
     uncache_protein_page(obj.slug, request)
Exemplo n.º 5
0
def add_reference(request, slug=None):
    try:
        with reversion.create_revision():
            doi = request.POST.get("reference_doi").lower()
            P = Protein.objects.get(slug=slug)
            ref, created = Reference.objects.get_or_create(doi=doi)
            P.references.add(ref)
            if not request.user.is_staff:
                P.status = "pending"
                msg = "User: {}\nProtein: {}\nReference: {}. {}\n\n{}".format(
                    request.user.username,
                    P,
                    ref,
                    ref.title,
                    request.build_absolute_uri(P.get_absolute_url()),
                )
                mail_managers("Reference Added", msg, fail_silently=True)
            P.save()
            reversion.set_user(request.user)
            reversion.set_comment("Added Reference: {}".format(ref))
            try:
                uncache_protein_page(slug, request)
            except Exception as e:
                logger.error("failed to uncache protein: {}".format(e))
        return JsonResponse({"status": "success"})
    except Exception as e:
        return JsonResponse({"status": "failed", "msg": e})
Exemplo n.º 6
0
 def form_valid(self, form):
     # This method is called when valid form data has been POSTed.
     # It should return an HttpResponse.
     i = super().form_valid(form)
     try:
         uncache_protein_page(self.object.owner_state.protein.slug,
                              self.request)
     except Exception:
         pass
     if not self.request.user.is_staff:
         EmailMessage(
             '[FPbase] Spectrum submitted: %s' % form.cleaned_data['owner'],
             self.request.build_absolute_uri(form.instance.get_admin_url()),
             to=[a[1] for a in settings.ADMINS],
             headers={
                 'X-Mailgun-Track': 'no'
             }).send()
     return i
Exemplo n.º 7
0
def update_transitions(request, slug=None):
    template_name = "proteins/forms/_transition_form.html"
    obj = Protein.objects.get(slug=slug)
    if request.method == "POST":
        formset = StateTransitionFormSet(request.POST, instance=obj)
        if formset.is_valid():
            with transaction.atomic():
                with reversion.create_revision():
                    formset.save()
                    chg_string = "\n".join(get_form_changes(formset))

                    if request.user.is_staff:
                        pass
                        # obj.status = 'approved'
                    else:
                        obj.status = "pending"
                        mail_managers(
                            "Transition updated",
                            "User: {}\nProtein: {}\n\n{}".format(
                                request.user.username, obj, chg_string),
                            fail_silently=True,
                        )
                    obj.save()
                    reversion.set_user(request.user)
                    reversion.set_comment(chg_string)
                    try:
                        uncache_protein_page(slug, request)
                    except Exception as e:
                        logger.error("failed to uncache protein: {}".format(e))
                    check_switch_type(obj, request)
            return HttpResponse(status=200)
        else:
            response = render(request,
                              template_name, {"transition_form": formset},
                              status=422)
            return response
    else:
        formset = StateTransitionFormSet(instance=obj)
        formset.form.base_fields["from_state"].queryset = State.objects.filter(
            protein=obj)
        formset.form.base_fields["to_state"].queryset = State.objects.filter(
            protein=obj)
        return render(request, template_name, {"transition_form": formset})
Exemplo n.º 8
0
def flag_object(request):
    if not request.is_ajax():
        return HttpResponseNotAllowed([])
    try:
        model_type = request.POST["target_model"]
        id = request.POST["target_id"]
        model = apps.get_model(model_type)
        obj = get_object_or_404(model, id=id)

        status = None
        if request.POST["flagged"] == "1":
            if request.user.is_staff:
                obj.status = model.STATUS.approved
                status = "unflagged"
        else:
            obj.status = model.STATUS.flagged
            status = "flagged"
        obj.save()

        if status:
            try:
                uncache_protein_page(obj.protein.slug, request)
            except Exception as e:
                logger.error("failed to uncache protein: {}".format(e))

            mail_admins(
                "%s %s" % (model_type, status),
                "User: {}\nObject: {}\nID: {}\n{}".format(
                    request.user.username,
                    obj,
                    obj.pk,
                    request.build_absolute_uri(obj.get_absolute_url()),
                ),
                fail_silently=True,
            )

        return JsonResponse({"status": status})
    except (KeyError, ValueError):
        return HttpResponseBadRequest()
Exemplo n.º 9
0
def revert_revision(request, rev=None):
    revision = get_object_or_404(Revision, id=rev)

    with transaction.atomic():
        revision.revert(delete=True)
        proteins = {
            v.object
            for v in revision.version_set.all()
            if v.object._meta.model_name == "protein"
        }
        if len(proteins) == 1:
            P = proteins.pop()
            with reversion.create_revision():
                reversion.set_user(request.user)
                reversion.set_comment("Reverted to revision dated {}".format(
                    revision.date_created))
                P.save()
                try:
                    uncache_protein_page(P.slug, request)
                except Exception:
                    pass

    return JsonResponse({"status": 200})
Exemplo n.º 10
0
def protein_bleach_formsets(request, slug):
    template_name = "proteins/protein_bleach_form.html"
    BleachMeasurementFormSet = modelformset_factory(BleachMeasurement,
                                                    BleachMeasurementForm,
                                                    extra=1,
                                                    can_delete=True)
    protein = get_object_or_404(Protein, slug=slug)
    qs = BleachMeasurement.objects.filter(state__protein=protein)
    if request.method == "POST":
        formset = BleachMeasurementFormSet(request.POST, queryset=qs)
        formset.form.base_fields["state"].queryset = State.objects.filter(
            protein__slug=slug)
        if formset.is_valid():
            with transaction.atomic():
                with reversion.create_revision():

                    saved = formset.save(commit=False)
                    for s in saved:
                        if not s.created_by:
                            s.created_by = request.user
                        s.updated_by = request.user
                        s.save()
                    for s in formset.deleted_objects:
                        s.delete()

                    chg_string = "\n".join(get_form_changes(formset))

                    if not request.user.is_staff:
                        protein.status = "pending"
                        mail_managers(
                            "BleachMeasurement Added",
                            "User: {}\nProtein: {}\n{}\n\n{}".format(
                                request.user.username,
                                protein,
                                chg_string,
                                request.build_absolute_uri(
                                    protein.get_absolute_url()),
                            ),
                            fail_silently=True,
                        )
                    # else:
                    #     protein.status = 'approved'

                    protein.save()
                    reversion.set_user(request.user)
                    reversion.set_comment(chg_string)
                    try:
                        uncache_protein_page(slug, request)
                    except Exception as e:
                        logger.error("failed to uncache protein: {}".format(e))
            return HttpResponseRedirect(protein.get_absolute_url())
        else:
            return render(request, template_name, {
                "formset": formset,
                "protein": protein
            })
    else:
        formset = BleachMeasurementFormSet(queryset=qs)
        formset.form.base_fields["state"].queryset = State.objects.filter(
            protein__slug=slug)
    return render(request, template_name, {
        "formset": formset,
        "protein": protein
    })
Exemplo n.º 11
0
    def form_valid(self, form):
        # This method is called when valid form data has been POSTed.
        context = self.get_context_data()
        states = context["states"]
        lineage = context["lineage"]

        if states.is_valid() and lineage.is_valid():
            # check if another protein already has the sequence that would be
            if not form.cleaned_data.get("seq"):
                for lform in lineage.forms:
                    mut = lform.cleaned_data.get("mutation")
                    par = lform.cleaned_data.get("parent")
                    if par and mut:
                        seq = par.protein.seq.mutate(mut)
                        try:
                            prot = Protein.objects.get(seq__iexact=str(seq))
                            msg = mark_safe(
                                f'<a href="{prot.get_absolute_url()}" style="text-decoration: '
                                +
                                f'underline;">{prot.name}</a> already has the sequence that'
                                +
                                " would be generated by this parent & mutation"
                            )
                            lform.add_error(None, msg)
                            context.update({
                                "states": states,
                                "lineage": lineage
                            })
                            return self.render_to_response(context)
                        except Protein.DoesNotExist:
                            pass

            with transaction.atomic():
                with reversion.create_revision():
                    self.object = form.save()
                    doi = form.cleaned_data.get("reference_doi")
                    if doi:
                        ref, created = Reference.objects.get_or_create(
                            doi=doi.lower())
                        self.object.primary_reference = ref
                    else:
                        self.object.primary_reference = None

                    states.instance = self.object
                    saved_states = states.save(commit=False)
                    for s in saved_states:
                        if not s.created_by:
                            s.created_by = self.request.user
                        s.updated_by = self.request.user
                        s.save()
                    for s in states.deleted_objects:
                        if self.object.default_state == s:
                            self.object.default_state = None
                        s.delete()

                    lineage.instance = self.object
                    for lin in lineage.save(commit=False):
                        # if the form has been cleared and there are no children,
                        # let's clean up a little
                        if (not (lin.mutation and lin.parent)
                                and not lin.children.exists()):
                            lin.delete()
                        else:
                            if not lin.created_by:
                                lin.created_by = self.request.user
                            lin.updated_by = self.request.user
                            lin.reference = self.object.primary_reference
                            lin.save()
                    for lin in lineage.deleted_objects:
                        lin.delete()

                    if hasattr(self.object, "lineage"):
                        if not self.object.seq:
                            seq = self.object.lineage.parent.protein.seq.mutate(
                                self.object.lineage.mutation)
                            self.object.seq = str(seq)
                        if not self.object.parent_organism:
                            self.object.parent_organism = (
                                self.object.lineage.root_node.protein.
                                parent_organism)

                    comment = "{} {} form.".format(self.object,
                                                   self.get_form_type())
                    chg_string = "\n".join(
                        get_form_changes(form, states, lineage))

                    if not self.request.user.is_staff:
                        self.object.status = "pending"
                        msg = "User: {}\nProtein: {}\n\n{}\n\n{}".format(
                            self.request.user.username,
                            self.object,
                            chg_string,
                            self.request.build_absolute_uri(
                                self.object.get_absolute_url()),
                        )
                        mail_managers(comment, msg, fail_silently=True)
                    # else:
                    #     self.object.status = 'approved'

                    self.object.save()
                    reversion.set_user(self.request.user)
                    reversion.set_comment(chg_string)
                    try:
                        uncache_protein_page(self.object.slug, self.request)
                    except Exception as e:
                        logger.error("failed to uncache protein: {}".format(e))

                    check_switch_type(self.object, self.request)

        else:
            context.update({"states": states, "lineage": lineage})
            return self.render_to_response(context)

        return HttpResponseRedirect(self.get_success_url())