Exemple #1
0
def new_project(request, group=None):
    (profile, permissions,
     is_default) = cv.get_profile_and_permissions(request)

    if request.method == 'POST':
        form = CreateProjectForm(request.POST)
        if form.is_valid():
            project = ToolReviewProject()
            project.name = form.cleaned_data["tool_name"]
            project.url = form.cleaned_data["tool_url"]
            project.tool_category = form.cleaned_data["tool_category"]
            project.project_category = form.cleaned_data["project_category"]
            screenshot_url = form.cleaned_data["screenshot"]
            path_with_bucket_and_leading_slash = urlsplit(screenshot_url)[2]
            path_without_bucket = "/".join(
                path_with_bucket_and_leading_slash.split("/")[2:])
            project.screenshot_filename = path_without_bucket

            if "youtube_video_id" in form.cleaned_data:
                project.youtube_video_id = form.cleaned_data[
                    "youtube_video_id"]

            project.summary = form.cleaned_data["summary"]
            project.owner_profile = profile
            project.group = group
            project.save()

            t1 = cf.get_best_final_matching_tag(form.cleaned_data["tag1"])
            if not t1 is None:
                project.tags.add(t1)
            t2 = cf.get_best_final_matching_tag(form.cleaned_data["tag2"])
            if not t2 is None:
                project.tags.add(t2)
            t3 = cf.get_best_final_matching_tag(form.cleaned_data["tag3"])
            if not t3 is None:
                project.tags.add(t3)

            ct.finalize_project(project)

            return render(
                request, 'core/thanks.html', {
                    "action_description":
                    "creating a new tool review",
                    "link":
                    "/apps/tool_review/administer_project/" + str(project.id)
                })
        else:
            return render(request, 'core/generic_form.html', {
                'form': form,
                'action_path': request.path
            })
    else:
        form = CreateProjectForm()
        return render(request, 'core/generic_form.html', {
            'form': form,
            'action_path': request.path
        })
Exemple #2
0
def edit_project(request, project_id):
    (profile, permissions,
     is_default) = cv.get_profile_and_permissions(request)
    project = get_object_or_404(ManualNewsCurationProject, pk=project_id)
    basic_fields = ["name", "url", "first_paragraph"]

    if request.method == 'POST':
        form = EditProjectForm(request.POST)
        changes = set()
        if form.is_valid():
            for key in basic_fields:
                if not project.__dict__[key] == form.cleaned_data[key]:
                    project.__dict__[key] = form.cleaned_data[key]
                    changes.add(key)
            # ignore screenshot, too hard
            project.save()

            current_tags = set(project.tags.all())
            new_tags = set()
            for key, val in form.cleaned_data.items():
                if key.startswith("tag"):
                    t = cf.get_best_final_matching_tag(val)
                    if not t is None:
                        new_tags.add(t)

            if len(new_tags.symmetric_difference(current_tags)) > 0:
                project.tags.clear()
                project.tags.add(*new_tags)
                changes.add("tags")

            if "name" in changes or "tags" in changes:
                ct.finalize_project(project)
            return render(
                request, 'core/thanks.html', {
                    "action_description":
                    "editing your tool review",
                    "link":
                    "/apps/tool_review/administer_project/" + str(project.id)
                })
        else:
            return render(request, 'core/generic_form.html', {
                'form': form,
                'action_path': request.path
            })

    else:
        data = {k: project.__dict__[k] for k in basic_fields}
        current_tags = list(project.tags.all())
        for i, t in enumerate(current_tags):
            if i > 2:
                break
            data["tag" + str(i + 1)] = t.get_name()
        form = EditProjectForm(data)
        return render(request, 'core/generic_form.html', {
            'form': form,
            'action_path': request.path
        })
Exemple #3
0
def new_project(request, group=None):
    (profile, permissions,
     is_default) = cv.get_profile_and_permissions(request)

    if request.method == 'POST':
        form = CreateProjectForm(request.POST)
        if form.is_valid():
            project = CityBudgetingProject()
            project.city = cf.get_best_final_matching_tag(
                form.cleaned_data["city"]).geotag

            simple_fields = [
                "fiscal_period_start", "fiscal_period_end", "budget_url",
                "name", "budget_description", "revenues_description",
                "funds_description", "expenses_description"
            ]
            for k in simple_fields:
                project.__dict__[k] = form.cleaned_data[k]

            excel_file_url = form.cleaned_data["budget_excel_file"]
            path_with_bucket_and_leading_slash = urlsplit(excel_file_url)[2]
            path_without_bucket = "/".join(
                path_with_bucket_and_leading_slash.split("/")[2:])
            project.budget_excel_file = path_without_bucket

            project.owner_profile = profile
            project.group = group
            project.save()

            ct.finalize_project(project)

            return render(
                request, 'core/thanks.html', {
                    "action_description":
                    "creating a new city budget project",
                    "link":
                    "/apps/city_budgeting/administer_project/" +
                    str(project.id)
                })
        else:
            return render(request, 'core/generic_form.html', {
                'form': form,
                'action_path': request.path
            })
    else:
        initial = {
            "download_link_1":
            default_storage.url("city_budgeting/misc/example.xlsx")
        }
        form = CreateProjectForm(initial=initial)
        return render(request, 'core/generic_form.html', {
            'form': form,
            'action_path': request.path
        })
