-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathforms.py
More file actions
195 lines (171 loc) Β· 7.52 KB
/
Copy pathforms.py
File metadata and controls
195 lines (171 loc) Β· 7.52 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
# from allauth.account.forms import BaseSignupForm
from contextlib import suppress
import random
import string
from PIL import Image
from io import BytesIO
from django.core.files import File
from django.urls.exceptions import NoReverseMatch
from crispy_forms.bootstrap import InlineCheckboxes
from allauth.socialaccount.forms import SignupForm
from django import forms
from django_summernote.widgets import SummernoteInplaceWidget
from django.utils.translation import ugettext_lazy as _
from django.conf import settings
from django.core.files.images import get_image_dimensions
from crispy_forms.layout import Submit
from crispy_forms.helper import FormHelper
from .models import Profile
from django.urls import reverse
from django.db import transaction
from django.contrib.auth import get_user_model
UserModel = get_user_model()
class ProfileForm(forms.ModelForm):
email = forms.EmailField(required=True)
def __init__(self, *args, **kwargs):
super(ProfileForm, self).__init__(*args, **kwargs)
self.fields['name_ko'].required = True
self.fields['name_en'].required = True
self.fields['email'].initial = self.instance.user.email
self.helper = FormHelper()
self.helper.form_method = 'post'
self.helper.add_input(Submit('submit', _('Submit')))
self.fields['image_ori'].help_text += _('Maximum size is %(size)d MB') \
% {'size': settings.SPEAKER_IMAGE_MAXIMUM_FILESIZE_IN_MB}
self.fields['image_ori'].help_text += ' / ' \
+ _('Minimum dimension is %(width)d x %(height)d') \
% {'width': settings.SPEAKER_IMAGE_MINIMUM_DIMENSION[0],
'height': settings.SPEAKER_IMAGE_MINIMUM_DIMENSION[1]}
class Meta:
model = Profile
fields = ('name_ko', 'name_en', 'email', 'phone',
'organization', 'image_ori', 'bio_ko', 'bio_en', 'agreement_receive_advertising_info')
widgets = {
'bio': SummernoteInplaceWidget(),
}
labels = {
'name_ko': _('μ΄λ¦ (νκΈ)'),
'name_en': _('μ΄λ¦ (μμ΄)'),
'image_ori': _('Photo'),
'agreement_receive_advertising_info': _('νλ³΄μ± λ©μΌ μμ λμ')
}
def save(self, commit=True):
# Update user email
user = self.instance.user
email = self.cleaned_data['email']
if email != user.email:
user.email = self.cleaned_data['email']
user.save()
# Make user code
profile = self.instance
if not profile.user_code:
length = 20
pool = string.ascii_letters + string.digits
while True:
result = ""
for _ in range(length):
result += random.choice(pool)
if not Profile.objects.filter(user_code=result).exists():
break
profile.user_code = result
profile.save()
# Optimize user profile image
image = self.instance.image_ori
small_image_size = 256
new_width = 0
new_height = 0
if image.width >= image.height:
new_height = small_image_size
new_width = int(small_image_size * image.width / image.height)
else:
new_width = small_image_size
new_height = int(small_image_size * image.height / image.width)
try:
PIL_image = Image.open(image.file)
image_small = PIL_image.resize((new_width, new_height))
blob = BytesIO()
image_small.save(blob, 'PNG')
self.instance.image_small.save(image.name+'_small.jpg', File(blob), save=False)
self.instance.save()
except ValueError: # λμΌν νμΌ μ
λ ₯
pass
return super(ProfileForm, self).save(commit=commit)
def clean_image(self):
image = self.cleaned_data.get('image_ori')
if image:
try:
if image._size > settings.SPEAKER_IMAGE_MAXIMUM_FILESIZE_IN_MB * 1024 * 1024:
raise forms.ValidationError(
_('Maximum size is %(size)d MB')
% {'size': settings.SPEAKER_IMAGE_MAXIMUM_FILESIZE_IN_MB}
)
except AttributeError:
pass
w, h = get_image_dimensions(image)
if w < settings.SPEAKER_IMAGE_MINIMUM_DIMENSION[0] \
or h < settings.SPEAKER_IMAGE_MINIMUM_DIMENSION[1]:
raise forms.ValidationError(
_('Minimum dimension is %(width)d x %(height)d')
% {'width': settings.SPEAKER_IMAGE_MINIMUM_DIMENSION[0],
'height': settings.SPEAKER_IMAGE_MINIMUM_DIMENSION[1]}
)
return image
class SocialSignupForm(SignupForm):
email = forms.EmailField(label=_('μ΄λ©μΌ'), help_text=_(
'νμ΄μ½ νμ¬μ κ΄λ ¨λ μλ΄ λ©μΌμ λ°μ μ΄λ©μΌ μ£Όμλ₯Ό μ
λ ₯ν΄μ£ΌμΈμ.'))
name = forms.CharField(max_length=100, label=_(
'μ΄λ¦'), help_text=_('κΈ°μ
ν μ΄λ¦μ΄ νμ¬ λΉμΌ μ΄λ¦νμ νμλ©λλ€.'))
organization = forms.CharField(max_length=100, required=False, label=_(
'μμ'), help_text=_('κΈ°μ
ν μ‘°μ§λͺ
μ΄ νμ¬ λΉμΌ μ΄λ¦νμ νμλ©λλ€. νμ μ
λ ₯ μ¬νμ μλλλ€.'))
checked_terms_of_service = forms.BooleanField()
checked_privacy_policy = forms.BooleanField()
checked_coc = forms.BooleanField()
def __init__(self, *args, **kwargs):
super(SocialSignupForm, self).__init__(*args, **kwargs)
self.fields['email'].initial = self.sociallogin.user.email
self.fields['username'].widget = forms.HiddenInput()
self.set_form()
self.set_agreement_labels()
def set_agreement_labels(self):
terms_of_service_text = _("μ΄μ© μ½κ΄μ λμν©λλ€.")
self.fields['checked_terms_of_service'].label = f'''
<a target="_blank" {self.reserve_flatpage_with_href_attr('2020/terms-of-service/')}">
{terms_of_service_text}
</a>
'''
checked_privacy_text = _("κ°μΈμ 보 μ²λ¦¬λ°©μΉ¨μ λμν©λλ€.")
self.fields['checked_privacy_policy'].label = f'''
<a target="_blank" {self.reserve_flatpage_with_href_attr('2020/privacy-policy/')}">
{checked_privacy_text}
</a>
'''
coc_text = _("νμ΄μ½ νκ΅ νλ κ°λ Ήμ λμν©λλ€.")
self.fields['checked_coc'].label = f'''
<a target="_blank" {self.reserve_flatpage_with_href_attr('2020/about/coc/')}">
{coc_text}
</a>
'''
def reserve_flatpage_with_href_attr(self, url):
try:
reserved_url = reverse('flatpage', kwargs={'url': url})
return f'href="{reserved_url}"'
except NoReverseMatch as e:
pass
return ''
def set_form(self):
self.helper = FormHelper()
self.helper.form_id = 'signup_form'
self.helper.form_class = 'signup'
self.helper.form_method = 'post'
self.helper.form_action = reverse('socialaccount_signup')
self.helper.add_input(Submit('submit', _('κ°μ
νκΈ°')))
@transaction.atomic
def save(self, request, commit=True):
user = super(SocialSignupForm, self).save(request)
user.email = self.cleaned_data['email']
user.save()
profile, _ = Profile.objects.get_or_create(user=user)
profile.name = self.cleaned_data['name']
profile.organization = self.cleaned_data['organization']
profile.save()
return user