Skip to content

Commit

Permalink
Update Django to 4.2, start splitting ajapaik into different apps
Browse files Browse the repository at this point in the history
  • Loading branch information
MaertHaekkinen committed Oct 22, 2024
1 parent d49f75e commit 3173cf6
Show file tree
Hide file tree
Showing 102 changed files with 4,089 additions and 3,911 deletions.
4 changes: 2 additions & 2 deletions ajapaik/ajapaik/account_adapter.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
from allauth.account.adapter import DefaultAccountAdapter
from django.conf import settings
from django.utils.http import is_safe_url
from django.utils.http import url_has_allowed_host_and_scheme


class safeUrlAdapter(DefaultAccountAdapter):
def is_safe_url(self, url):
return is_safe_url(url, allowed_hosts=settings.ALLOWED_HOSTS)
return url_has_allowed_host_and_scheme(url, allowed_hosts=settings.ALLOWED_HOSTS)
5 changes: 3 additions & 2 deletions ajapaik/ajapaik/admin.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
from django.contrib.admin.sites import NotRegistered, AlreadyRegistered
from django.contrib.auth.models import User
from django.http.response import HttpResponse
from django.urls import re_path
from django.utils.translation import gettext as _
from django_comments_xtd.admin import XtdCommentsAdmin
from sorl.thumbnail import delete as sorl_delete
Expand Down Expand Up @@ -94,9 +95,9 @@ def change_view(self, request, object_id, form_url='', extra_context={}):
return super(PhotoAdmin, self).change_view(request, object_id, form_url, extra_context=extra_context)

def get_urls(self):
from django.conf.urls import url
urls = super(PhotoAdmin, self).get_urls()
my_urls = list((url(r'^(.+)/%(url)s/$' % b, self.admin_site.admin_view(b['func'])) for b in self.extra_buttons))
my_urls = list(
(re_path(r'^(.+)/%(url)s/$' % b, self.admin_site.admin_view(b['func'])) for b in self.extra_buttons))
return my_urls + urls

inlines = (AlbumPhotoInline,)
Expand Down
181 changes: 67 additions & 114 deletions ajapaik/ajapaik/api.py

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion ajapaik/ajapaik/autocomplete.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
from django.forms import ModelForm

from ajapaik.ajapaik.models import Album, AlbumPhoto, ApplicationException, Dating, DatingConfirmation, GeoTag, \
Location, LocationPhoto, ImageSimilarity, ImageSimilaritySuggestion, Photo, Points, Profile, Skip, Supporter, Video
Location, LocationPhoto, ImageSimilarity, ImageSimilaritySuggestion, Photo, Points, Skip, Supporter, Video, Profile
from ajapaik.ajapaik_face_recognition.models import FaceRecognitionRectangle, FaceRecognitionRectangleFeedback, \
FaceRecognitionUserSuggestion, FaceRecognitionRectangleSubjectDataSuggestion
from ajapaik.ajapaik_object_recognition.models import ObjectDetectionAnnotation, ObjectAnnotationClass, \
Expand Down
4 changes: 3 additions & 1 deletion ajapaik/ajapaik/delfi.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ def clean(self):
try:
bbox_parts = [float(x) for x in bbox_parts]
except: # noqa
raise forms.ValidationError(_('Bounding box values must be numbers'))
raise forms.ValidationError(_(f'{bbox_parts[3]}Bounding box values must be numbers'))
our_ref = SpatialReference(4326)
delfi_ref = SpatialReference(3301)
trans = CoordTransform(delfi_ref, our_ref)
Expand Down Expand Up @@ -68,6 +68,8 @@ def photos_bbox(request):
})

return Response(photos)
else:
return Response({"errors": form.errors})

return Response([])

Expand Down
146 changes: 2 additions & 144 deletions ajapaik/ajapaik/forms.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,12 @@
from captcha.fields import ReCaptchaField
from dal import autocomplete
from django import forms
from django.conf import settings
from django.db.models import Q
from django.shortcuts import get_object_or_404
from django.utils.translation import get_language_info, gettext_lazy as _
from django_comments import get_model
from django.utils.translation import gettext_lazy as _
from django_comments_xtd.conf.defaults import COMMENT_MAX_LENGTH
from django_comments_xtd.forms import XtdCommentForm