Exemple #4
0
def new_project(request, group=None):
    (profile, permissions, is_default) = cv.get_profile_and_permissions(request)
    AssignmentItemsFormset = forms.formset_factory(AssignmentItemForm, can_delete=True)
    if request.method == 'POST':
        formset = AssignmentItemsFormset(request.POST, form_kwargs={'userprofile':profile})
        project_form = CreateProjectForm(request.POST)
        if formset.is_valid() and project_form.is_valid():
            sys.stderr.write("formset data:\n{}\n".format(formset.cleaned_data))
            sys.stderr.flush()
            project = ReadingAssignmentProject()
            project.owner_profile = profile
            project.name = project_form.cleaned_data["assignment_name"]
            project.group = group
            project.save()
            num = 0
            for item in formset.cleaned_data:
                if item.get("text_question", u'') != u'':                    
                    num += 1
                    q = TextQuestion()
                    q.question_text = item["text_question"]
                    q.save()
                    oai = OrderedAssignmentItem()
                    oai.number = num
                    oai.text_question = q
                    oai.assignment=project
                    oai.save()
                elif not item.get("participation_item", None) is None:
                    num += 1
                    oai = OrderedAssignmentItem()
                    oai.number = num
                    oai.participation_item = cm.ParticipationItem.objects.get(id=item["participation_item"], is_active=True)
                    oai.assignment=project
                    oai.save()
                else:
                    # this item is blank, ignore it
                    pass                

            ct.finalize_project(project)
            return render(request, 'core/thanks.html', {"action_description": "creating a new reading assignment", "link": "/apps/reading_assignment/administer_project/"+str(project.id)})

        else:
            sys.stderr.write("formset errors:\n{}\n".format(formset.errors))
            sys.stderr.write("project form errors:\n{}\n".format(project_form.errors))
            sys.stderr.flush()
            raise Exception()
    else:
        project_form = CreateProjectForm()
        formset = AssignmentItemsFormset(form_kwargs={'userprofile':profile})
        return render(request, 'reading_assignment/new_project.html', {'project_form': project_form, 'items_formset': formset})
Exemple #5
0
def new_project(request, group=None):
    (profile, permissions,
     is_default) = cv.get_profile_and_permissions(request)

    if request.method == 'POST':
        form = CreateProjectForm(request.POST)
        if form.is_valid():
            project = LandUseProject()
            project.name = form.cleaned_data["project_name"]
            project.group = group
            # !!! Warning, Google lists geo data lat,lon.
            # everyone else, including better dem portal, does lon, lat
            poly_data = [(x[1], x[0])
                         for x in form.cleaned_data["polygon_field"]]
            poly_data.append(
                poly_data[0]
            )  # polygon must be instantiated with a closed ring
            project.polygon = Polygon(LinearRing(tuple(poly_data)))
            project.owner_profile = profile
            project.save()

            goals = FeedbackGoal.objects.all()
            for goal in goals:
                var_name = goal.name + "_pref"
                if form.cleaned_data[var_name]:
                    project.feedback_goals.add(goal)

            ct.finalize_project(project)

            return render(
                request, 'core/thanks.html', {
                    "action_description":
                    "creating a new land use planning project",
                    "link":
                    "/apps/land_use_planning/administer_project/" +
                    str(project.id)
                })
        else:
            return render(request, 'core/generic_form.html', {
                'form': form,
                'action_path': request.path
            })
    else:
        form = CreateProjectForm()
        return render(request, 'core/generic_form.html', {
            'form': form,
            'action_path': request.path
        })
Exemple #6
0
def new_project(request, group=None):
    (profile, permissions,
     is_default) = cv.get_profile_and_permissions(request)

    if request.method == 'POST':
        form = CreateProjectForm(request.POST)
        if form.is_valid():
            project = ManualNewsCurationProject()
            project.name = form.cleaned_data["name"]
            project.url = form.cleaned_data["url"]
            project.first_paragraph = form.cleaned_data["first_paragraph"]
            screenshot_url = form.cleaned_data["screenshot"]
            path_with_bucket_and_leading_slash = urlsplit(screenshot_url)[2]
            path_without_bucket = "/".join(
                path_with_bucket_and_leading_slash.split("/")[2:])
            project.screenshot_filename = path_without_bucket
            project.owner_profile = profile
            project.group = group
            project.save()

            # iterate through form adding tags
            for key, val in form.cleaned_data.items():
                if key.startswith("tag"):
                    t = cf.get_best_final_matching_tag(val)
                    if not t is None:
                        project.tags.add(t)

            ct.finalize_project(project)

            return render(
                request, 'core/thanks.html', {
                    "action_description":
                    "creating a new news article project",
                    "link":
                    "/apps/manual_news_article_curation/administer_project/" +
                    str(project.id)
                })
        else:
            return render(request, 'core/generic_form.html', {
                'form': form,
                'action_path': request.path
            })
    else:
        form = CreateProjectForm()
        return render(request, 'core/generic_form.html', {
            'form': form,
            'action_path': request.path
        })
