Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature/clipping #557

Merged
merged 10 commits into from
Sep 9, 2024
8 changes: 4 additions & 4 deletions bin/web.sh
Original file line number Diff line number Diff line change
Expand Up @@ -24,10 +24,10 @@ else
fi
if [[ $(echo $DEV_BUILD | tr a-z A-Z) = "TRUE" ]]; then
extra_reload_opts=$(
find -regextype posix-extended -regex '.*/(templates|static)/?$' \
| while read path; do
echo --reload-extra-file $path
done
find -regextype posix-extended -regex '.*\.(html|css|js|jpg|gif|png|svg|ttf|woff|woff2|eot)$' \
| while read filename; do
echo "--reload-extra-file $(dirname $filename)";
done | sort -u
)
OPTS="$OPTS --reload $extra_reload_opts"
fi
Expand Down
Empty file added clipping/__init__.py
Empty file.
72 changes: 72 additions & 0 deletions clipping/admin.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
from django import forms
from django.contrib import admin
from django.contrib.contenttypes.models import ContentType
from django.forms.models import ModelChoiceField

from .models import Clipping, ClippingRelation


TARGET_MODELS = {
"core": ["dataset", "table"]
}


class ClippingRelationAdminForm(forms.ModelForm):
contents = []
for app_name in TARGET_MODELS:
for model_name in TARGET_MODELS[app_name]:
contents.append(model_name)

content_type = ModelChoiceField(
ContentType.objects.filter(app_label__in=TARGET_MODELS, model__in=contents),
empty_label="--------",
label="Content",
)
object_id = forms.CharField(widget=forms.Select(choices=[("", "---------")]), label="Element")

class Meta:
model = ClippingRelation
fields = ["content_type", "object_id", "clipping"]


@admin.register(ClippingRelation)
class ClippingRelationAdmin(admin.ModelAdmin):
form = ClippingRelationAdminForm
list_display = (
"id",
"content_type",
"get_clipping_relation",
"clipping",
)

def get_clipping_relation(self, obj):
content_type = obj.content_type
content_object = obj.content_object

if content_type.model == 'dataset':
return f"{content_object.slug} ({content_object.name})"
elif content_type.model == 'table':
return f"{content_object.dataset.slug}.{content_object.name}"
else:
return str(content_object)

get_clipping_relation.short_description = "Relation"


class ClippingAdminForm(forms.ModelForm):
category = forms.CharField(widget=forms.Select(choices=Clipping.CategoryChoices.choices), label="Category")

class Meta:
model = Clipping
exclude = ["added_by"]


@admin.register(Clipping)
class ClippingAdmin(admin.ModelAdmin):
form = ClippingAdminForm
list_display = ("date", "title", "author", "vehicle", "category", "url", "added_by", "published")

def save_model(self, request, obj, form, change):
if getattr(obj, "added_by", None) is None:
obj.added_by = request.user
obj.save()
5 changes: 5 additions & 0 deletions clipping/apps.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
from django.apps import AppConfig


class ClippingConfig(AppConfig):
name = "clipping"
16 changes: 16 additions & 0 deletions clipping/forms.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
from django import forms
from django.forms import ModelForm

from .models import Clipping


class ClippingForm(ModelForm):
category = forms.CharField(widget=forms.Select(choices=Clipping.CategoryChoices.choices), label="Categoria")
date = forms.CharField(widget=forms.TextInput(attrs={"class": "datepicker"}), label="Data")
author = forms.CharField(label="Autor")
title = forms.CharField(label="Título")

class Meta:
model = Clipping
fields = "__all__"
exclude = ["added_by", "published"]
38 changes: 38 additions & 0 deletions clipping/management/commands/import_clippings.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import csv
from pathlib import Path

from django.contrib.auth import get_user_model
from django.core.management.base import BaseCommand

from clipping.models import Clipping


class Command(BaseCommand):
def add_arguments(self, parser):
parser.add_argument("csv", type=Path, help="CSV file to update the clippings JSON field")

def clean_args(self, **kwargs):
csv_file = kwargs["csv"]
if csv_file and not csv_file.exists():
raise Exception(f"The CSV {csv_file} does not exists")
return csv_file

def handle(self, *args, **kwargs):
csv_file = self.clean_args(**kwargs)
username = "turicas"
user = get_user_model().objects.get(username=username)
with open(csv_file, encoding="utf-8") as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
p = Clipping(
date=row["data"],
vehicle=row["veiculo"],
author=row["autor"],
title=row["titulo"],
category=row["categoria"],
url=row["link"],
published=True,
added_by=user,
)
p.save()
self.stdout.write(self.style.SUCCESS("Successfully imported"))
91 changes: 91 additions & 0 deletions clipping/migrations/0001_initial.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
# Generated by Django 4.2.16 on 2024-09-08 23:28

import datetime
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion


class Migration(migrations.Migration):

initial = True

dependencies = [
("contenttypes", "0002_remove_content_type_name"),
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]