from .models import (Album, Area, Dating, GeoTag, Licence, Photo, PhotoLike,
from .models import (Album, Area, Dating, GeoTag, Photo, PhotoLike,
Profile, Video)


Expand All @@ -37,13 +34,6 @@ def signup(self, request, user):
return user


class APIAuthForm(forms.Form):
_s = forms.CharField(max_length=255)
_u = forms.IntegerField()
_l = forms.CharField(max_length=2, required=False)
_v = forms.FloatField(required=False)


class APILoginForm(forms.Form):
LOGIN_TYPE_AUTO = 'auto'
LOGIN_TYPE_AJAPAIK = 'ajapaik'
Expand Down Expand Up @@ -258,16 +248,6 @@ class AddAlbumForm(forms.Form):
), label=_('Choose parent album'), required=False)


class PublicPhotoUploadForm(forms.Form):
institution = forms.CharField(max_length=255, required=False)
number = forms.CharField(max_length=100, required=False)
title = forms.CharField(max_length=255, required=False)
description = forms.CharField(max_length=2047, required=False)
date = forms.CharField(max_length=100, required=False)
url = forms.CharField(max_length=1023, required=False)
licence = forms.CharField(max_length=255, required=False)


class CuratorPhotoUploadForm(forms.Form):
id = forms.CharField(max_length=100)
title = forms.CharField(required=False)
Expand Down Expand Up @@ -309,11 +289,6 @@ class ConfirmGeotagForm(forms.Form):
photo = forms.ModelChoiceField(queryset=Photo.objects.filter(rephoto_of__isnull=True))


class FrontpagePagingForm(forms.Form):
album = forms.ModelChoiceField(queryset=Album.objects.filter(is_public=True), required=False)
page = forms.IntegerField(min_value=1, required=False)


class ApiAlbumNearestPhotosForm(forms.Form):
id = forms.ModelChoiceField(queryset=Album.objects.filter(is_public=True), required=False)
latitude = forms.FloatField(min_value=-85.05115, max_value=85)
Expand Down Expand Up @@ -416,100 +391,6 @@ class VideoStillCaptureForm(forms.Form):
timestamp = forms.IntegerField()


class UserPhotoUploadForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(UserPhotoUploadForm, self).__init__(*args, **kwargs)
self.fields['licence'].queryset = Licence.objects.filter(is_public=True)

class Meta:
model = Photo
fields = ('image', 'description', 'uploader_is_author', 'author', 'licence')
labels = {
'image': _('Picture file'),
'description': _('Description'),
'uploader_is_author': _('I am the author'),
'author': _('Author'),
'licence': _('Licence or status of copyright')
}
help_texts = {
'image': _('Accepted formats are .png or .jpg files'),
'description': _('Add a short description of the picture'),
'author': _('Author of the picture (photographer, painter)'),
'licence': _(
'''Please select a licence to let other people know if and how they can reuse the material you upload.
\n\nIf you are the author, you can choose the licence (we recommend using open Creative Commons
licences). If someone else created the work, you need to use the same licence and rights holder that it
currently has.\n\nCurrently we are also accepting content with unclear copyright status,
please choose ‘Copyright not evaluated’ then.''')
}
widgets = {
'description': forms.Textarea(
attrs={'rows': 1, 'cols': 40, 'placeholder': _('Description of the picture')}),
'author': forms.TextInput(attrs={'placeholder': _('Author name')}),
}

def clean(self):
super(UserPhotoUploadForm, self).clean()
if not self.cleaned_data.get('image'):
self.errors['image'] = [_('Missing image')]
if not self.cleaned_data.get('description'):
self.errors['description'] = [_('Missing description')]
if not self.cleaned_data.get('uploader_is_author') and not self.cleaned_data.get('licence'):
self.errors['licence'] = [_('Missing licence')]


class UserPhotoUploadAddAlbumForm(forms.ModelForm):
location = forms.CharField(max_length=255, required=False)

class Meta:
model = Album
fields = ('atype', 'subalbum_of', 'name', 'description', 'is_public', 'open', 'location', 'lat', 'lon')