Exemple #7
0
def new_project(request, group=None):
    (profile, permissions,
     is_default) = cv.get_profile_and_permissions(request)
    if request.method == 'POST':
        form = CreateProjectForm(request.POST)
        if form.is_valid():
            project = InteractiveVisualizationProject()
            project.owner_profile = profile
            project.group = group
            # first time through, create the project
            for key, val in form.cleaned_data.items():
                if key == "visualization_title":
                    project.name = val
                elif not key.startswith("tag"):
                    project.__dict__[key] = val
            project.save()

            # second time, add tags to the project
            for key, val in form.cleaned_data.items():
                if key.startswith("tag"):
                    t = cf.get_best_final_matching_tag(form.cleaned_data[key])
                    if not t is None:
                        project.tags.add(t)

            ct.finalize_project(project)

            return render(
                request, 'core/thanks.html', {
                    "action_description":
                    "creating a new interactive visualization",
                    "link":
                    "/apps/interactive_visualization/administer_project/" +
                    str(project.id)
                })
        else:
            return render(request, 'core/generic_form.html', {
                'form': form,
                'action_path': request.path
            })
    else:
        form = CreateProjectForm()
        return render(request, 'core/generic_form.html', {
            'form': form,
            'action_path': request.path
        })
Exemple #8
0
def new_project(request, group=None):
    (profile, permissions, is_default) = cv.get_profile_and_permissions(request)

    if request.method == 'POST':
        form = CreateProjectForm(request.POST)
        if form.is_valid():
            project = SingleQuizProject()
            project.name = form.cleaned_data["question_text"]
            project.group = group
            project.question_text = form.cleaned_data["question_text"]

            project.option1=form.cleaned_data["option1"]
            project.option2=form.cleaned_data["option2"]
            if "option3" in form.cleaned_data:
                project.option3=form.cleaned_data["option3"]
            if "option4" in form.cleaned_data:
                project.option4=form.cleaned_data["option4"]
            if "option5" in form.cleaned_data:
                project.option5=form.cleaned_data["option5"]

            project.correct_answer_index = form.cleaned_data["correct_answer_index"]
            project.citation_url = form.cleaned_data["citation_url"]
            project.explanation = form.cleaned_data["explanation"]
            project.owner_profile = profile
            project.save()

            t1 = cf.get_best_final_matching_tag(form.cleaned_data["tag1"])
            if not t1 is None:
                project.tags.add(t1)
            t2 = cf.get_best_final_matching_tag(form.cleaned_data["tag2"])
            if not t2 is None:
                project.tags.add(t2)
            t3 = cf.get_best_final_matching_tag(form.cleaned_data["tag3"])
            if not t3 is None:
                project.tags.add(t3)
            
            ct.finalize_project(project)
            return render(request, 'core/thanks.html', {"action_description": "creating a new single quiz", "link": "/apps/single_quiz/administer_project/"+str(project.id)})
        else:
            return render(request, 'core/generic_form.html', {'form': form, 'action_path' : request.path})
    else:
        form = CreateProjectForm()
        return render(request, 'core/generic_form.html', {'form': form, 'action_path' : request.path })
Exemple #9
0
def edit_project(request, project_id):
    (profile, permissions,
     is_default) = cv.get_profile_and_permissions(request)
    project = get_object_or_404(BeatTheBullshitProject, pk=project_id)
    basic_fields = [
        "name", "topic_overview", "bullet_1", "bullet_2", "bullet_3"
    ]

    if request.method == 'POST':
        form = EditProjectForm(project, request.POST)
        changes = set()
        if form.is_valid():
            for key in basic_fields:
                if not project.__dict__[key] == form.cleaned_data[key]:
                    project.__dict__[key] = form.cleaned_data[key]
                    changes.add(key)

            project.save()

            # allow adding more points of view, basics, and effects
            for i in range(1, 4):
                quote = form.cleaned_data.get("quote" + str(i), None)
                if not quote is None and not quote == "":
                    q = Quote()
                    q.quote_string = quote
                    q.speaker_name = form.cleaned_data["speaker_name" + str(i)]
                    q.reference = form.cleaned_data["reference" + str(i)]
                    screenshot_url = form.cleaned_data["screenshot_filename" +
                                                       str(i)]
                    path_with_bucket_and_leading_slash = urlsplit(
                        screenshot_url)[2]
                    path_without_bucket = "/".join(
                        path_with_bucket_and_leading_slash.split("/")[2:])
                    q.screenshot_filename = path_without_bucket
                    if "youtube_video_id" + str(i) in form.cleaned_data:
                        q.youtube_video_id = form.cleaned_data[
                            "youtube_video_id" + str(i)]

                    q.project = project
                    q.save()

                    qfa = QuoteFallacyAssociation()
                    qfa.quote = q
                    qfa.fallacy = form.cleaned_data["fallacy" + str(i)]
                    qfa.explanation = form.cleaned_data[
                        "fallacy_association_explanation" + str(i)]
                    qfa.improvement = form.cleaned_data[
                        "fallacy_association_improvement" + str(i)]
                    qfa.save()

            # Allow deleting quotes
            for key, val in form.cleaned_data.items():
                if key.startswith("delete_quote_") and val:
                    changes.add("del_quotes")
                    quote_id = int(key.replace("delete_quote_", ""))
                    assert (project.quote_set.filter(id=quote_id).exists())
                    project.quote_set.filter(id=quote_id).delete()
                    Quote.objects.filter(id=quote_id).delete()
                    # quote-filter-assiciation is deleted with cascade

            current_tags = set(project.tags.all())
            new_tags = set()
            for key, val in form.cleaned_data.items():
                if key.startswith("tag"):
                    t = cf.get_best_final_matching_tag(val)
                    if not t is None:
                        new_tags.add(t)

            if len(new_tags.symmetric_difference(current_tags)) > 0:
                project.tags.clear()
                project.tags.add(*new_tags)
                changes.add("tags")

            if "name" in changes or "tags" in changes:
                ct.finalize_project(project)

            return render(
                request, 'core/thanks.html', {
                    "action_description":
                    "editing your beat-the-bullshit project",
                    "link":
                    "/apps/beat_the_bullshit/administer_project/" +
                    str(project.id)
                })
        else:
            return render(request, 'core/generic_form.html', {
                'form': form,
                'action_path': request.path
            })

    else:
        data = {k: project.__dict__[k] for k in basic_fields}
        current_tags = list(project.tags.all())
        for i, t in enumerate(current_tags):
            if i > 2:
                break
            data["tag" + str(i + 1)] = t.get_name()
        sys.stderr.write(str(data))
        sys.stderr.flush()
        form = EditProjectForm(project, data)
        return render(request, 'core/generic_form.html', {
            'form': form,
            'action_path': request.path
        })
