random all commit

This commit is contained in:
moanos [he/him] 2024-05-10 13:54:16 +02:00
parent ba7e229ab2
commit e2e3a77fd9
6 changed files with 220 additions and 42 deletions

View File

@ -13,7 +13,7 @@ authors = [
maintainers = [ maintainers = [
{name = "moanos", email = "julian-samuel@gebuehr.net"}, {name = "moanos", email = "julian-samuel@gebuehr.net"},
] ]
keywords = ["matrix", "registration", "bot", "user", "registration", "API" ] keywords = ["animal", "adoption", "django", "rescue", ]
license = {text = "AGPL-3.0-or-later"} license = {text = "AGPL-3.0-or-later"}
classifiers = [ classifiers = [
"Environment :: Web", "Environment :: Web",

View File

@ -1,9 +1,13 @@
import datetime
from django import forms from django import forms
from .models import AdoptionNotice, Animal, Image, Report, ModerationAction, User from .models import AdoptionNotice, Animal, Image, Report, ModerationAction, User, Species
from django_registration.forms import RegistrationForm from django_registration.forms import RegistrationForm
from crispy_forms.helper import FormHelper from crispy_forms.helper import FormHelper
from crispy_forms.layout import Submit from crispy_forms.layout import Submit, Layout, Fieldset, HTML, Row, Column, Field
from django.utils.translation import gettext_lazy as _ from django.utils.translation import gettext_lazy as _
from notfellchen.settings import MEDIA_URL
class DateInput(forms.DateInput): class DateInput(forms.DateInput):
input_type = 'date' input_type = 'date'
@ -38,7 +42,116 @@ class AdoptionNoticeForm(forms.ModelForm):
} }
class AnimalForm(forms.ModelForm): class AnimalForm(forms.Form):
def __init__(self, animal_id, *args, **kwargs):
photo_rows = []
super().__init__(*args, **kwargs)
# Get the animal instance
animal = Animal.objects.get(pk=animal_id)
# Define Django form fields for later use
self.fields["name"] = forms.CharField(initial=animal.name)
self.fields["species"] = forms.ChoiceField(
label=_("Tierart"),
choices=[(x.id, x.name) for x in Species.objects.all()],
initial=animal.species.pk
)
photos = animal.get_photos()
for photo in photos:
alt_field_name = f"image_alt_{photo.pk}"
self.fields[alt_field_name] = forms.CharField()
self.fields[alt_field_name].initial = photo.alt_text
title_field_name = f"image_title_{photo.pk}"
self.fields[title_field_name] = forms.CharField(max_length=200)
self.fields[title_field_name].initial = photo.title
delete_btn = f"delete_photo_{photo.pk}"
save_btn = f"save_photo_{photo.pk}"
current_row = Row(
Column(title_field_name, css_class="form-group col-md-2 mb-0"),
Column(
HTML(photo.as_html),
css_class="form-group col-md-4 mb-0"),
Column(alt_field_name, css_class="form-group col-md-2 mb-0"),
Column(
Submit(delete_btn, _("Löschen")),
css_class="form-group col-md-auto mb-0 needs_manual",
),
Column(
Submit(save_btn, _("Bearbeiten")),
css_class="form-group col-md-auto mb-0 needs_manual",
),
css_class="form-row",
)
photo_rows.append(current_row)
self.helper = FormHelper()
self.helper.form_class = 'card'
submit_form_btn = f"submit_form_{animal.pk}"
self.helper.layout = Layout(
Fieldset(
animal.name,
Row(
Field("name", selected="", css_class="form-group col-md-6 mb-0"),
Field("species", css_class="form-group col-md-6 mb-0"),
Submit(submit_form_btn, _("Submit"),
css_class="form-group col-md-2 mb-0 needs_manual",
),
css_class="form-row",
)
)
)
self.helper.layout.append(Fieldset(_("Fotos"), css_class="fieldsets"))
for photo_row in photo_rows:
self.helper.layout[-1].append(photo_row)
current_row = Row(
HTML(
"<hr style='border: 0; clear:both; display:block; width: 96%; background-color:black; height: 1px;'>"
)
)
self.helper.layout.append(current_row)
# self.helper.layout.append('i_want_to_add_a_new_column')
self.fields["add_image"] = forms.ImageField()
self.fields["add_image_alt"] = forms.CharField()
self.fields["add_image_title"] = forms.CharField(max_length=200, )
current_row = Row(
Column("add_image", css_class="form-group col-md-6 mb-0"),
Column("add_image_alt", css_class="form-group col-md-2 mb-0"),
Column("add_image_title", css_class="form-group col-md-2 mb-0"),
css_class="form-row",
)
#self.helper.layout.append(current_row)
#add_photo_btn = f"add_photo_btn_{animal.pk}"
#self.helper.layout.append(Submit(add_photo_btn, _("Bild hinzufügen")))
class AnimalForm2(forms.ModelForm):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.helper = FormHelper()
self.helper.form_id = 'form-animal'
self.helper.form_class = 'card'
self.helper.form_method = 'post'
self.helper.add_input(Submit('submit', _('Submit')))
class Meta: class Meta:
model = Animal model = Animal
picture = forms.ImageField(label='Image', required=False) picture = forms.ImageField(label='Image', required=False)
@ -49,6 +162,13 @@ class AnimalForm(forms.ModelForm):
class ImageForm(forms.ModelForm): class ImageForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.helper = FormHelper()
self.helper.form_id = 'form-animal-photo'
self.helper.form_class = 'card'
self.helper.form_method = 'post'
class Meta: class Meta:
model = Image model = Image
fields = ('title', 'image', 'alt_text') fields = ('title', 'image', 'alt_text')

View File

@ -10,6 +10,7 @@ from django.contrib.auth.models import Group
from django.contrib.auth.models import AbstractUser from django.contrib.auth.models import AbstractUser
from fellchensammlung.tools import misc from fellchensammlung.tools import misc
from notfellchen.settings import MEDIA_URL
class Language(models.Model): class Language(models.Model):
@ -41,6 +42,10 @@ class Image(models.Model):
def __str__(self): def __str__(self):
return self.title return self.title
@property
def as_html(self):
return f'<img src="{ MEDIA_URL }/{ self.image }" alt="{ self.alt_text }">'
class Species(models.Model): class Species(models.Model):
"""Model representing a species of animal.""" """Model representing a species of animal."""

View File

@ -1,5 +1,6 @@
{% extends "fellchensammlung/base_generic.html" %} {% extends "fellchensammlung/base_generic.html" %}
{% load i18n %} {% load i18n %}
{% load crispy_forms_tags %}
{% block content %} {% block content %}
<h1>{% translate "Vermitteln" %}</h1> <h1>{% translate "Vermitteln" %}</h1>
@ -8,17 +9,5 @@
kannst kannst
du im nächsten Schritt hochladen. du im nächsten Schritt hochladen.
{% endblocktranslate %} {% endblocktranslate %}
<form method="post" enctype="multipart/form-data"> {% crispy form %}
{% csrf_token %}
<div class="form-animal">
{{ form.as_p }}
</div>
<div class="form-image">
<h2>{% translate "Bild hinzufügen" %}</h2>
{{ image_form.as_p }}
</div>
<button name="button_add_another_animal"
type="submit">{% translate "Speichern und nächstes Tier hinzufügen" %}</button>
<button name="button_save_and_continue" type="submit">{% translate "Speichern und weiter" %}</button>
</form>
{% endblock %} {% endblock %}

View File

@ -11,19 +11,18 @@ urlpatterns = [
path("rss/", LatestAdoptionNoticesFeed(), name="rss"), path("rss/", LatestAdoptionNoticesFeed(), name="rss"),
# ex: /animal/5/ # ex: /animal/5/
path("<int:animal_id>/", views.animal_detail, name="animal-detail"), path("<int:animal_id>/", views.animal_detail, name="animal-detail"),
# ex: /animal/5/edit
path("<int:animal_id>/edit", views.change_animal, name="animal-edit"),
# ex: /adoption_notice/7/ # ex: /adoption_notice/7/
path("vermittlung/<int:adoption_notice_id>/", views.adoption_notice_detail, name="adoption-notice-detail"), path("vermittlung/<int:adoption_notice_id>/", views.adoption_notice_detail, name="adoption-notice-detail"),
# ex: /adoption_notice/7/edit
path("vermittlung/<int:adoption_notice_id>/edit", views.change_animal, name="adoption-notice-edit"),
# ex: /search/ # ex: /search/
path("suchen/", views.search, name="search"), path("suchen/", views.search, name="search"),
# ex: /vermitteln/ # ex: /vermitteln/
path("vermitteln/", views.add_adoption, name="add-adoption"), path("vermitteln/", views.add_adoption, name="add-adoption"),
# ex: vermitteln-tiere-hinzufügen/5
path("vermitteln-tiere-hinzufügen/<int:adoption_notice_id>",
views.add_animal_to_adoption,
name="add-animal-to-adoption"),
path("ueber-uns/", views.about, name="about"), path("ueber-uns/", views.about, name="about"),
############# #############

View File

@ -63,39 +63,104 @@ def add_adoption(request):
if form.is_valid(): if form.is_valid():
instance = form.save() instance = form.save()
return redirect(reverse("add-animal-to-adoption", args=[instance.pk])) return redirect(reverse("adoption-notice-edit", args=[instance.pk]))
else: else:
form = AdoptionNoticeForm() form = AdoptionNoticeForm()
return render(request, 'fellchensammlung/forms/form_add_adoption.html', {'form': form}) return render(request, 'fellchensammlung/forms/form_add_adoption.html', {'form': form})
@login_required @login_required
def add_animal_to_adoption(request, adoption_notice_id): def edit_adoption_notice(request, animal_id):
"""
View implements the following methods
* Updating an AdoptionNotice
* Adding animals to an AN
"""
def delete_photo():
print("Photo deleted")
def save_photo():
print("Photo save")
def add_photo():
print("Photo added")
def save_animal():
print("Animal saved")
if request.method == 'POST': if request.method == 'POST':
form = AnimalForm(request.POST) form = AnimalForm(request.POST, animal_id=animal_id, )
image_form = ImageForm(request.POST, request.FILES) for key in request.POST:
if key.startswith("delete_photo_"):
action = delete_photo
if key.startswith("save_photo_"):
action = save_photo
if key.startswith("add_photo"):
action = add_photo
if key.startswith("save_animal"):
action = save_animal
pk = key.split("_")[-1]
action(animal_id, pk, form_data=request.POST)
if form.is_valid(): if form.is_valid():
form.cleaned_data["adoption_notice_id"] = adoption_notice_id animal = form.save()
instance = form.save(commit=False) return render(request, 'fellchensammlung/forms/form_add_animal_to_adoption.html',
instance.adoption_notice_id = adoption_notice_id {'form': form})
instance.save()
if 'image_-image' in request.FILES:
image = Image(image=request.FILES['image_-image'])
image.save()
instance.photos.add(image)
if "button_add_another_animal" in request.POST:
return redirect(reverse("add-animal-to-adoption", args=[str(adoption_notice_id)]))
else: else:
return redirect(reverse("adoption-notice-detail", args=[str(adoption_notice_id)])) form = AnimalForm(animal_id)
else:
form = AnimalForm()
image_form = ImageForm(request.POST, request.FILES, prefix="image_") image_form = ImageForm(request.POST, request.FILES, prefix="image_")
return render(request, 'fellchensammlung/forms/form_add_animal_to_adoption.html', return render(request, 'fellchensammlung/forms/form_add_animal_to_adoption.html',
{'form': form, "image_form": image_form}) {'form': form})
@login_required
def change_animal(request, animal_id):
"""
View implements the following methods
* Updating an Animal
* Adding photos to an animal
"""
def delete_photo():
print("Photo deleted")
def save_photo():
print("Photo save")
def add_photo():
print("Photo added")
def save_animal():
print("Animal saved")
if request.method == 'POST':
form = AnimalForm(request.POST, animal_id=animal_id, )
for key in request.POST:
if key.startswith("delete_photo_"):
action = delete_photo
if key.startswith("save_photo_"):
action = save_photo
if key.startswith("add_photo"):
action = add_photo
if key.startswith("save_animal"):
action = save_animal
pk = key.split("_")[-1]
action(animal_id, pk, form_data=request.POST)
return render(request, 'fellchensammlung/forms/form_add_animal_to_adoption.html',
{'form': form})
else:
form = AnimalForm(animal_id)
image_form = ImageForm(request.POST, request.FILES, prefix="image_")
return render(request, 'fellchensammlung/forms/form_add_animal_to_adoption.html',
{'form': form})
def about(request): def about(request):