operations = [
migrations.CreateModel(
name="Clipping",
fields=[
(
"id",
models.AutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name="ID",
),
),
("date", models.DateField(default=datetime.date.today)),
("vehicle", models.CharField(blank=True, max_length=100, null=True)),
("author", models.CharField(blank=True, max_length=100, null=True)),
("title", models.CharField(blank=True, max_length=200, null=True)),
(
"category",
models.SmallIntegerField(
choices=[
(1, "Notícias e Entrevistas"),
(2, "Análises"),
(3, "Podcasts e Rádio"),
(4, "Outro"),
]
),
),
("url", models.URLField(unique=True)),
("published", models.BooleanField(blank=True, default=False)),
(
"added_by",
models.ForeignKey(
blank=True,
null=True,
on_delete=django.db.models.deletion.SET_NULL,
to=settings.AUTH_USER_MODEL,
),
),
],
),
migrations.CreateModel(
name="ClippingRelation",
fields=[
(
"id",
models.AutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name="ID",
),
),
("object_id", models.PositiveIntegerField(db_index=True)),
(
"clipping",
models.ForeignKey(
on_delete=django.db.models.deletion.CASCADE,
to="clipping.clipping",
),
),
(
"content_type",
models.ForeignKey(
on_delete=django.db.models.deletion.CASCADE,
to="contenttypes.contenttype",
),
),
],
options={
"unique_together": {("content_type", "object_id", "clipping")},
},
),
]
Empty file added clipping/migrations/__init__.py
Empty file.
41 changes: 41 additions & 0 deletions clipping/models.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import datetime

from django.contrib.auth import get_user_model
from django.contrib.contenttypes.fields import GenericForeignKey
from django.contrib.contenttypes.models import ContentType
from django.db import models


class Clipping(models.Model):
class CategoryChoices(models.IntegerChoices):
NOTICIAS_ENTREVISTAS = (1, "Notícias e Entrevistas")
ANALISES = (2, "Análises")
PODCASTS_RADIO = (3, "Podcasts e Rádio")
OUTRO = (4, "Outro")

date = models.DateField(null=False, blank=False, default=datetime.date.today)
vehicle = models.CharField(max_length=100, null=True, blank=True)
author = models.CharField(max_length=100, null=True, blank=True)
title = models.CharField(max_length=200, null=True, blank=True)
category = models.SmallIntegerField(choices=CategoryChoices.choices, null=False, blank=False)
url = models.URLField(null=False, blank=False, unique=True)
published = models.BooleanField(default=False, blank=True)

added_by = models.ForeignKey(get_user_model(), null=True, blank=True, on_delete=models.SET_NULL)

def __str__(self):
return self.title


class ClippingRelation(models.Model):
content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
object_id = models.PositiveIntegerField(db_index=True)
content_object = GenericForeignKey()

clipping = models.ForeignKey(Clipping, on_delete=models.CASCADE)

def __str__(self):
return "Content: {} | Clipping: {}".format(self.content_object.name, self.clipping.title)

class Meta:
unique_together = ["content_type", "object_id", "clipping"]
37 changes: 37 additions & 0 deletions clipping/templates/admin/clipping/change_form.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
{% extends "admin/change_form.html" %}
{% block extrahead %}
{{ block.super }}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript">
const populateSelect = (defaultValue) =>
$.getJSON(
"/clipping/get/contentype_instances/",
{ id: $("select#id_content_type").val() },
function (items) {
var options = '<option value="">---------</option>';
for (const item of items) {
options += `<option value="${item.id}"` + (item.id === parseInt(defaultValue) ? ' selected="selected"' : "") + `>${item.name}</option>`;
}
$("select#id_object_id").html(options);
}
);

/*
inspect html to check id of Content select, populate
select Element if change occurs
*/
$(document).on("change", "select#id_content_type", () => populateSelect());

// Document ready
$(function () {
const objPk = $(location).attr("href").match("\/([0-9_]+)\/");
if (objPk && $("select#id_content_type").val()) {
$.getJSON("/clipping/get/selected_instance/", { id: objPk[1] }, (obj) =>
populateSelect(obj.object_id)
);
} else if ($("select#id_content_type").val()) {
populateSelect();
}
});
</script>
{% endblock %}
1 change: 1 addition & 0 deletions clipping/tests.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
# Create your tests here.
8 changes: 8 additions & 0 deletions clipping/urls.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
from django.urls import path

from . import views

urlpatterns = [
path("get/contentype_instances/", views.get_contenttype_instances),
path("get/selected_instance/", views.get_current_selected_instance),
]
46 changes: 46 additions & 0 deletions clipping/views.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
from django.contrib.auth.decorators import login_required
from django.contrib.contenttypes.models import ContentType
from django.core.exceptions import ObjectDoesNotExist
from django.http import JsonResponse

from core.models import Dataset, Table
from .models import ClippingRelation


@login_required
def get_contenttype_instances(request):
try:
pk = int(request.GET.get("id"))
content_type = ContentType.objects.get(id=pk)
if content_type.app_label == "core" and content_type.model == "dataset":
result = list(
Dataset.objects
.values("id", "name", "slug")
.order_by("slug")
)
for item in result:
item["name"] = f"{item['slug']} ({item['name']})"
del item["slug"]
elif content_type.app_label == "core" and content_type.model == "table":
result = list(
Table.objects.select_related("dataset")
.values("id", "name", "dataset__slug")
.order_by("dataset__slug", "name")
)
for item in result:
item["name"] = f"{item['dataset__slug']}.{item['name']}"
del item["dataset__slug"]
else:
return JsonResponse({"error": "Invalid content type ID"}, status=400)
return JsonResponse(result, safe=False)
except (ValueError, ObjectDoesNotExist):
return JsonResponse({"error": "Invalid content type ID"}, status=400)

@login_required
def get_current_selected_instance(request):
try:
pk = int(request.GET.get("id"))
result = ClippingRelation.objects.get(id=pk).object_id
return JsonResponse({"object_id": result})
except (ValueError, ObjectDoesNotExist):
return JsonResponse({"error": "Invalid clipping relation ID"}, status=400)
Loading
Loading