Exemple #10
0
def new_project(request, group=None):
    (profile, permissions,
     is_default) = cv.get_profile_and_permissions(request)
    if request.method == 'POST':
        form = CreateProjectForm(request.POST)
        if form.is_valid():
            project = BeatTheBullshitProject()
            project.name = form.cleaned_data["name"]
            project.group = group
            project.owner_profile = profile
            project.topic_overview = form.cleaned_data["topic_overview"]
            for i in range(1, 4):
                k = "bullet_" + str(i)
                if k in form.cleaned_data:
                    project.__dict__[k] = form.cleaned_data[k]
            project.save()

            for i in range(1, 4):
                q_string = form.cleaned_data.get("quote" + str(i), None)
                if not q_string is None and not q_string == "":
                    q = Quote()
                    q.quote_string = q_string
                    q.speaker_name = form.cleaned_data["speaker_name" + str(i)]
                    q.reference = form.cleaned_data["reference" + str(i)]
                    screenshot_url = form.cleaned_data["screenshot_filename" +
                                                       str(i)]
                    path_with_bucket_and_leading_slash = urlsplit(
                        screenshot_url)[2]
                    path_without_bucket = "/".join(
                        path_with_bucket_and_leading_slash.split("/")[2:])
                    q.screenshot_filename = path_without_bucket
                    if "youtube_video_id" + str(i) in form.cleaned_data:
                        q.youtube_video_id = form.cleaned_data[
                            "youtube_video_id" + str(i)]

                    q.project = project
                    q.save()

                    qfa = QuoteFallacyAssociation()
                    qfa.quote = q
                    qfa.fallacy = form.cleaned_data["fallacy" + str(i)]
                    qfa.explanation = form.cleaned_data[
                        "fallacy_association_explanation" + str(i)]
                    qfa.improvement = form.cleaned_data[
                        "fallacy_association_improvement" + str(i)]
                    qfa.save()

            # iterate through form adding tags
            for key, val in form.cleaned_data.items():
                if key.startswith("tag"):
                    t = cf.get_best_final_matching_tag(val)
                    if not t is None:
                        project.tags.add(t)

            ct.finalize_project(project)

            return render(
                request, 'core/thanks.html', {
                    "action_description":
                    "creating a new ballot decider project",
                    "link":
                    "/apps/beat_the_bullshit/administer_project/" +
                    str(project.id)
                })
        else:
            return render(request, 'core/generic_form.html', {
                'form': form,
                'action_path': request.path
            })
    else:
        form = CreateProjectForm()
        return render(request, 'core/generic_form.html', {
            'form': form,
            'action_path': request.path
        })