def __init__(self, *args, **kwargs):
# TODO: Show person fields if applicable
self.profile = kwargs.pop('profile', None)
super(UserPhotoUploadAddAlbumForm, self).__init__(*args, **kwargs)
self.fields['subalbum_of'].label = _('Parent album')
self.fields['subalbum_of'].queryset = Album.objects.filter(atype=Album.CURATED) \
.filter(Q(open=True) | Q(profile=self.profile))
self.fields['location'].label = _('Location')
self.fields['location'].help_text = _('If this album is tied to a certain location, specify here')
self.fields['lat'].widget = forms.HiddenInput()
self.fields['lon'].widget = forms.HiddenInput()
self.fields['atype'].label = _('Album type')
self.fields['atype'].choices = [(Album.CURATED, _('Anything else')), (Album.PERSON, _('Person'))]
self.fields['name'].label = _('Name')
self.fields['description'].label = _('Description')
self.fields['is_public'].label = _('Is public')
self.fields['open'].label = _('Is open')


class UserSettingsForm(forms.ModelForm):
class Meta:
model = Profile
fields = ('preferred_language', 'newsletter_consent')
languages = settings.LANGUAGES
translated_languages = []
for language in languages:
li = get_language_info(language[0])
translated_languages.append((language[0], (li['name_local'].capitalize())))
labels = {
'preferred_language': _('My preferred language is'),
'newsletter_consent': _('I wish to receive the newsletter')
}
widgets = {
'preferred_language': forms.Select(choices=translated_languages),
'newsletter_consent': forms.Select(choices=[(True, _('Yes')), (False, _('No'))]),
}

def clean(self):
super(UserSettingsForm, self).clean()
if not self.cleaned_data.get('preferred_language'):
self.errors['preferred_language'] = [_('Please specify your prefered language')]
if self.cleaned_data.get('newsletter_consent') is None:
self.errors['newsletter_consent'] = [_('Please specify whether you would like to receive the newsletter')]


class RephotoUploadSettingsForm(forms.ModelForm):
class Meta:
model = Profile
Expand All @@ -528,15 +409,6 @@ def clean(self):
_('Please specify whether you would like your rephotos to be uploaded to Wikimedia Commons as well')]


class ChangeDisplayNameForm(forms.Form):
display_name = forms.CharField()

def clean(self):
super(ChangeDisplayNameForm, self).clean()
if self.cleaned_data.get('display_name') is None:
self.errors['display_name'] = [_('Please specify what would you like your display name to be')]


class CuratorWholeSetAlbumsSelectionForm(forms.Form):
albums = forms.ModelChoiceField(
queryset=Album.objects.all(),
Expand Down Expand Up @@ -582,20 +454,6 @@ def __init__(self, *args, **kwargs):
max_length=COMMENT_MAX_LENGTH)


class EditCommentForm(forms.Form):
comment_id = forms.IntegerField()
text = forms.CharField()

def clean_comment_id(self):
self.comment = get_object_or_404(
get_model(), pk=self.cleaned_data['comment_id']
)

def clean(self):
if self.comment.comment == self.cleaned_data['text']:
forms.ValidationError(_('Nothing to change.'), code='same_text')


class ApiFetchFinnaPhoto(forms.Form):
id = forms.CharField(max_length=255)

Expand Down
23 changes: 0 additions & 23 deletions ajapaik/ajapaik/fotis_utils.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,3 @@
import re
from typing import List

from ajapaik.ajapaik.models import Dating


Expand All @@ -25,23 +22,3 @@ def parse_fotis_timestamp_data(date_accuracy_in: str):
date_format = '%Y.%m.%d'

return date_accuracy, date_format


def transform_fotis_persons_response(persons_str: str) -> List[str]:
persons_str = persons_str.strip().strip(";")

if ";" in persons_str:
persons = persons_str.strip().split(";")
else:
persons = [persons_str]

result = []
for person in persons:
person = person.strip()
match = re.match(r'\b(\w+(?:\s*\w*))\s+\1\b', person)
if match:
result.append(match.groups()[0])
elif person:
result.append(person)

return list(set(result))
Loading

0 comments on commit 3173cf6

Please sign in to comment.