|
| 1 | +from django import forms |
| 2 | +from django.db import transaction |
| 3 | + |
| 4 | +from pyconbalkan.organizers.models import Volunteer, VolunteerPhoto |
| 5 | + |
| 6 | + |
| 7 | +class VolunteerCreateForm(forms.ModelForm): |
| 8 | + required_fields = ( |
| 9 | + 'full_name', 'name', 'date_of_birth', 'job', |
| 10 | + 'email', 'description', 'country', 'profile_photo' |
| 11 | + ) |
| 12 | + |
| 13 | + profile_picture = forms.ImageField(label='Profile Photo', required=True) |
| 14 | + |
| 15 | + def __init__(self, **kwargs): |
| 16 | + super().__init__(**kwargs) |
| 17 | + |
| 18 | + for name, field in self.fields.items(): |
| 19 | + self.add_required(name, field) |
| 20 | + self.add_form_control(field) |
| 21 | + self.label_as_placeholder(field, name) |
| 22 | + |
| 23 | + def add_form_control(self, field): |
| 24 | + old_classes = field.widget.attrs['class'] if 'class' in field.widget.attrs else '' |
| 25 | + field.widget.attrs.update({'class': f'{old_classes} form-control'}) |
| 26 | + |
| 27 | + def label_as_placeholder(self, field, name): |
| 28 | + placeholder = field.label if not field.required else field.label + '*' |
| 29 | + field.widget.attrs.update({'placeholder': placeholder}) |
| 30 | + |
| 31 | + if name != 'profile_picture': |
| 32 | + field.label = '' |
| 33 | + else: |
| 34 | + field.label = placeholder |
| 35 | + |
| 36 | + def add_required(self, name, field): |
| 37 | + if name in self.required_fields: |
| 38 | + field.required = True |
| 39 | + |
| 40 | + def save(self, commit=True): |
| 41 | + """ |
| 42 | + Save both Volunteer model and VolunteerPhoto at once. |
| 43 | + If more complex - maybe add formset. |
| 44 | + """ |
| 45 | + |
| 46 | + with transaction.atomic(): |
| 47 | + instance = super().save(commit=commit) |
| 48 | + VolunteerPhoto.objects.create( |
| 49 | + volunteer=instance, profile_picture=self.cleaned_data['profile_picture'] |
| 50 | + ) |
| 51 | + return instance |
| 52 | + |
| 53 | + class Meta: |
| 54 | + model = Volunteer |
| 55 | + exclude = ('active', 'user', 'type', 'slug', ) |
| 56 | + widgets = { |
| 57 | + 'date_of_birth': forms.DateInput(attrs={'class': 'datepicker'}), |
| 58 | + } |
0 commit comments