Exemple #11
0
def update_bill(bill_json, state_geotag):
    bill_fields = {
        "open_states_bill_id": "id",
        "name": "title",
        "bill_id": "bill_id"
    }
    bill_action_date_fields = {
        "first_action_date": "first",
        "last_action_date": "last",
        "passed_upper_date": "passed_upper",
        "passed_lower_date": "passed_lower",
        "signed_date": "signed"
    }
    bill_document_fields = {
        "url": "url",
        "name": "name",
        "mimetype": "mimetype"
    }

    existing_bill = None
    try:
        existing_bill = BillsProject.objects.get(
            open_states_bill_id=bill_json["id"])
    except BillsProject.DoesNotExist:
        pass

    if existing_bill is None:
        p = BillsProject()
        # sys.stderr.write("Bill title:{}\n".format(bill_json['title']))
        for i in bill_fields.items():
            max_len = BillsProject._meta.get_field(i[0]).max_length
            val = bill_json.get(i[1], None)
            p.__dict__[i[0]] = val if not isinstance(
                val, unicode) and not isinstance(val, str) else val[:max_len]

        for i in bill_action_date_fields.items():
            date_object = bill_json["action_dates"].get(i[1], None)
            if isinstance(date_object, unicode) or isinstance(
                    date_object, str):
                date_string = date_object
                if " " in date_string:
                    date_string = date_string.split(" ")[0]
                p.__dict__[i[0]] = date_string
            elif isinstance(date_object, datetime.datetime):
                p.__dict__[i[0]] = date_object
            elif date_object is None:
                pass
            else:
                sys.stderr.write(
                    "update_bill. Don't know how to handle this date object:{}\n"
                    .format(date_object))

        p.owner_profile = cm.get_default_user().userprofile
        p.save()

        versions = bill_json["versions"]
        for v in versions:
            doc_openstates_id = v["doc_id"]
            existing_doc = None
            try:
                existing_doc = cm.ReferenceDocument.objects.get(
                    external_api="openstates", external_id=doc_openstates_id)
            except cm.ReferenceDocument.DoesNotExist:
                pass
            if existing_doc is None:
                doc = cm.ReferenceDocument()
                doc.external_api = "openstates"
                doc.external_id = doc_openstates_id
                for i in bill_document_fields.items():
                    max_len = cm.ReferenceDocument._meta.get_field(
                        i[0]).max_length
                    val = v.get(i[1], None)
                    doc.__dict__[i[0]] = val if not isinstance(
                        val, unicode) and not isinstance(
                            val, str) else val[:max_len]

                doc.save()
                p.documents.add(doc)
            else:
                p.documents.add(existing_doc)

        p.tags.add(state_geotag.tag_ptr)
        subjects = bill_json.get("subjects", [])
        for s in subjects:
            try:
                t = cm.Tag.objects.get(name=s, detail="Openstates Subject")
                p.tags.add(t)
            except cm.Tag.DoesNotExist:
                pass

        ct.finalize_project(p, True)
        return "new"

    else:
        change_set = set()
        p = existing_bill
        for i in bill_fields.items():
            max_len = BillsProject._meta.get_field(i[0]).max_length
            val = bill_json.get(i[1], None)
            val = val if not isinstance(val, unicode) and not isinstance(
                val, str) else val[:max_len]
            if not p.__dict__[i[0]] == val:
                change_set.add(i[0])
                p.__dict__[i[0]] = val

        for i in bill_action_date_fields.items():

            date_object = bill_json["action_dates"].get(i[1], None)
            current_val = p.__dict__[i[0]]
            if isinstance(date_object, unicode) or isinstance(
                    date_object, str):
                date_string = date_object
                if " " in date_string:
                    date_string = date_string.split(" ")[0]

                if not str(current_val).strip() == date_string:
                    change_set.add(i[0])
                    p.__dict__[i[0]] = date_string

            elif isinstance(date_object, datetime.datetime):
                if current_val != date_object:
                    change_set.add(i[0])
                    p.__dict__[i[0]] = date_object

            elif date_object is None:
                if not current_val is None:
                    change_set.add(i[0])
                    p.__dict__[i[0]] = date_string
            else:
                sys.stderr.write(
                    "update_bill. Don't know how to handle this date object:{}\n"
                    .format(date_object))

        versions = bill_json["versions"]
        current_documents = p.documents.all()
        new_documents = set()
        for v in versions:
            doc_openstates_id = v["doc_id"]
            existing_doc = None
            try:
                existing_doc = cm.ReferenceDocument.objects.get(
                    external_api="openstates", external_id=doc_openstates_id)
            except cm.ReferenceDocument.DoesNotExist:
                pass
            if existing_doc is None:
                doc = cm.ReferenceDocument()
                doc.external_api = "openstates"
                doc.external_id = doc_openstates_id
                for i in bill_document_fields.items():
                    max_len = cm.ReferenceDocument._meta.get_field(
                        i[0]).max_length
                    val = v.get(i[1], None)
                    doc.__dict__[i[0]] = val if not isinstance(
                        val, unicode) and not isinstance(
                            val, str) else val[:max_len]

                doc.save()
                new_documents.add(doc)
            else:
                new_documents.add(existing_doc)

        if len(new_documents.symmetric_difference(current_documents)) > 0:
            p.documents.clear()
            p.documents.add(*new_documents)
            change_set.add("documents")

        if len(change_set) > 0:
            p.save()

        current_tags = p.tags.all()
        new_tags = set()
        new_tags.add(state_geotag.tag_ptr)
        subjects = bill_json.get("subjects", [])
        for s in subjects:
            try:
                t = cm.Tag.objects.get(name=s, detail="Openstates Subject")
                new_tags.add(t)
            except cm.Tag.DoesNotExist:
                sys.stderr.write("tag doesn't exist:{}\n".format(s))

        if len(new_tags.symmetric_difference(current_tags)) > 0:
            p.tags.clear()
            p.tags.add(*new_tags)
            change_set.add("tags")

        #### propagate project changes
        if "tags" in change_set or "name" in change_set or "last_action_date" in change_set:
            sys.stderr.write(
                "there are changes requiring item updates to project {}: {}\n".
                format(p.id, change_set))

            sys.stderr.flush()
            ct.finalize_project(p, True)

        if len(change_set) > 0:
            return "updated"
