Skip to content

Commit

Permalink
feat(votepeloclima): add get_states and get_city_choices in candidatu…
Browse files Browse the repository at this point in the history
…re form
  • Loading branch information
miguelzinh3 committed Jul 15, 2024
1 parent d56d11a commit dad5a60
Show file tree
Hide file tree
Showing 6 changed files with 10,777 additions and 4 deletions.
10,671 changes: 10,671 additions & 0 deletions app/votepeloclima/candidature/csv/places.csv

Large diffs are not rendered by default.

36 changes: 33 additions & 3 deletions app/votepeloclima/candidature/forms.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,12 @@
from django import forms
from captcha.widgets import ReCaptchaV2Checkbox

from django_select2.forms import Select2Widget
from django.utils.functional import lazy
from django.urls import reverse_lazy

from .fields import ValidateOnceReCaptchaField
from .utils import get_ufs, get_choices


class CaptchaForm(forms.Form):
Expand All @@ -20,13 +25,38 @@ class InitialForm(forms.Form):
class ApplicationForm(forms.Form):
number_id = forms.IntegerField(label="Número de identificação", min_value=1)
intended_position = forms.CharField(label="Cargo pretendido")
state = forms.CharField(label="Estado")
city = forms.CharField(label="Cidade")
state = forms.ChoiceField(
label="Estado",
choices=lazy(get_ufs, list)(),
widget=Select2Widget(
attrs={
"data-address-fields": "state",
"data-address-url": reverse_lazy("address"),
}
)
)
city = forms.ChoiceField(
choices=[],
label="Cidade",
widget=Select2Widget(
attrs={
"data-address-fields": "city",
"data-address-url": reverse_lazy("address"),
}
)
)
is_collective_mandate = forms.BooleanField(
label="É um mandato coletivo?", required=False
)
political_party = forms.CharField(label="Partido político")

def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
if 'state' in self.data:
self.fields['city'].choices = get_choices(self.data.get('state'))
elif self.initial.get('state'):
self.fields['city'].choices = get_choices(self.initial.get('state'))


class ProfileForm(forms.Form):
video = forms.URLField(label="Vídeo", required=False)
Expand Down Expand Up @@ -57,7 +87,7 @@ class CheckoutForm(forms.Form):


register_form_list = [
("captcha", CaptchaForm),
# ("captcha", CaptchaForm),
("informacoes-iniciais", InitialForm),
("informacoes-de-candidatura", ApplicationForm),
("complemente-seu-perfil", ProfileForm),
Expand Down
30 changes: 30 additions & 0 deletions app/votepeloclima/candidature/static/js/address-fields.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
(function ($) {
"use strict";

$(function () {
const $stateField = $('[data-address-fields="state"]');
const $cityField = $('[data-address-fields="city"]');
console.log("oiee")

if ($stateField.length) {
$stateField.select2({ dropdownAutoWidth: true, width: 'auto', placeholder: 'Selecione seu estado' });
$cityField.select2({ allowClear: true, dropdownAutoWidth: true, width: 'auto', placeholder: 'Selecione sua cidade' });

var uf;
$stateField.on("change", (evt) => {
uf = evt.target.value;
const url = $stateField.data("address-url");

$.get(url + "?state=" + uf, (data) => {
$cityField.empty();
$cityField.append('<option value="">Selecione sua cidade</option>');
$.each(data, (index, value) => {
$cityField.append(
'<option value="' + value.code + '">' + value.name + '</option>'
);
});
});
});
}
});
}(window.jQuery));
30 changes: 30 additions & 0 deletions app/votepeloclima/candidature/utils.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
from django.conf import settings
import csv

def get_states(column_label="Nome_UF"):
csv_filename = settings.BASE_DIR / "votepeloclima/candidature/csv/places.csv"
states = set()
with open(csv_filename) as f:
reader = csv.DictReader(f)
reader.fieldnames = [field.strip() for field in reader.fieldnames]
for row in reader:
uf = row["UF"].strip()
state_name = row[column_label].strip()
states.add((uf, state_name))
return sorted(list(states), key=lambda x: x[1])

def get_ufs():
return get_states(column_label="Nome_UF")

def get_choices(uf):
csv_filename = settings.BASE_DIR / "votepeloclima/candidature/csv/places.csv"
choices = set()
with open(csv_filename) as f:
reader = csv.DictReader(f)
reader.fieldnames = [field.strip() for field in reader.fieldnames]
for row in reader:
if row["UF"].strip() == uf:
city_code = row["Código Município Completo"].strip()
city_name = row["Nome_Município"].strip()
choices.append((city_code, city_name))
return sorted(list(choices), key=lambda x: x[1])
11 changes: 11 additions & 0 deletions app/votepeloclima/candidature/views.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
from django.shortcuts import redirect
from django.contrib.auth.mixins import LoginRequiredMixin
from django.urls import reverse
from django.http import JsonResponse
from django.views import View
from django.contrib.auth.models import User
from django.views.generic import TemplateView
from django.http import HttpResponseForbidden
Expand All @@ -10,6 +13,7 @@
from contrib.oauth.utils import send_confirmation_email
from .models import CandidatureFlow, CandidatureFlowStatus, Candidature
from .forms import register_form_list, InitialForm, FlagForm, AppointmentForm
from .utils import get_choices


class RegisterView(NamedUrlSessionWizardView):
Expand Down Expand Up @@ -181,3 +185,10 @@ def get_context_data(self, **kwargs):
})

return context


class AddressView(View):
def get(self, request, *args, **kwargs):
state = request.GET.get('state')
cities = get_choices(state)
return JsonResponse([{'code': code, 'name': name} for code, name in cities], safe=False)
3 changes: 2 additions & 1 deletion app/votepeloclima/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.urls import path, include, re_path

from .candidature.views import RegisterView, EditRegisterView, DashboardView
from .candidature.views import RegisterView, EditRegisterView, DashboardView, AddressView

register_view = RegisterView.as_view(url_name="register_step", done_step_name="concluir")
register_edit_view = EditRegisterView.as_view(url_name="register_edit_step", done_step_name="concluir")
Expand All @@ -42,6 +42,7 @@
path("oauth/", DashboardView.as_view()),
path("admin/", admin.site.urls),
path("select2/", include("django_select2.urls")),
path('address/', AddressView.as_view(), name='address'),
path("", include("cms.urls")),
]

Expand Down

0 comments on commit dad5a60

Please sign in to comment.