This repository has been archived on 2025-05-04. You can view files and clone it, but you cannot make any changes to it's state, such as pushing and creating new issues, pull requests or comments.
s2forums/djangobb_forum/forms.py

565 lines
21 KiB
Python
Raw Permalink Normal View History

# coding: utf-8
2009-04-14 14:57:17 +03:00
import os.path
2013-01-30 19:15:52 -05:00
from datetime import timedelta
2009-01-05 14:30:08 +02:00
from django import forms
from django.conf import settings
from django.contrib.auth.models import User
from django.db.models.expressions import F
2012-02-17 00:30:03 +02:00
from django.utils.translation import ugettext_lazy as _
2013-01-30 19:15:52 -05:00
from django.utils.timezone import now
2009-01-05 14:30:08 +02:00
2010-10-30 09:03:50 +03:00
from djangobb_forum.models import Topic, Post, Profile, Reputation, Report, \
Attachment, Poll, PollChoice, PostStatus
main app moved from apps/forum to djangobb_forum. Warning: you must renaming DB tables prefix! --HG-- rename : djangobb/apps/forum/__init__.py => djangobb/djangobb_forum/__init__.py rename : djangobb/apps/forum/admin.py => djangobb/djangobb_forum/admin.py rename : djangobb/apps/forum/context_processors.py => djangobb/djangobb_forum/context_processors.py rename : djangobb/apps/forum/feeds.py => djangobb/djangobb_forum/feeds.py rename : djangobb/apps/forum/fields.py => djangobb/djangobb_forum/fields.py rename : djangobb/apps/forum/forms.py => djangobb/djangobb_forum/forms.py rename : djangobb/apps/forum/index.py => djangobb/djangobb_forum/index.py rename : djangobb/apps/forum/locale/ru/LC_MESSAGES/django.mo => djangobb/djangobb_forum/locale/ru/LC_MESSAGES/django.mo rename : djangobb/apps/forum/locale/ru/LC_MESSAGES/django.po => djangobb/djangobb_forum/locale/ru/LC_MESSAGES/django.po rename : djangobb/apps/forum/locale/zh_CN/LC_MESSAGES/django.mo => djangobb/djangobb_forum/locale/zh_CN/LC_MESSAGES/django.mo rename : djangobb/apps/forum/locale/zh_CN/LC_MESSAGES/django.po => djangobb/djangobb_forum/locale/zh_CN/LC_MESSAGES/django.po rename : djangobb/apps/forum/management/__init__.py => djangobb/djangobb_forum/management/__init__.py rename : djangobb/apps/forum/management/commands/__init__.py => djangobb/djangobb_forum/management/commands/__init__.py rename : djangobb/apps/forum/management/commands/unban.py => djangobb/djangobb_forum/management/commands/unban.py rename : djangobb/apps/forum/markups/__init__.py => djangobb/djangobb_forum/markups/__init__.py rename : djangobb/apps/forum/markups/mypostmarkup.py => djangobb/djangobb_forum/markups/mypostmarkup.py rename : djangobb/apps/forum/markups/postmarkup.py => djangobb/djangobb_forum/markups/postmarkup.py rename : djangobb/apps/forum/middleware.py => djangobb/djangobb_forum/middleware.py rename : djangobb/apps/forum/models.py => djangobb/djangobb_forum/models.py rename : djangobb/apps/forum/settings.py => djangobb/djangobb_forum/settings.py rename : djangobb/apps/forum/signals.py => djangobb/djangobb_forum/signals.py rename : djangobb/apps/forum/subscription.py => djangobb/djangobb_forum/subscription.py rename : djangobb/apps/forum/templates/forum/add_post.html => djangobb/djangobb_forum/templates/forum/add_post.html rename : djangobb/apps/forum/templates/forum/base.html => djangobb/djangobb_forum/templates/forum/base.html rename : djangobb/apps/forum/templates/forum/delete_posts.html => djangobb/djangobb_forum/templates/forum/delete_posts.html rename : djangobb/apps/forum/templates/forum/edit_post.html => djangobb/djangobb_forum/templates/forum/edit_post.html rename : djangobb/apps/forum/templates/forum/feeds/posts_description.html => djangobb/djangobb_forum/templates/forum/feeds/posts_description.html rename : djangobb/apps/forum/templates/forum/feeds/posts_title.html => djangobb/djangobb_forum/templates/forum/feeds/posts_title.html rename : djangobb/apps/forum/templates/forum/feeds/topics_description.html => djangobb/djangobb_forum/templates/forum/feeds/topics_description.html rename : djangobb/apps/forum/templates/forum/feeds/topics_title.html => djangobb/djangobb_forum/templates/forum/feeds/topics_title.html rename : djangobb/apps/forum/templates/forum/forum.html => djangobb/djangobb_forum/templates/forum/forum.html rename : djangobb/apps/forum/templates/forum/forum_row.html => djangobb/djangobb_forum/templates/forum/forum_row.html rename : djangobb/apps/forum/templates/forum/header.html => djangobb/djangobb_forum/templates/forum/header.html rename : djangobb/apps/forum/templates/forum/index.html => djangobb/djangobb_forum/templates/forum/index.html rename : djangobb/apps/forum/templates/forum/lofi/base.html => djangobb/djangobb_forum/templates/forum/lofi/base.html rename : djangobb/apps/forum/templates/forum/lofi/footer.html => djangobb/djangobb_forum/templates/forum/lofi/footer.html rename : djangobb/apps/forum/templates/forum/lofi/forum.html => djangobb/djangobb_forum/templates/forum/lofi/forum.html rename : djangobb/apps/forum/templates/forum/lofi/header.html => djangobb/djangobb_forum/templates/forum/lofi/header.html rename : djangobb/apps/forum/templates/forum/lofi/index.html => djangobb/djangobb_forum/templates/forum/lofi/index.html rename : djangobb/apps/forum/templates/forum/lofi/pagination.html => djangobb/djangobb_forum/templates/forum/lofi/pagination.html rename : djangobb/apps/forum/templates/forum/lofi/topic.html => djangobb/djangobb_forum/templates/forum/lofi/topic.html rename : djangobb/apps/forum/templates/forum/mail_to.html => djangobb/djangobb_forum/templates/forum/mail_to.html rename : djangobb/apps/forum/templates/forum/moderate.html => djangobb/djangobb_forum/templates/forum/moderate.html rename : djangobb/apps/forum/templates/forum/moderators.html => djangobb/djangobb_forum/templates/forum/moderators.html rename : djangobb/apps/forum/templates/forum/move_topic.html => djangobb/djangobb_forum/templates/forum/move_topic.html rename : djangobb/apps/forum/templates/forum/pagination.html => djangobb/djangobb_forum/templates/forum/pagination.html rename : djangobb/apps/forum/templates/forum/pm/base_pm.html => djangobb/djangobb_forum/templates/forum/pm/base_pm.html rename : djangobb/apps/forum/templates/forum/pm/create_pm.html => djangobb/djangobb_forum/templates/forum/pm/create_pm.html rename : djangobb/apps/forum/templates/forum/pm/inbox.html => djangobb/djangobb_forum/templates/forum/pm/inbox.html rename : djangobb/apps/forum/templates/forum/pm/menu_pm.html => djangobb/djangobb_forum/templates/forum/pm/menu_pm.html rename : djangobb/apps/forum/templates/forum/pm/message.html => djangobb/djangobb_forum/templates/forum/pm/message.html rename : djangobb/apps/forum/templates/forum/pm/outbox.html => djangobb/djangobb_forum/templates/forum/pm/outbox.html rename : djangobb/apps/forum/templates/forum/post_preview.html => djangobb/djangobb_forum/templates/forum/post_preview.html rename : djangobb/apps/forum/templates/forum/profile/profile_admin.html => djangobb/djangobb_forum/templates/forum/profile/profile_admin.html rename : djangobb/apps/forum/templates/forum/profile/profile_display.html => djangobb/djangobb_forum/templates/forum/profile/profile_display.html rename : djangobb/apps/forum/templates/forum/profile/profile_essentials.html => djangobb/djangobb_forum/templates/forum/profile/profile_essentials.html rename : djangobb/apps/forum/templates/forum/profile/profile_menu.html => djangobb/djangobb_forum/templates/forum/profile/profile_menu.html rename : djangobb/apps/forum/templates/forum/profile/profile_messaging.html => djangobb/djangobb_forum/templates/forum/profile/profile_messaging.html rename : djangobb/apps/forum/templates/forum/profile/profile_personal.html => djangobb/djangobb_forum/templates/forum/profile/profile_personal.html rename : djangobb/apps/forum/templates/forum/profile/profile_personality.html => djangobb/djangobb_forum/templates/forum/profile/profile_personality.html rename : djangobb/apps/forum/templates/forum/profile/profile_privacy.html => djangobb/djangobb_forum/templates/forum/profile/profile_privacy.html rename : djangobb/apps/forum/templates/forum/report.html => djangobb/djangobb_forum/templates/forum/report.html rename : djangobb/apps/forum/templates/forum/reputation.html => djangobb/djangobb_forum/templates/forum/reputation.html rename : djangobb/apps/forum/templates/forum/reputation_form.html => djangobb/djangobb_forum/templates/forum/reputation_form.html rename : djangobb/apps/forum/templates/forum/search_form.html => djangobb/djangobb_forum/templates/forum/search_form.html rename : djangobb/apps/forum/templates/forum/search_posts.html => djangobb/djangobb_forum/templates/forum/search_posts.html rename : djangobb/apps/forum/templates/forum/search_topics.html => djangobb/djangobb_forum/templates/forum/search_topics.html rename : djangobb/apps/forum/templates/forum/topic.html => djangobb/djangobb_forum/templates/forum/topic.html rename : djangobb/apps/forum/templates/forum/upload_avatar.html => djangobb/djangobb_forum/templates/forum/upload_avatar.html rename : djangobb/apps/forum/templates/forum/user.html => djangobb/djangobb_forum/templates/forum/user.html rename : djangobb/apps/forum/templates/forum/users.html => djangobb/djangobb_forum/templates/forum/users.html rename : djangobb/apps/forum/templatetags/__init__.py => djangobb/djangobb_forum/templatetags/__init__.py rename : djangobb/apps/forum/templatetags/forum_extras.py => djangobb/djangobb_forum/templatetags/forum_extras.py rename : djangobb/apps/forum/tests/__init__.py => djangobb/djangobb_forum/tests/__init__.py rename : djangobb/apps/forum/tests/postmarkup.py => djangobb/djangobb_forum/tests/postmarkup.py rename : djangobb/apps/forum/urls.py => djangobb/djangobb_forum/urls.py rename : djangobb/apps/forum/util.py => djangobb/djangobb_forum/util.py rename : djangobb/apps/forum/views.py => djangobb/djangobb_forum/views.py
2009-12-23 17:06:48 +02:00
from djangobb_forum import settings as forum_settings
2014-02-13 14:06:27 -05:00
from djangobb_forum.util import smiles, convert_text_to_html, filter_language, \
set_language, UnapprovedImageError
2013-06-25 16:37:17 +00:00
# scratchr2
from base_comments.models import BaseComment
2014-02-19 10:12:38 -05:00
import logging
logger = logging.getLogger(__name__)
2009-01-05 14:30:08 +02:00
SORT_USER_BY_CHOICES = (
('username', _(u'Username')),
('registered', _(u'Registered')),
2013-01-14 22:57:35 -05:00
('num_posts', _(u'Number of posts')),
2009-01-05 14:30:08 +02:00
)
SORT_POST_BY_CHOICES = (
('0', _(u'Post time')),
('1', _(u'Author')),
('2', _(u'Subject')),
('3', _(u'Forum')),
)
SORT_DIR_CHOICES = (
('ASC', _(u'Ascending')),
('DESC', _(u'Descending')),
)
SHOW_AS_CHOICES = (
('topics', _(u'Topics')),
('posts', _(u'Posts')),
)
SEARCH_IN_CHOICES = (
('all', _(u'Message text and topic subject')),
('message', _(u'Message text only')),
('topic', _(u'Topic subject only')),
)
class AddPostForm(forms.ModelForm):
FORM_NAME = "AddPostForm" # used in view and template submit button
name = forms.CharField(label=_('Subject'), max_length=155,
2009-01-05 14:30:08 +02:00
widget=forms.TextInput(attrs={'size':'115'}))
2009-04-21 20:45:03 +03:00
attachment = forms.FileField(label=_('Attachment'), required=False)
2013-08-20 20:05:19 +00:00
subscribe = forms.BooleanField(label=_('Subscribe'), help_text=_("Subscribe to this topic."), required=False)
2009-01-05 14:30:08 +02:00
class Meta:
model = Post
fields = ['body']
def __init__(self, *args, **kwargs):
self.user = kwargs.pop('user', None)
self.topic = kwargs.pop('topic', None)
self.forum = kwargs.pop('forum', None)
self.ip = kwargs.pop('ip', None)
2013-08-14 23:28:13 +00:00
self.is_ip_banned = kwargs.pop('is_ip_banned')
2014-02-14 15:08:16 -05:00
self.request_data = kwargs.pop('request_data', {})
self.url = kwargs.pop('url', None)
2009-01-05 14:30:08 +02:00
super(AddPostForm, self).__init__(*args, **kwargs)
2009-05-25 13:56:21 +03:00
2009-01-05 14:30:08 +02:00
if self.topic:
self.fields['name'].widget = forms.HiddenInput()
self.fields['name'].required = False
2009-05-25 13:56:21 +03:00
self.fields['body'].widget = forms.Textarea(attrs={'class':'markup', 'rows':'20', 'cols':'95'})
2009-05-25 13:56:21 +03:00
2009-04-14 14:57:17 +03:00
if not forum_settings.ATTACHMENT_SUPPORT:
self.fields['attachment'].widget = forms.HiddenInput()
self.fields['attachment'].required = False
2009-01-05 14:30:08 +02:00
def clean(self):
'''
checking is post subject and body contains not only space characters
'''
errmsg = _('Can\'t be empty nor contain only whitespace characters')
cleaned_data = self.cleaned_data
body = cleaned_data.get('body')
subject = cleaned_data.get('name')
2011-05-17 10:37:25 +03:00
if subject:
if not subject.strip():
self._errors['name'] = self.error_class([errmsg])
del cleaned_data['name']
2013-01-15 16:00:14 -05:00
cleaned_data['name'] = filter_language(subject)
2013-06-25 16:37:17 +00:00
if BaseComment.user_is_muted(self.user):
self._errors['body'] = self.error_class([_("Hmm, the filterbot is pretty sure your recent comments weren't ok for Scratch, so your account has been muted for the rest of the day. :/")])
2013-08-14 23:28:13 +00:00
if self.is_ip_banned:
error = """Sorry, the Scratch Team had to prevent your network from
sharing comments or projects because it was used to break our
community guidelines too many times. You can still share comments
and projects from another network. If you'd like to appeal this
block, you can contact {appeal_email}.
""".format(appeal_email=settings.BAN_APPEAL_EMAIL)
self._errors['body'] = self.error_class([_(error)])
2011-05-17 10:37:25 +03:00
if body:
if not body.strip():
self._errors['body'] = self.error_class([errmsg])
del cleaned_data['body']
2012-12-05 21:24:42 -05:00
try:
2013-01-17 20:28:40 -05:00
convert_text_to_html(body, self.user.forum_profile)
2012-12-05 21:24:42 -05:00
except UnapprovedImageError as e:
self._errors['body'] = self.error_class([e.user_error()])
del cleaned_data['body']
2014-02-13 14:06:27 -05:00
2013-01-15 16:00:14 -05:00
cleaned_data['body'] = filter_language(body)
try:
recent_post = Post.objects.filter(user=self.user).latest()
2013-01-30 19:15:52 -05:00
lastpost_diff = now() - recent_post.created
except Post.DoesNotExist:
lastpost_diff = timedelta(1) # one day if first post
if forum_settings.POST_FLOOD and not self.user.has_perm('djangobb_forum.fast_post'):
if self.user.has_perm('djangobb_forum.med_post'):
if lastpost_diff.total_seconds() < forum_settings.POST_FLOOD_MED:
2013-02-18 18:59:27 -05:00
self._errors['body'] = self.error_class([_("Sorry, you have to wait %d seconds between posts." % forum_settings.POST_FLOOD_MED)])
2013-04-08 22:46:33 +00:00
else:
if lastpost_diff.total_seconds() < forum_settings.POST_FLOOD_SLOW:
2013-02-18 18:59:27 -05:00
self._errors['body'] = self.error_class([_("Sorry, you have to wait %d seconds between posts." % forum_settings.POST_FLOOD_SLOW)])
return cleaned_data
2009-04-14 14:57:17 +03:00
def clean_attachment(self):
if self.cleaned_data['attachment']:
memfile = self.cleaned_data['attachment']
if memfile.size > forum_settings.ATTACHMENT_SIZE_LIMIT:
raise forms.ValidationError(_('Attachment is too big'))
return self.cleaned_data['attachment']
2009-01-05 14:30:08 +02:00
2009-11-20 16:25:14 +02:00
def save(self):
2009-01-05 14:30:08 +02:00
if self.forum:
topic = Topic(forum=self.forum,
user=self.user,
name=self.cleaned_data['name'])
topic.save()
else:
topic = self.topic
if self.cleaned_data['subscribe']:
# User would like to subscripe to this topic
topic.subscribers.add(self.user)
2009-01-05 14:30:08 +02:00
post = Post(topic=topic, user=self.user, user_ip=self.ip,
markup=self.user.forum_profile.markup,
2009-01-05 14:30:08 +02:00
body=self.cleaned_data['body'])
2009-11-20 16:25:14 +02:00
post.save()
if self.user.groups.filter(name="New Scratchers").exists():
tracking_data = dict(**self.request_data)
tracking_data['permalink'] = self.url
status = PostStatus.objects.create_for_post(post, **tracking_data)
2009-04-14 14:57:17 +03:00
if forum_settings.ATTACHMENT_SUPPORT:
self.save_attachment(post, self.cleaned_data['attachment'])
2009-01-05 14:30:08 +02:00
return post
2009-11-20 16:25:14 +02:00
2009-04-14 14:57:17 +03:00
def save_attachment(self, post, memfile):
if memfile:
obj = Attachment(size=memfile.size, content_type=memfile.content_type,
name=memfile.name, post=post)
dir = os.path.join(settings.MEDIA_ROOT, forum_settings.ATTACHMENT_UPLOAD_TO)
fname = '%d.0' % post.id
path = os.path.join(dir, fname)
2010-02-18 11:04:35 +02:00
file(path, 'wb').write(memfile.read())
2009-04-14 14:57:17 +03:00
obj.path = fname
obj.save()
2009-12-17 22:30:17 +02:00
class EditPostForm(forms.ModelForm):
name = forms.CharField(required=False, label=_('Subject'), max_length=155,
2009-12-17 22:30:17 +02:00
widget=forms.TextInput(attrs={'size':'115'}))
2013-02-19 01:05:40 -05:00
silent_edit = forms.BooleanField(required=False, label=_('Silent edit?'))
2009-12-17 22:30:17 +02:00
class Meta:
model = Post
fields = ['body']
def __init__(self, *args, **kwargs):
self.topic = kwargs.pop('topic', None)
super(EditPostForm, self).__init__(*args, **kwargs)
self.fields['name'].initial = self.topic
self.fields['body'].widget = forms.Textarea(attrs={'class':'markup'})
2009-12-17 22:30:17 +02:00
2012-12-05 21:24:42 -05:00
def clean(self):
cleaned_data = self.cleaned_data
2013-01-15 16:00:14 -05:00
subject = cleaned_data.get('name')
if subject:
cleaned_data['name'] = filter_language(subject)
2012-12-05 21:24:42 -05:00
body = cleaned_data.get('body')
if body:
try:
2013-01-17 20:28:40 -05:00
convert_text_to_html(body, self.instance)
2012-12-05 21:24:42 -05:00
except UnapprovedImageError as e:
self._errors['body'] = self.error_class([e.user_error()])
del cleaned_data['body']
2013-01-15 16:00:14 -05:00
cleaned_data['body'] = filter_language(body)
2012-12-05 21:24:42 -05:00
return cleaned_data
2009-12-17 22:30:17 +02:00
def save(self, commit=True):
post = super(EditPostForm, self).save(commit=False)
topic_name = self.cleaned_data['name']
if topic_name:
post.topic.name = topic_name
if commit:
post.topic.save()
post.save()
return post
2009-01-05 14:30:08 +02:00
class EssentialsProfileForm(forms.ModelForm):
username = forms.CharField(label=_('Username'))
email = forms.CharField(label=_('E-mail'))
2009-01-05 14:30:08 +02:00
class Meta:
model = Profile
fields = ['auto_subscribe', 'time_zone', 'language']
2009-01-05 14:30:08 +02:00
def __init__(self, *args, **kwargs):
2012-03-05 01:51:00 +02:00
extra_args = kwargs.pop('extra_args', {})
self.request = extra_args.pop('request', None)
self.profile = kwargs['instance']
2009-01-05 14:30:08 +02:00
super(EssentialsProfileForm, self).__init__(*args, **kwargs)
self.fields['username'].initial = self.profile.user.username
if not self.request.user.is_superuser:
2009-04-21 14:41:20 +03:00
self.fields['username'].widget = forms.HiddenInput()
self.fields['email'].initial = self.profile.user.email
2009-07-02 16:31:48 +03:00
def save(self, commit=True):
2009-01-05 14:30:08 +02:00
if self.cleaned_data:
if self.request.user.is_superuser:
self.profile.user.username = self.cleaned_data['username']
self.profile.user.email = self.cleaned_data['email']
self.profile.time_zone = self.cleaned_data['time_zone']
self.profile.language = self.cleaned_data['language']
self.profile.user.save()
2009-07-02 16:31:48 +03:00
if commit:
self.profile.save()
set_language(self.request, self.profile.language)
return self.profile
2009-01-05 14:30:08 +02:00
class PersonalProfileForm(forms.ModelForm):
2010-01-05 16:16:05 +02:00
name = forms.CharField(label=_('Real name'), required=False)
2009-01-05 14:30:08 +02:00
class Meta:
model = Profile
fields = ['status', 'location', 'site']
2009-01-05 14:30:08 +02:00
def __init__(self, *args, **kwargs):
2012-03-05 01:51:00 +02:00
extra_args = kwargs.pop('extra_args', {})
2009-07-02 16:31:48 +03:00
self.profile = kwargs['instance']
2009-01-05 14:30:08 +02:00
super(PersonalProfileForm, self).__init__(*args, **kwargs)
self.fields['name'].initial = "%s %s" % (self.profile.user.first_name, self.profile.user.last_name)
2009-07-02 16:31:48 +03:00
def save(self, commit=True):
self.profile.status = self.cleaned_data['status']
self.profile.location = self.cleaned_data['location']
self.profile.site = self.cleaned_data['site']
2009-01-05 14:30:08 +02:00
if self.cleaned_data['name']:
cleaned_name = self.cleaned_data['name'].strip()
if ' ' in cleaned_name:
self.profile.user.first_name, self.profile.user.last_name = cleaned_name.split(None, 1)
2009-01-05 14:30:08 +02:00
else:
self.profile.user.first_name = cleaned_name
self.profile.user.last_name = ''
self.profile.user.save()
2009-07-02 16:31:48 +03:00
if commit:
self.profile.save()
return self.profile
2009-01-05 14:30:08 +02:00
class MessagingProfileForm(forms.ModelForm):
class Meta:
model = Profile
fields = ['jabber', 'icq', 'msn', 'aim', 'yahoo']
2012-03-05 01:51:00 +02:00
def __init__(self, *args, **kwargs):
extra_args = kwargs.pop('extra_args', {})
super(MessagingProfileForm, self).__init__(*args, **kwargs)
2009-01-05 14:30:08 +02:00
class PersonalityProfileForm(forms.ModelForm):
class Meta:
model = Profile
fields = ['show_avatar', 'signature']
2009-01-05 14:30:08 +02:00
def __init__(self, *args, **kwargs):
2012-03-05 01:51:00 +02:00
extra_args = kwargs.pop('extra_args', {})
self.profile = kwargs['instance']
2009-01-05 14:30:08 +02:00
super(PersonalityProfileForm, self).__init__(*args, **kwargs)
self.fields['signature'].widget = forms.Textarea(attrs={'class':'markup', 'rows':'10', 'cols':'75'})
def clean(self):
cleaned_data = self.cleaned_data
signature = cleaned_data.get('signature')
if signature:
try:
2013-01-17 20:28:40 -05:00
convert_text_to_html(signature, self.profile)
except UnapprovedImageError as e:
self._errors['signature'] = self.error_class([e.user_error()])
del cleaned_data['signature']
cleaned_data['signature'] = filter_language(signature)
return cleaned_data
2009-07-02 16:31:48 +03:00
def save(self, commit=True):
2009-01-05 14:30:08 +02:00
profile = super(PersonalityProfileForm, self).save(commit=False)
2013-01-17 20:28:40 -05:00
profile.signature_html = convert_text_to_html(profile.signature, self.profile)
2012-12-04 22:30:01 -05:00
if forum_settings.SMILES_SUPPORT:
profile.signature_html = smiles(profile.signature_html)
2009-07-02 16:31:48 +03:00
if commit:
profile.save()
2009-01-05 14:30:08 +02:00
return profile
2009-01-05 14:30:08 +02:00
class DisplayProfileForm(forms.ModelForm):
class Meta:
model = Profile
fields = ['theme', 'markup', 'show_smilies']
2012-03-05 01:51:00 +02:00
def __init__(self, *args, **kwargs):
extra_args = kwargs.pop('extra_args', {})
super(DisplayProfileForm, self).__init__(*args, **kwargs)
2009-01-05 14:30:08 +02:00
class PrivacyProfileForm(forms.ModelForm):
class Meta:
model = Profile
fields = ['privacy_permission']
2009-01-05 14:30:08 +02:00
def __init__(self, *args, **kwargs):
2012-03-05 01:51:00 +02:00
extra_args = kwargs.pop('extra_args', {})
2009-01-05 14:30:08 +02:00
super(PrivacyProfileForm, self).__init__(*args, **kwargs)
self.fields['privacy_permission'].widget = forms.RadioSelect(
2009-01-05 14:30:08 +02:00
choices=self.fields['privacy_permission'].choices
)
2009-04-15 12:12:20 +03:00
2009-01-05 14:30:08 +02:00
class UploadAvatarForm(forms.ModelForm):
class Meta:
model = Profile
fields = ['avatar']
2012-03-05 01:51:00 +02:00
def __init__(self, *args, **kwargs):
extra_args = kwargs.pop('extra_args', {})
super(UploadAvatarForm, self).__init__(*args, **kwargs)
2009-04-15 12:12:20 +03:00
2009-01-05 14:30:08 +02:00
class UserSearchForm(forms.Form):
username = forms.CharField(required=False, label=_('Username'))
2009-01-05 14:30:08 +02:00
#show_group = forms.ChoiceField(choices=SHOW_GROUP_CHOICES)
sort_by = forms.ChoiceField(choices=SORT_USER_BY_CHOICES, label=_('Sort by'))
sort_dir = forms.ChoiceField(choices=SORT_DIR_CHOICES, label=_('Sort order'))
2009-01-05 14:30:08 +02:00
def filter(self, qs):
if self.is_valid():
username = self.cleaned_data['username']
#show_group = self.cleaned_data['show_group']
sort_by = self.cleaned_data['sort_by']
sort_dir = self.cleaned_data['sort_dir']
2012-04-25 14:04:46 +03:00
qs = qs.filter(username__contains=username, forum_profile__post_count__gte=forum_settings.POST_USER_SEARCH)
if sort_by == 'username':
if sort_dir == 'ASC':
2012-04-25 14:04:46 +03:00
return qs.order_by('username')
elif sort_dir == 'DESC':
2012-04-25 14:04:46 +03:00
return qs.order_by('-username')
elif sort_by == 'registered':
if sort_dir == 'ASC':
2012-04-25 14:04:46 +03:00
return qs.order_by('date_joined')
elif sort_dir == 'DESC':
2012-04-25 14:04:46 +03:00
return qs.order_by('-date_joined')
elif sort_by == 'num_posts':
if sort_dir == 'ASC':
2012-04-25 14:04:46 +03:00
return qs.order_by('forum_profile__post_count')
elif sort_dir == 'DESC':
2012-04-25 14:04:46 +03:00
return qs.order_by('-forum_profile__post_count')
2009-01-05 14:30:08 +02:00
else:
return qs
2009-04-03 15:09:08 +03:00
class PostSearchForm(forms.Form):
keywords = forms.CharField(required=False, label=_('Keyword search'),
2009-04-03 15:09:08 +03:00
widget=forms.TextInput(attrs={'size':'40', 'maxlength':'100'}))
author = forms.CharField(required=False, label=_('Author search'),
widget=forms.TextInput(attrs={'size':'25', 'maxlength':'25'}))
forum = forms.CharField(required=False, label=_('Forum'))
search_in = forms.ChoiceField(choices=SEARCH_IN_CHOICES, label=_('Search in'))
sort_by = forms.ChoiceField(choices=SORT_POST_BY_CHOICES, label=_('Sort by'))
2010-11-04 12:49:41 +02:00
sort_dir = forms.ChoiceField(choices=SORT_DIR_CHOICES, initial='DESC', label=_('Sort order'))
2009-04-03 15:09:08 +03:00
show_as = forms.ChoiceField(choices=SHOW_AS_CHOICES, label=_('Show results as'))
2009-04-03 15:09:08 +03:00
2009-01-05 14:30:08 +02:00
class ReputationForm(forms.ModelForm):
2009-01-05 14:30:08 +02:00
class Meta:
model = Reputation
fields = ['reason', 'post', 'sign']
2009-01-05 14:30:08 +02:00
def __init__(self, *args, **kwargs):
self.from_user = kwargs.pop('from_user', None)
self.to_user = kwargs.pop('to_user', None)
self.post = kwargs.pop('post', None)
2009-01-05 14:30:08 +02:00
self.sign = kwargs.pop('sign', None)
super(ReputationForm, self).__init__(*args, **kwargs)
self.fields['post'].widget = forms.HiddenInput()
2009-01-05 14:30:08 +02:00
self.fields['sign'].widget = forms.HiddenInput()
self.fields['reason'].widget = forms.Textarea(attrs={'class':'markup'})
2009-01-05 14:30:08 +02:00
def clean_to_user(self):
name = self.cleaned_data['to_user']
try:
user = User.objects.get(username=name)
except User.DoesNotExist:
2013-01-14 22:57:35 -05:00
raise forms.ValidationError(_('User "%s" does not exist') % name)
2009-01-05 14:30:08 +02:00
else:
return user
def clean(self):
try:
Reputation.objects.get(from_user=self.from_user, post=self.cleaned_data['post'])
except Reputation.DoesNotExist:
pass
else:
raise forms.ValidationError(_('You already voted for this post'))
# check if this post really belong to `from_user`
if not Post.objects.filter(pk=self.cleaned_data['post'].id, user=self.to_user).exists():
2013-01-14 22:57:35 -05:00
raise forms.ValidationError(_('This post does\'t belong to that user'))
return self.cleaned_data
2009-07-02 16:31:48 +03:00
def save(self, commit=True):
2009-01-05 14:30:08 +02:00
reputation = super(ReputationForm, self).save(commit=False)
reputation.from_user = self.from_user
reputation.to_user = self.to_user
2009-07-02 16:31:48 +03:00
if commit:
reputation.save()
2009-01-05 14:30:08 +02:00
return reputation
2009-01-05 14:30:08 +02:00
class MailToForm(forms.Form):
subject = forms.CharField(label=_('Subject'),
widget=forms.TextInput(attrs={'size':'75', 'maxlength':'70', 'class':'longinput'}))
body = forms.CharField(required=False, label=_('Message'),
2009-01-05 14:30:08 +02:00
widget=forms.Textarea(attrs={'rows':'10', 'cols':'75'}))
2009-01-05 14:30:08 +02:00
class ReportForm(forms.ModelForm):
2009-01-05 14:30:08 +02:00
class Meta:
model = Report
fields = ['reason', 'post']
2009-01-05 14:30:08 +02:00
def __init__(self, *args, **kwargs):
self.reported_by = kwargs.pop('reported_by', None)
self.post = kwargs.pop('post', None)
super(ReportForm, self).__init__(*args, **kwargs)
self.fields['post'].widget = forms.HiddenInput()
self.fields['post'].initial = self.post
self.fields['reason'].widget = forms.Textarea(attrs={'rows':'5', 'cols':'75', 'maxlength':'500'})
2009-07-02 16:31:48 +03:00
def save(self, commit=True):
2009-01-05 14:30:08 +02:00
report = super(ReportForm, self).save(commit=False)
2013-01-30 19:15:52 -05:00
report.created = now()
2009-01-05 14:30:08 +02:00
report.reported_by = self.reported_by
2009-07-02 16:31:48 +03:00
if commit:
report.save()
2009-01-05 14:30:08 +02:00
return report
class VotePollForm(forms.Form):
"""
Dynamic form for the poll.
"""
FORM_NAME = "VotePollForm" # used in view and template submit button
choice = forms.MultipleChoiceField()
def __init__(self, poll, *args, **kwargs):
self.poll = poll
super(VotePollForm, self).__init__(*args, **kwargs)
choices = self.poll.choices.all().values_list("id", "choice")
if self.poll.choice_count == 1:
self.fields["choice"] = forms.ChoiceField(
choices=choices, widget=forms.RadioSelect
)
else:
self.fields["choice"] = forms.MultipleChoiceField(
choices=choices, widget=forms.CheckboxSelectMultiple
)
def clean_choice(self):
ids = self.cleaned_data["choice"]
count = len(ids)
if count > self.poll.choice_count:
raise forms.ValidationError(
2013-01-14 22:57:35 -05:00
_(u'You have selected too many choices. You may only select %i.') % self.poll.choice_count
)
return ids
class PollForm(forms.ModelForm):
answers = forms.CharField(min_length=2, widget=forms.Textarea,
help_text=_("Write each answer on a new line.")
)
days = forms.IntegerField(required=False, min_value=1,
2013-01-14 22:57:35 -05:00
help_text=_("Number of days for this poll to run. Leave empty for an indefinite poll.")
)
class Meta:
model = Poll
fields = ['question', 'choice_count']
def create_poll(self):
"""
return True if one field filled with data -> the user wants to create a poll
"""
return any(self.data.get(key) for key in ('question', 'answers', 'days'))
def clean_answers(self):
# validate if there is more than whitespaces ;)
raw_answers = self.cleaned_data["answers"]
answers = [answer.strip() for answer in raw_answers.splitlines() if answer.strip()]
if len(answers) == 0:
2013-01-14 22:57:35 -05:00
raise forms.ValidationError(_(u"There is no valid answer."))
# validate length of all answers
is_max_length = max([len(answer) for answer in answers])
should_max_length = PollChoice._meta.get_field("choice").max_length
if is_max_length > should_max_length:
2013-01-14 22:57:35 -05:00
raise forms.ValidationError(_(u"One of the answers is too long."))
return answers
def save(self, post):
"""
Create poll and all answers in PollChoice model.
"""
poll = super(PollForm, self).save(commit=False)
poll.topic = post.topic
days = self.cleaned_data["days"]
if days:
2013-01-30 19:15:52 -05:00
now = now()
poll.deactivate_date = now + timedelta(days=days)
poll.save()
answers = self.cleaned_data["answers"]
for answer in answers:
PollChoice.objects.create(poll=poll, choice=answer)