Exemple #12
0
def update_legislator(leg_json, state_geotag):
    legislator_fields = {
        "name": "full_name",
        "photo_url": "photo_url",
        "webpage_url": "url",
        "chamber": "chamber",
        "district": "district",
        "open_states_leg_id": "id",
        "open_states_active": "active",
        "email": "email",
        "phone": "office_phone"
    }

    existing_leg = None
    try:
        existing_leg = LegislatorsProject.objects.get(
            open_states_leg_id=leg_json["id"])
    except LegislatorsProject.DoesNotExist:
        pass

    if existing_leg is None:
        p = LegislatorsProject()
        for i in legislator_fields.items():
            max_len = LegislatorsProject._meta.get_field(i[0]).max_length
            val = leg_json.get(i[1], None)
            p.__dict__[i[0]] = val if not isinstance(
                val, unicode) and not isinstance(val, str) else val[:max_len]

        p.open_states_state = state_geotag.name
        p.owner_profile = cm.get_default_user().userprofile
        p.save()
        p.tags.add(state_geotag.tag_ptr)
        ct.finalize_project(p, True)
        return "new"

    else:  # check for updates to an existing legislator
        change_set = set()
        p = existing_leg
        for i in legislator_fields.items():
            max_len = LegislatorsProject._meta.get_field(i[0]).max_length
            val = leg_json.get(i[1], None)
            val = val if not isinstance(val, unicode) and not isinstance(
                val, str) else val[:max_len]
            if not p.__dict__[i[0]] == val:
                change_set.add(i[0])
                p.__dict__[i[0]] = val

        p.open_states_state = state_geotag.name
        if len(change_set) > 0:
            p.save()

        current_tags = p.tags.all()
        new_tags = set()
        new_tags.add(state_geotag.tag_ptr)
        if len(new_tags.symmetric_difference(current_tags)) > 0:
            p.tags.clear()
            p.tags.add(*new_tags)
            change_set.add("tags")

        #### finalize
        if "name" in change_set or "photo_url" in change_set or "tags" in change_set:
            sys.stderr.write(
                "there are changes requiring item updates: {}\n".format(
                    change_set))
            ct.finalize_project(p, True)
        if len(change_set) > 0:
            return "updated"
Exemple #13
0
def edit_project(request, project_id):
    (profile, permissions,
     is_default) = cv.get_profile_and_permissions(request)
    project = get_object_or_404(InteractiveVisualizationProject, pk=project_id)

    if request.method == 'POST':
        form = CreateProjectForm(request.POST)
        changes = set()
        if form.is_valid():
            for key, val in form.cleaned_data.items():
                if key == "visualization_title":
                    if not project.name == val:
                        changes.add("name")
                        project.name = val
                elif not key.startswith("tag"):
                    if not project.__dict__[key] == val:
                        project.__dict__[key] = val
                        changes.add(key)
            project.save()

            current_tags = set(project.tags.all())
            new_tags = set()
            for key, val in form.cleaned_data.items():
                if key.startswith("tag"):
                    t = cf.get_best_final_matching_tag(val)
                    if not t is None:
                        new_tags.add(t)

            if len(new_tags.symmetric_difference(current_tags)) > 0:
                project.tags.clear()
                project.tags.add(*new_tags)
                changes.add("tags")

            if "name" in changes or "tags" in changes:
                ct.finalize_project(project)

            return render(
                request, 'core/thanks.html', {
                    "action_description":
                    "editing your interactive visualization",
                    "link":
                    "/apps/interactive_visualization/administer_project/" +
                    str(project.id)
                })
        else:
            return render(request, 'core/generic_form.html', {
                'form': form,
                'action_path': request.path
            })

    else:
        data = {
            i: project.__dict__[i]
            for i in [
                "methodology_note", "methodology_url", "csv_data",
                "switch_variable", "switch_title", "switch_note",
                "pie1_variable", "pie1_title", "pie2_variable", "pie2_title",
                "bar1_variable", "bar1_title", "bar1_x_label", "bar1_y_label",
                "bar2_variable", "bar2_title", "bar2_x_label", "bar2_y_label"
            ]
        }
        data["visualization_title"] = project.name
        current_tags = list(project.tags.all())
        for i, t in enumerate(current_tags):
            if i > 2:
                break
            data["tag" + str(i + 1)] = t.get_name()
        form = CreateProjectForm(data)
        return render(request, 'core/generic_form.html', {
            'form': form,
            'action_path': request.path
        })
Exemple #14
0
def edit_project(request, project_id):
    (profile, permissions,
     is_default) = cv.get_profile_and_permissions(request)
    project = get_object_or_404(BallotDeciderProject, pk=project_id)
    basic_fields = {
        "name": "measure_name",
        "ballot_text": "ballot_text",
        "election_date": "election_date",
        "election_website": "election_website",
        "basics_notes": "basics_notes",
        "effects_notes": "effects_notes"
    }

    if request.method == 'POST':
        form = EditProjectForm(project, request.POST)
        changes = set()
        if form.is_valid():
            for key in basic_fields:
                if not project.__dict__[key] == form.cleaned_data[
                        basic_fields[key]]:
                    project.__dict__[key] = form.cleaned_data[
                        basic_fields[key]]
                    changes.add(key)

            project.save()

            # allow adding more points of view, basics, and effects
            for i in range(1, 4):
                data = form.cleaned_data.get("basics" + str(i), None)
                if not data is None and not data == "":
                    item = cm.ParticipationItem.objects.get(id=data,
                                                            is_active=True)
                    project.basics.add(item)
                    changes.add("basics")

            for i in range(1, 4):
                data = form.cleaned_data.get("effects" + str(i), None)
                if not data is None and not data == "":
                    item = cm.ParticipationItem.objects.get(id=data,
                                                            is_active=True)
                    project.effects.add(item)
                    changes.add("effects")

            for i in range(1, 4):
                quote = form.cleaned_data.get("pov_quote_" + str(i), None)
                if not quote is None and not quote == "":
                    pov = PointOfView()
                    pov.quote = quote
                    pov.is_favorable = form.cleaned_data["pov_is_favorable_" +
                                                         str(i)]
                    pov.save()
                    project.points_of_view.add(pov)
                    changes.add("povs")

            # Allow deleting POVs
            for key, val in form.cleaned_data.items():
                if key.startswith("delete_pov_") and val:
                    changes.add("del_povs")
                    pov_id = int(key.replace("delete_pov_", ""))
                    assert (project.points_of_view.filter(id=pov_id).exists())
                    project.points_of_view.filter(id=pov_id).delete()
                    PointOfView.objects.filter(id=pov_id).delete()

            current_tags = set(project.tags.all())
            new_tags = set()
            for key, val in form.cleaned_data.items():
                if key.startswith("tag"):
                    t = cf.get_best_final_matching_tag(val)
                    if not t is None:
                        new_tags.add(t)

            if len(new_tags.symmetric_difference(current_tags)) > 0:
                project.tags.clear()
                project.tags.add(*new_tags)
                changes.add("tags")

            if "name" in changes or "tags" in changes:
                ct.finalize_project(project)

            return render(
                request, 'core/thanks.html', {
                    "action_description":
                    "editing your ballot decider",
                    "link":
                    "/apps/ballot_decider/administer_project/" +
                    str(project.id)
                })
        else:
            return render(request, 'core/generic_form.html', {
                'form': form,
                'action_path': request.path
            })

    else:
        data = {i[1]: project.__dict__[i[0]] for i in basic_fields.items()}
        current_tags = list(project.tags.all())
        for i, t in enumerate(current_tags):
            if i > 2:
                break
            data["tag" + str(i + 1)] = t.get_name()
        form = EditProjectForm(project, data)
        return render(request, 'core/generic_form.html', {
            'form': form,
            'action_path': request.path
        })
Exemple #15
0
def edit_project(request, project_id):
    (profile, permissions,
     is_default) = cv.get_profile_and_permissions(request)
    project = get_object_or_404(ToolReviewProject, pk=project_id)

    if request.method == 'POST':
        form = EditProjectForm(request.POST)
        changes = set()
        if form.is_valid():
            for k in ["tool_name", "tool_url"]:
                if not project.__dict__[k.split("_")
                                        [1]] == form.cleaned_data[k]:
                    project.__dict__[k.split("_")[1]] = form.cleaned_data[k]
                    changes.add(k.split("_")[1])

            for k in ["tool_category", "project_category", "summary"]:
                if not project.__dict__[k] == form.cleaned_data[k]:
                    project.__dict__[k] = form.cleaned_data[k]
                    changes.add(k)

            # currently we don't support updating screenshot, too much work

            if "youtube_video_id" in form.cleaned_data and \
               ( project.youtube_video_id is None or \
                 not project.youtube_video_id == form.cleaned_data["youtube_video_id"] ) :
                project.youtube_video_id = form.cleaned_data[
                    "youtube_video_id"]
                changes.add("video")
            elif not project.youtube_video_id is None and not "youtube_video_id" in form.cleaned_data:
                del project.youtube_video_id
                changes.add("video")
            project.save()

            current_tags = set(project.tags.all())
            new_tags = set()
            t1 = cf.get_best_final_matching_tag(form.cleaned_data["tag1"])
            if not t1 is None:
                new_tags.add(t1)
            t2 = cf.get_best_final_matching_tag(form.cleaned_data["tag2"])
            if not t2 is None:
                new_tags.add(t2)
            t3 = cf.get_best_final_matching_tag(form.cleaned_data["tag3"])
            if not t3 is None:
                new_tags.add(t3)

            if len(new_tags.symmetric_difference(current_tags)) > 0:
                project.tags.clear()
                project.tags.add(*new_tags)
                changes.add("tags")

            if "name" in changes or "tags" in changes:
                ct.finalize_project(project)
            return render(
                request, 'core/thanks.html', {
                    "action_description":
                    "editing your tool review",
                    "link":
                    "/apps/tool_review/administer_project/" + str(project.id)
                })
        else:
            return render(request, 'core/generic_form.html', {
                'form': form,
                'action_path': request.path
            })

    else:
        data = {
            "tool_name": project.name,
            "tool_url": project.url,
            "summary": project.summary,
            "tool_category": project.tool_category,
            "project_category": project.project_category
        }
        if not project.youtube_video_id is None:
            data["youtube_video_id"] = project.youtube_video_id
        current_tags = list(project.tags.all())
        for i, t in enumerate(current_tags):
            if i > 2:
                break
            data["tag" + str(i + 1)] = t.get_name()
        form = EditProjectForm(data)
        return render(request, 'core/generic_form.html', {
            'form': form,
            'action_path': request.path
        })
Exemple #16
0
def edit_project(request, project_id):
    (profile, permissions,
     is_default) = cv.get_profile_and_permissions(request)
    project = get_object_or_404(CityBudgetingProject, pk=project_id)
    simple_fields = [
        "fiscal_period_start", "fiscal_period_end", "budget_url", "name",
        "budget_description", "revenues_description", "funds_description",
        "expenses_description"
    ]
    if request.method == 'POST':
        form = EditProjectForm(request.POST)
        changes = set()
        if form.is_valid():
            for k in simple_fields:
                if not project.__dict__[k] == form.cleaned_data[k]:
                    project.__dict__[k] = form.cleaned_data[k]
                    changes.add(k)

            form_city = cf.get_best_final_matching_tag(
                form.cleaned_data["city"]).geotag
            if not project.city == form_city:
                project.city = form_city
                changes.add("city")

            if "budget_excel_file" in form.cleaned_data and not form.cleaned_data[
                    "budget_excel_file"] is None and not form.cleaned_data[
                        "budget_excel_file"] == "":
                changes.add("data")
                excel_file_url = form.cleaned_data["budget_excel_file"]
                path_with_bucket_and_leading_slash = urlsplit(
                    excel_file_url)[2]
                path_without_bucket = "/".join(
                    path_with_bucket_and_leading_slash.split("/")[2:])
                project.budget_excel_file = path_without_bucket

            project.save()

            if "name" in changes or "data" in changes:
                ct.finalize_project(project)
            return render(
                request, 'core/thanks.html', {
                    "action_description":
                    "editing your budget transparency project",
                    "link":
                    "/apps/city_budgeting/administer_project/" +
                    str(project.id)
                })
        else:
            return render(request, 'core/generic_form.html', {
                'form': form,
                'action_path': request.path
            })

    else:
        data = {k: project.__dict__[k] for k in simple_fields}
        data["city"] = project.city.get_name()
        initial = {
            "download_link_1":
            default_storage.url("city_budgeting/misc/example.xlsx"),
            "download_link_2":
            default_storage.url(project.budget_excel_file)
        }
        form = EditProjectForm(data, initial=initial)
        return render(request, 'core/generic_form.html', {
            'form': form,
            'action_path': request.path
        })
Exemple #17
0
def new_project(request, group=None):
    (profile, permissions,
     is_default) = cv.get_profile_and_permissions(request)

    if request.method == 'POST':
        form = CreateProjectForm(request.POST)
        if form.is_valid():
            project = BallotDeciderProject()
            project.name = form.cleaned_data["measure_name"]
            project.owner_profile = profile
            project.ballot_text = form.cleaned_data["ballot_text"]
            project.election_date = form.cleaned_data["election_date"]
            project.election_website = form.cleaned_data["election_website"]
            if "basics_notes" in form.cleaned_data and not form.cleaned_data[
                    "basics_notes"] == "":
                project.basics_notes = form.cleaned_data["basics_notes"]
            if "effects_notes" in form.cleaned_data and not form.cleaned_data[
                    "effects_notes"] == "":
                project.effects_notes = form.cleaned_data["effects_notes"]
            project.group = group
            project.save()

            for i in range(1, 4):
                data = form.cleaned_data.get("basics" + str(i), None)
                if not data is None and not data == "":
                    item = cm.ParticipationItem.objects.get(id=data,
                                                            is_active=True)
                    project.basics.add(item)

            for i in range(1, 4):
                data = form.cleaned_data.get("effects" + str(i), None)
                if not data is None and not data == "":
                    item = cm.ParticipationItem.objects.get(id=data,
                                                            is_active=True)
                    project.effects.add(item)

            for i in range(1, 4):
                quote = form.cleaned_data.get("pov_quote_" + str(i), None)
                if not quote is None and not quote == "":
                    pov = PointOfView()
                    pov.quote = quote
                    pov.is_favorable = form.cleaned_data["pov_is_favorable_" +
                                                         str(i)]
                    pov.save()
                    project.points_of_view.add(pov)

            # iterate through form adding tags
            for key, val in form.cleaned_data.items():
                if key.startswith("tag"):
                    t = cf.get_best_final_matching_tag(val)
                    if not t is None:
                        project.tags.add(t)

            ct.finalize_project(project)

            return render(
                request, 'core/thanks.html', {
                    "action_description":
                    "creating a new ballot decider project",
                    "link":
                    "/apps/ballot_decider/administer_project/" +
                    str(project.id)
                })
        else:
            return render(request, 'core/generic_form.html', {
                'form': form,
                'action_path': request.path
            })
    else:
        form = CreateProjectForm()
        return render(request, 'core/generic_form.html', {
            'form': form,
            'action_path': request.path
        })