def form(request): message = None if request.method == 'POST': form = UserSendActivationMailForm(request.POST, request=request) if form.is_valid(): user = form.found_user user_ban = Ban.objects.check_ban(username=user.username, email=user.email) if user_ban: return error_banned(request, user, user_ban) if user.activation == User.ACTIVATION_NONE: return redirect_message(request, Message(_("%(username)s, your account is already active.") % {'username': user.username}), 'info') if user.activation == User.ACTIVATION_ADMIN: return redirect_message(request, Message(_("%(username)s, only board administrator can activate your account.") % {'username': user.username}), 'info') user.email_user( request, 'users/activation/resend', _("Account Activation"), ) return redirect_message(request, Message(_("%(username)s, e-mail containing new activation link has been sent to %(email)s.") % {'username': user.username, 'email': user.email}), 'success') else: message = Message(form.non_field_errors()[0], 'error') else: form = UserSendActivationMailForm(request=request) return request.theme.render_to_response('resend_activation.html', { 'message': message, 'form': FormLayout(form), }, context_instance=RequestContext(request));
def thread_action_move(self): message = None if self.request.POST.get('do') == 'move': form = MoveThreadsForm(self.request.POST, request=self.request, forum=self.forum) if form.is_valid(): new_forum = form.cleaned_data['new_forum'] self.thread.move_to(new_forum) self.thread.save(force_update=True) self.thread.set_checkpoint(self.request, 'moved', forum=self.forum) self.forum.sync() self.forum.save(force_update=True) new_forum.sync() new_forum.save(force_update=True) self.request.messages.set_flash( Message( _('Thread has been moved to "%(forum)s".') % {'forum': new_forum.name}), 'success', 'threads') return None message = Message(form.non_field_errors()[0], 'error') else: form = MoveThreadsForm(request=self.request, forum=self.forum) return self.request.theme.render_to_response( '%ss/move_thread.html' % self.type_prefix, { 'type_prefix': self.type_prefix, 'message': message, 'forum': self.forum, 'parents': self.parents, 'thread': self.thread, 'form': FormLayout(form), }, context_instance=RequestContext(self.request))
def signature(request): # Intercept all requests if we can't use signature if not request.acl.usercp.can_use_signature(): return error403(request) if request.user.signature_ban: return request.theme.render_to_response('usercp/signature_banned.html', context_instance=RequestContext(request, { 'tab': 'signature', })); siggy_text = '' message = request.messages.get_message('usercp_signature') if request.method == 'POST': form = SignatureForm(request.POST, request=request, initial={'signature': request.user.signature}) if form.is_valid(): request.user.signature = form.cleaned_data['signature'] if request.user.signature: request.user.signature_preparsed = signature_markdown(request.acl, request.user.signature) else: request.user.signature_preparsed = None request.user.save(force_update=True) request.messages.set_flash(Message(_("Your signature has been changed.")), 'success', 'usercp_signature') return redirect(reverse('usercp_signature')) else: message = Message(form.non_field_errors()[0], 'error') else: form = SignatureForm(request=request, initial={'signature': request.user.signature}) return request.theme.render_to_response('usercp/signature.html', context_instance=RequestContext(request, { 'message': message, 'tab': 'signature', 'form': FormLayout(form), }));
def settings(request, group_id=None, group_slug=None): # Load groups and find selected group settings_groups = SettingsGroup.objects.all().order_by('key') if not group_id: active_group = settings_groups[0] group_id = active_group.pk else: group_id = int(group_id) for group in settings_groups: if group.pk == group_id: active_group = group break else: return error404(request, _('Requested settings group could not be found.')) # Load selected group settings and turn them into form group_settings = Setting.objects.filter(group=active_group).order_by('position') last_fieldset = (None, []) group_form = {'layout': []} for setting in group_settings: # New field subgroup? if setting.separator and last_fieldset[0] != setting.separator: if last_fieldset[0]: group_form['layout'].append(last_fieldset) last_fieldset = (_(setting.separator), []) last_fieldset[1].append(setting.pk) group_form[setting.pk] = setting.get_field() group_form['layout'].append(last_fieldset) SettingsGroupForm = type('SettingsGroupForm', (Form,), group_form) #Submit form message = request.messages.get_message('admin_settings') if request.method == 'POST': form = SettingsGroupForm(request.POST, request=request) if form.is_valid(): for setting in form.cleaned_data.keys(): request.settings[setting] = form.cleaned_data[setting] cache.delete('settings') request.messages.set_flash(Message(_('Configuration has been changed.')), 'success', 'admin_settings') return redirect(reverse('admin_settings', kwargs={ 'group_id': active_group.pk, 'group_slug': active_group.key, })) else: message = Message(form.non_field_errors()[0], 'error') else: form = SettingsGroupForm(request=request) # Display settings group form return request.theme.render_to_response('settings/settings.html', { 'message': message, 'groups': settings_groups, 'active_group': active_group, 'search_form': FormFields(SearchForm(request=request)), 'form': FormLayout(form), 'raw_form': form, }, context_instance=RequestContext(request));
def overview_graph(request, model, date_start, date_end, precision): """ Generate fancy graph for model and stuff """ if date_start == date_end: # Bad dates raise Http404() # Turn stuff into datetime's date_start = datetime.strptime(date_start, '%Y-%m-%d') date_end = datetime.strptime(date_end, '%Y-%m-%d') statistics_providers = [] models_map = {} for model_obj in models.get_models(): try: getattr(model_obj.objects, 'filter_overview') statistics_providers.append( (str(model_obj.__name__).lower(), model_obj.statistics_name)) models_map[str(model_obj.__name__).lower()] = model_obj except AttributeError: pass if not statistics_providers: # Like before, q.q on lack of models return request.theme.render_to_response( 'overview/stats/not_available.html', context_instance=RequestContext(request)) if not model in models_map or check_dates(date_start, date_end, precision): # Bad model name or graph data! raise Http404() form = GenerateStatisticsForm(provider_choices=statistics_providers, request=request, initial={ 'provider_model': model, 'date_start': date_start, 'date_end': date_end, 'stats_precision': precision }) return request.theme.render_to_response( 'overview/stats/graph.html', { 'title': models_map[model].statistics_name, 'graph': build_graph(models_map[model], date_start, date_end, precision), 'form': FormLayout(form), 'message': request.messages.get_message('admin_stats'), }, context_instance=RequestContext(request))
def post_action_move(self, ids): message = None if self.request.POST.get('do') == 'move': form = MovePostsForm(self.request.POST, request=self.request, thread=self.thread) if form.is_valid(): thread = form.cleaned_data['thread_url'] for post in self.posts: if post.pk in ids: post.move_to(thread) post.save(force_update=True) if self.thread.post_set.count() == 0: self.thread.delete() else: self.thread.sync() self.thread.save(force_update=True) thread.sync() thread.save(force_update=True) thread.forum.sync() thread.forum.save(force_update=True) if self.forum.pk != thread.forum.pk: self.forum.sync() self.forum.save(force_update=True) self.request.messages.set_flash( Message( _("Selected posts have been moved to new thread.")), 'success', 'threads') return redirect( reverse(self.type_prefix, kwargs={ 'thread': thread.pk, 'slug': thread.slug })) message = Message(form.non_field_errors()[0], 'error') else: form = MovePostsForm(request=self.request) return self.request.theme.render_to_response( '%ss/move_posts.html' % self.type_prefix, { 'type_prefix': self.type_prefix, 'message': message, 'forum': self.forum, 'parents': self.parents, 'thread': self.thread, 'posts': ids, 'form': FormLayout(form), }, context_instance=RequestContext(self.request))
def form(request): message = None if request.method == 'POST': form = UserResetPasswordForm(request.POST, request=request) if form.is_valid(): user = form.found_user user_ban = Ban.objects.check_ban(username=user.username, email=user.email) if user_ban: return error_banned(request, user, user_ban) elif user.activation != User.ACTIVATION_NONE: return redirect_message( request, Message( _("%(username)s, your account has to be activated in order for you to be able to request new password." ) % {'username': user.username}), 'info') user.token = random_string(12) user.save(force_update=True) user.email_user(request, 'users/password/confirm', _("Confirm New Password Request")) return redirect_message( request, Message( _("%(username)s, new password request confirmation has been sent to %(email)s." ) % { 'username': user.username, 'email': user.email }), 'info') else: message = Message(form.non_field_errors()[0], 'error') else: form = UserResetPasswordForm(request=request) return request.theme.render_to_response( 'reset_password.html', { 'message': message, 'form': FormLayout(form), }, context_instance=RequestContext(request))
def options(request): message = request.messages.get_message('usercp_options') if request.method == 'POST': form = UserForumOptionsForm(request.POST, request=request) if form.is_valid(): request.user.hide_activity = form.cleaned_data['hide_activity'] request.user.allow_pds = form.cleaned_data['allow_pds'] request.user.receive_newsletters = form.cleaned_data['newsletters'] request.user.timezone = form.cleaned_data['timezone'] request.user.subscribe_start = form.cleaned_data['subscribe_start'] request.user.subscribe_reply = form.cleaned_data['subscribe_reply'] request.user.save(force_update=True) request.messages.set_flash( Message(_("Forum options have been changed.")), 'success', 'usercp_options') return redirect(reverse('usercp')) message = Message(form.non_field_errors()[0], 'error') else: form = UserForumOptionsForm(request=request, initial={ 'newsletters': request.user.receive_newsletters, 'hide_activity': request.user.hide_activity, 'allow_pds': request.user.allow_pds, 'timezone': request.user.timezone, 'subscribe_start': request.user.subscribe_start, 'subscribe_reply': request.user.subscribe_reply, }) return request.theme.render_to_response('usercp/options.html', context_instance=RequestContext( request, { 'message': message, 'tab': 'options', 'form': FormLayout(form) }))
def action_move(self, ids): threads = [] for thread in self.threads: if thread.pk in ids: threads.append(thread) if self.request.POST.get('origin') == 'move_form': form = MoveThreadsForm(self.request.POST, request=self.request, forum=self.forum) if form.is_valid(): new_forum = form.cleaned_data['new_forum'] for thread in threads: thread.move_to(new_forum) thread.save(force_update=True) thread.set_checkpoint(self.request, 'moved', forum=self.forum) thread.update_current_dates() new_forum.sync() new_forum.save(force_update=True) self.forum.sync() self.forum.save(force_update=True) self.request.messages.set_flash( Message( _('Selected threads have been moved to "%(forum)s".') % {'forum': new_forum.name}), 'success', 'threads') return None self.message = Message(form.non_field_errors()[0], 'error') else: form = MoveThreadsForm(request=self.request, forum=self.forum) return self.request.theme.render_to_response( '%ss/move_threads.html' % self.type_prefix, { 'type_prefix': self.type_prefix, 'message': self.message, 'forum': self.forum, 'parents': self.parents, 'threads': threads, 'form': FormLayout(form), }, context_instance=RequestContext(self.request))
def credentials(request): message = request.messages.get_message('usercp_credentials') if request.method == 'POST': form = CredentialsChangeForm(request.POST, request=request) if form.is_valid(): token = random_string(12) request.user.email_user(request, 'users/new_credentials', _("Activate new Sign-In Credentials"), {'token': token}) request.session['new_credentials'] = { 'token': token, 'email_hash': request.user.email_hash, 'new_email': form.cleaned_data['new_email'], 'new_password': form.cleaned_data['new_password'], } if form.cleaned_data['new_email']: request.user.email = form.cleaned_data['new_email'] request.messages.set_flash( Message( _("We have sent e-mail message to your new e-mail address with link you have to click to confirm change of your sign-in credentials. This link will be valid only for duration of this session, do not sign out until you confirm change!" )), 'success', 'usercp_credentials') else: request.messages.set_flash( Message( _("We have sent e-mail message to your e-mail address with link you have to click to confirm change of your sign-in credentials. This link will be valid only for duration of this session, do not sign out until you confirm change!" )), 'success', 'usercp_credentials') return redirect(reverse('usercp_credentials')) message = Message(form.non_field_errors()[0], 'error') else: form = CredentialsChangeForm(request=request) return request.theme.render_to_response('usercp/credentials.html', context_instance=RequestContext( request, { 'message': message, 'form': FormLayout(form), 'tab': 'credentials', }))
def form(request): if request.settings['account_activation'] == 'block': return redirect_message( request, Message( _("We are sorry but we don't allow new members registrations at this time." )), 'info') message = None if request.method == 'POST': form = UserRegisterForm(request.POST, request=request) if form.is_valid(): need_activation = 0 if request.settings['account_activation'] == 'user': need_activation = User.ACTIVATION_USER if request.settings['account_activation'] == 'admin': need_activation = User.ACTIVATION_ADMIN new_user = User.objects.create_user( form.cleaned_data['username'], form.cleaned_data['email'], form.cleaned_data['password'], ip=request.session.get_ip(request), agent=request.META.get('HTTP_USER_AGENT'), activation=need_activation, request=request) if need_activation == User.ACTIVATION_NONE: # Sign in user sign_user_in(request, new_user) request.messages.set_flash( Message( _("Welcome aboard, %(username)s! Your account has been registered successfully." ) % {'username': new_user.username}), 'success') if need_activation == User.ACTIVATION_USER: # Mail user activation e-mail request.messages.set_flash( Message( _("%(username)s, your account has been registered, but you will have to activate it before you will be able to sign-in. We have sent you an e-mail with activation link." ) % {'username': new_user.username}), 'info') new_user.email_user( request, 'users/activation/user', _("Welcome aboard, %(username)s!") % {'username': new_user.username}, ) if need_activation == User.ACTIVATION_ADMIN: # Require admin activation request.messages.set_flash( Message( _("%(username)s, Your account has been registered, but you won't be able to sign in until board administrator accepts it. We'll notify when this happens. Thank you for your patience!" ) % {'username': new_user.username}), 'info') new_user.email_user( request, 'users/activation/admin', _("Welcome aboard, %(username)s!") % {'username': new_user.username}, {'password': form.cleaned_data['password']}) User.objects.resync_monitor(request.monitor) return redirect(reverse('index')) else: message = Message(form.non_field_errors()[0], 'error') if request.settings['registrations_jams']: SignInAttempt.objects.register_attempt( request.session.get_ip(request)) # Have we jammed our account? if SignInAttempt.objects.is_jammed( request.settings, request.session.get_ip(request)): request.jam.expires = timezone.now() return redirect(reverse('register')) else: form = UserRegisterForm(request=request) return request.theme.render_to_response( 'register.html', { 'message': message, 'form': FormLayout(form), 'hide_signin': True, }, context_instance=RequestContext(request))
def action_merge(self, ids): if len(ids) < 2: raise ValidationError( _("You have to pick two or more threads to merge.")) threads = [] for thread in self.threads: if thread.pk in ids: threads.append(thread) if self.request.POST.get('origin') == 'merge_form': form = MergeThreadsForm(self.request.POST, request=self.request, threads=threads) if form.is_valid(): new_thread = Thread.objects.create( forum=form.cleaned_data['new_forum'], name=form.cleaned_data['thread_name'], slug=slugify(form.cleaned_data['thread_name']), start=timezone.now(), last=timezone.now()) merged = [] for thread in reversed(threads): merged.append(thread.pk) thread.merge_with(new_thread) Thread.objects.filter(id__in=merged).delete() new_thread.sync() new_thread.save(force_update=True) new_thread.update_current_dates() self.forum.sync() self.forum.save(force_update=True) if form.cleaned_data['new_forum'].pk != self.forum.pk: form.cleaned_data['new_forum'].sync() form.cleaned_data['new_forum'].save(force_update=True) self.request.messages.set_flash( Message( _('Selected threads have been merged into new one.')), 'success', 'threads') return None self.message = Message(form.non_field_errors()[0], 'error') else: form = MergeThreadsForm(request=self.request, threads=threads) warning = None lookback = threads[0].last_post_id for thread in threads[1:]: if thread.start_post_id < lookback: warning = Message( _("Warning: Posting times in one or more of threads that you are going to merge are overlapping. This may result in disturbed flow of merged thread." ), 'warning') break else: lookback = thread.last_post_id return self.request.theme.render_to_response( ('%ss/merge.html' % self.type_prefix), { 'type_prefix': self.type_prefix, 'message': self.message, 'warning': warning, 'forum': self.forum, 'parents': self.parents, 'threads': threads, 'form': FormLayout(form), }, context_instance=RequestContext(self.request))
def overview_stats(request): """ Allow admins to generate fancy statistic graphs for different models """ statistics_providers = [] models_map = {} for model in models.get_models(): try: getattr(model.objects, 'filter_overview') statistics_providers.append( (str(model.__name__).lower(), model.statistics_name)) models_map[str(model.__name__).lower()] = model except AttributeError: pass if not statistics_providers: """ Something went FUBAR - Misago ships with some stats providers out of box If those providers cant be found, this means Misago filesystem is corrupted """ return request.theme.render_to_response( 'overview/stats/not_available.html', context_instance=RequestContext(request)) message = None if request.method == 'POST': form = GenerateStatisticsForm(request.POST, provider_choices=statistics_providers, request=request) if form.is_valid(): date_start = form.cleaned_data['date_start'] date_end = form.cleaned_data['date_end'] if date_start > date_end: # Reverse dates if start is after end date_temp = date_end date_end = date_start date_start = date_temp # Assert that dates are correct if date_end == date_start: message = BasicMessage(_('Start and end date are same'), type='error') elif check_dates(date_start, date_end, form.cleaned_data['stats_precision']): message = check_dates(date_start, date_end, form.cleaned_data['stats_precision']) else: request.messages.set_flash( BasicMessage(_('Statistical report has been created.')), 'success', 'admin_stats') return redirect( reverse('admin_overview_graph', kwargs={ 'model': form.cleaned_data['provider_model'], 'date_start': date_start.strftime('%Y-%m-%d'), 'date_end': date_end.strftime('%Y-%m-%d'), 'precision': form.cleaned_data['stats_precision'] })) else: message = Message(request, form.non_field_errors()[0]) message.type = 'error' else: form = GenerateStatisticsForm(provider_choices=statistics_providers, request=request) return request.theme.render_to_response( 'overview/stats/form.html', { 'form': FormLayout(form), 'message': message, }, context_instance=RequestContext(request))
def upload(request): if not 'upload' in request.settings.avatars_types: return error404(request) message = request.messages.get_message('usercp_avatar') if request.method == 'POST': form = UploadAvatarForm(request.POST, request.FILES, request=request) if form.is_valid(): request.user.delete_avatar_temp() image = form.cleaned_data['avatar_upload'] image_name, image_extension = path(smart_str(image.name.lower())).splitext() image_name = '%s_tmp_%s%s' % (request.user.pk, random_string(8), image_extension) image_path = settings.MEDIA_ROOT + 'avatars/' + image_name request.user.avatar_temp = image_name with open(image_path, 'wb+') as destination: for chunk in image.chunks(): destination.write(chunk) request.user.save() try: if is_zipfile(image_path): # Composite file upload raise ValidationError() image = Image.open(image_path) if not image.format in ['GIF', 'PNG', 'JPEG']: raise ValidationError() image.seek(0) image.save(image_path) if request.POST.get('js_check'): return redirect(reverse('usercp_avatar_upload_crop')) # Redirect to crop page didnt happen, handle avatar with old school hollywood way image_path = settings.MEDIA_ROOT + 'avatars/' source = Image.open(image_path + request.user.avatar_temp) image_name, image_extension = path(request.user.avatar_temp).splitext() image_name = '%s_%s%s' % (request.user.pk, random_string(8), image_extension) resizeimage(source, settings.AVATAR_SIZES[0], image_path + image_name, info=source.info, format=source.format) for size in settings.AVATAR_SIZES[1:]: resizeimage(source, size, image_path + str(size) + '_' + image_name, info=source.info, format=source.format) # Update user model one more time request.user.delete_avatar_image() request.user.delete_avatar_original() request.user.avatar_type = 'upload' request.user.avatar_original = '%s_org_%s%s' % (request.user.pk, random_string(8), image_extension) source.save(image_path + request.user.avatar_original) request.user.delete_avatar_temp() request.user.avatar_image = image_name request.user.save(force_update=True) # Set message and adios! request.messages.set_flash(Message(_("Your avatar has changed.")), 'success', 'usercp_avatar') return redirect(reverse('usercp_avatar')) except ValidationError: request.user.delete_avatar() request.user.default_avatar(request.settings) message = Message(_("Only gif, jpeg and png files are allowed for member avatars."), 'error') else: message = Message(form.non_field_errors()[0], 'error') else: form = UploadAvatarForm(request=request) return request.theme.render_to_response('usercp/avatar_upload.html', context_instance=RequestContext(request, { 'message': message, 'form': FormLayout(form), 'tab': 'avatar', }));
def username(request): if not request.acl.usercp.show_username_change(): return error404(request) changes_left = request.acl.usercp.changes_left(request.user) next_change = None if request.acl.usercp.changes_expire() and not changes_left: next_change = request.user.namechanges.filter( date__gte=timezone.now() - timedelta(days=request.acl.usercp.acl['changes_expire']), ).order_by('-date')[0] next_change = next_change.date + timedelta( days=request.acl.usercp.acl['changes_expire']) message = request.messages.get_message('usercp_username') if request.method == 'POST': if not changes_left: message = Message( _("You have exceeded the maximum number of name changes."), 'error') form = UsernameChangeForm(request=request) else: org_username = request.user.username form = UsernameChangeForm(request.POST, request=request) if form.is_valid(): request.user.set_username(form.cleaned_data['username']) request.user.save(force_update=True) request.user.sync_username() request.user.namechanges.create(date=timezone.now(), old_username=org_username) request.messages.set_flash( Message(_("Your username has been changed.")), 'success', 'usercp_username') # Alert followers of namechange alert_time = timezone.now() bulk_alerts = [] alerted_users = [] for follower in request.user.follows_set.iterator(): alerted_users.append(follower.pk) alert = Alert( user=follower, message=ugettext_lazy( "User that you are following, %(username)s, has changed his name to %(newname)s" ).message, date=alert_time) alert.strong('username', org_username) alert.profile('newname', request.user) alert.hydrate() bulk_alerts.append(alert) if bulk_alerts: Alert.objects.bulk_create(bulk_alerts) User.objects.filter(id__in=alerted_users).update( alerts=F('alerts') + 1) # Hop back return redirect(reverse('usercp_username')) message = Message(form.non_field_errors()[0], 'error') else: form = UsernameChangeForm(request=request) return request.theme.render_to_response( 'usercp/username.html', context_instance=RequestContext( request, { 'message': message, 'changes_left': changes_left, 'form': FormLayout(form), 'next_change': next_change, 'changes_history': request.user.namechanges.order_by('-date')[:10], 'tab': 'username', }))
def post_action_split(self, ids): for id in ids: if id == self.thread.start_post_id: raise forms.ValidationError( _("You cannot split first post from thread.")) message = None if self.request.POST.get('do') == 'split': form = SplitThreadForm(self.request.POST, request=self.request) if form.is_valid(): new_thread = Thread() new_thread.forum = form.cleaned_data['thread_forum'] new_thread.name = form.cleaned_data['thread_name'] new_thread.slug = slugify(form.cleaned_data['thread_name']) new_thread.start = timezone.now() new_thread.last = timezone.now() new_thread.start_poster_name = 'n' new_thread.start_poster_slug = 'n' new_thread.last_poster_name = 'n' new_thread.last_poster_slug = 'n' new_thread.save(force_insert=True) for post in self.posts: if post.pk in ids: post.move_to(new_thread) post.save(force_update=True) new_thread.sync() new_thread.save(force_update=True) self.thread.sync() self.thread.save(force_update=True) self.forum.sync() self.forum.save(force_update=True) if new_thread.forum != self.forum: new_thread.forum.sync() new_thread.forum.save(force_update=True) self.request.messages.set_flash( Message( _("Selected posts have been split to new thread.")), 'success', 'threads') return redirect( reverse(self.type_prefix, kwargs={ 'thread': new_thread.pk, 'slug': new_thread.slug })) message = Message(form.non_field_errors()[0], 'error') else: form = SplitThreadForm(request=self.request, initial={ 'thread_name': _('[Split] %s') % self.thread.name, 'thread_forum': self.forum, }) return self.request.theme.render_to_response( '%ss/split.html' % self.type_prefix, { 'type_prefix': self.type_prefix, 'message': message, 'forum': self.forum, 'parents': self.parents, 'thread': self.thread, 'posts': ids, 'form': FormLayout(form), }, context_instance=RequestContext(self.request))
def __call__(self, request, page=0): """ Use widget as view """ self.request = request # Get basic list items items_total = self.get_items() # Set extra filters? try: items_total = self.select_items(items_total).count() except AttributeError: items_total = items_total.count() # Set sorting and paginating sorting_method = self.get_sorting() try: paginating_method = self.get_pagination(items_total, page) except Http404: return redirect(self.get_url()) # List items items = self.get_items() if not request.session.get(self.get_token('filter')): items = items.all() # Set extra filters? try: items = self.select_items(items) except AttributeError: pass # Sort them items = self.sort_items(items, sorting_method) # Set pagination if self.pagination: items = items[paginating_method['start']:paginating_method['stop']] # Prefetch related? try: items = self.prefetch_related(items) except AttributeError: pass # Default message message = None # See if we should make and handle search form search_form = None SearchForm = self.get_search_form() if SearchForm: if request.method == 'POST': # New search if request.POST.get('origin') == 'search': search_form = SearchForm(request.POST, request=request) if search_form.is_valid(): search_criteria = {} for field, criteria in search_form.cleaned_data.items( ): if len(criteria) > 0: search_criteria[field] = criteria if not search_criteria: message = Message( _("No search criteria have been defined.")) else: request.session[self.get_token( 'filter')] = search_criteria return redirect(self.get_url()) else: message = Message(_("Search form contains errors.")) message.type = 'error' else: search_form = SearchForm(request=request) # Kill search if request.POST.get( 'origin' ) == 'clear' and self.is_filtering and request.csrf.request_secure( request): request.session[self.get_token('filter')] = None request.messages.set_flash( Message(_("Search criteria have been cleared.")), 'info', self.admin.id) return redirect(self.get_url()) else: if self.is_filtering: search_form = SearchForm(request=request, initial=request.session.get( self.get_token('filter'))) else: search_form = SearchForm(request=request) # See if we sould make and handle tab form table_form = None TableForm = self.get_table_form(items) if TableForm: if request.method == 'POST' and request.POST.get( 'origin') == 'table': table_form = TableForm(request.POST, request=request) if table_form.is_valid(): message, redirect_url = self.table_action( items, table_form.cleaned_data) if redirect_url: request.messages.set_flash(message, message.type, self.admin.id) return redirect(redirect_url) else: message = Message(table_form.non_field_errors()[0], 'error') else: table_form = TableForm(request=request) # See if we should make and handle list form list_form = None ListForm = self.get_actions_form(items) if ListForm: if request.method == 'POST' and request.POST.get( 'origin') == 'list': list_form = ListForm(request.POST, request=request) if list_form.is_valid(): try: form_action = getattr( self, 'action_' + list_form.cleaned_data['list_action']) message, redirect_url = form_action( items, [ int(x) for x in list_form.cleaned_data['list_items'] ]) if redirect_url: request.messages.set_flash(message, message.type, self.admin.id) return redirect(redirect_url) except AttributeError: message = Message(_("Action requested is incorrect.")) else: if 'list_items' in list_form.errors: message = Message(self.nothing_checked_message) elif 'list_action' in list_form.errors: message = Message(_("Action requested is incorrect.")) else: message = Message(list_form.non_field_errors()[0]) message.type = 'error' else: list_form = ListForm(request=request) # Little hax to keep counters correct items_shown = len(items) if items_total < items_shown: items_total = items_shown # Render list return request.theme.render_to_response( self.get_template(), self.add_template_variables({ 'admin': self.admin, 'action': self, 'request': request, 'url': self.get_url(), 'messages_log': request.messages.get_messages(self.admin.id), 'message': message, 'sorting': self.sortables, 'sorting_method': sorting_method, 'pagination': paginating_method, 'list_form': FormLayout(list_form) if list_form else None, 'search_form': FormLayout(search_form) if search_form else None, 'table_form': FormFields(table_form).fields if table_form else None, 'items': items, 'items_total': items_total, 'items_shown': items_shown, }), context_instance=RequestContext(request))
def __call__(self, request, target=None, slug=None): self.request = request # Fetch target? model = None if target: model = self.get_and_validate_target(target) self.original_name = self.get_target_name(model) if not model: return redirect(self.get_fallback_url()) original_model = model # Get form type to instantiate FormType = self.get_form(model) #Submit form message = None if request.method == 'POST': form = self.get_form_instance(FormType, model, self.get_initial_data(model), True) if form.is_valid(): try: model, message = self.submit_form(form, model) if message.type != 'error': request.messages.set_flash(message, message.type, self.admin.id) # Redirect back to right page try: if 'save_new' in request.POST and self.get_new_url: return redirect(self.get_new_url(model)) except AttributeError: pass try: if 'save_edit' in request.POST and self.get_edit_url: return redirect(self.get_edit_url(model)) except AttributeError: pass try: if self.get_submit_url: return redirect(self.get_submit_url(model)) except AttributeError: pass return redirect(self.get_fallback_url()) except ValidationError as e: message = Message(e.messages[0], 'error') else: message = Message(form.non_field_errors()[0], 'error') else: form = self.get_form_instance(FormType, model, self.get_initial_data(model)) # Render form return request.theme.render_to_response( self.get_template(), self.add_template_variables({ 'admin': self.admin, 'action': self, 'request': request, 'url': self.get_url(model), 'fallback': self.get_fallback_url(), 'messages_log': request.messages.get_messages(self.admin.id), 'message': message, 'tabbed': self.tabbed, 'target': self.get_target_name(original_model), 'target_model': original_model, 'form': FormLayout(form, self.get_layout(form, target)), }), context_instance=RequestContext(request))
def __call__(self, request, **kwargs): self.request = request self.kwargs = kwargs self.forum = None self.thread = None self.quote = None self.post = None self.parents = [] self.message = request.messages.get_message('threads') post_preview = '' form = None try: self._type_available() self._set_context() self.check_forum_type() self._check_permissions() request.block_flood_requests = self.block_flood_requests if request.method == 'POST': # Create correct form instance if self.allow_quick_reply and 'quick_reply' in request.POST: form = QuickReplyForm(request.POST, request=request) if not form or 'preview' in request.POST or not form.is_valid( ): # Override "quick reply" form with full one try: form = self.form_type(request.POST, request.FILE, request=request, forum=self.forum, thread=self.thread) except AttributeError: form = self.form_type(request.POST, request=request, forum=self.forum, thread=self.thread) # Handle specific submit if 'preview' in request.POST: form.empty_errors() if form['post'].value(): md, post_preview = post_markdown(form['post'].value()) else: md, post_preview = None, None else: if form.is_valid(): self.post_form(form) self.watch_thread() self.after_form(form) self.notify_users() return self.response() else: self.message = Message(form.non_field_errors()[0], 'error') else: form = self.form_type(request=request, forum=self.forum, thread=self.thread, initial=self.form_initial_data()) except (Forum.DoesNotExist, Thread.DoesNotExist, Post.DoesNotExist): return error404(request) except ACLError403 as e: return error403(request, unicode(e)) except ACLError404 as e: return error404(request, unicode(e)) return request.theme.render_to_response( ('%ss/posting.html' % self.type_prefix), self.template_vars({ 'type_prefix': self.type_prefix, 'action': self.action, 'message': self.message, 'forum': self.forum, 'thread': self.thread, 'quote': self.quote, 'post': self.post, 'parents': self.parents, 'preview': post_preview, 'form': FormLayout(form), 'emojis': emojis(), }), context_instance=RequestContext(request))
def signin(request): message = request.messages.get_message('security') bad_password = False not_active = False banned_account = False if request.method == 'POST': form = SignInForm(request.POST, show_remember_me=not request.firewall.admin and request.settings['remember_me_allow'], request=request) if form.is_valid(): try: # Configure correct auth and redirect links if request.firewall.admin: auth_method = auth_admin success_redirect = reverse(site.get_admin_index()) else: auth_method = auth_forum success_redirect = reverse('index') # Authenticate user user = auth_method( request, form.cleaned_data['user_email'], form.cleaned_data['user_password'], ) sign_user_in(request, user) remember_me_token = False if not request.firewall.admin and request.settings[ 'remember_me_allow'] and form.cleaned_data[ 'user_remember_me']: remember_me_token = random_string(42) remember_me = Token( id=remember_me_token, user=user, created=timezone.now(), accessed=timezone.now(), ) remember_me.save() if remember_me_token: request.cookiejar.set('TOKEN', remember_me_token, True) request.messages.set_flash( Message( _("Welcome back, %(username)s!") % {'username': user.username}), 'success', 'security') return redirect(success_redirect) except AuthException as e: message = Message(e.error, 'error') bad_password = e.password banned_account = e.ban not_active = e.activation # If not in Admin, register failed attempt if not request.firewall.admin and e.type == auth.CREDENTIALS: SignInAttempt.objects.register_attempt( request.session.get_ip(request)) # Have we jammed our account? if SignInAttempt.objects.is_jammed( request.settings, request.session.get_ip(request)): request.jam.expires = timezone.now() return redirect(reverse('sign_in')) else: message = Message(form.non_field_errors()[0], 'error') else: form = SignInForm(show_remember_me=not request.firewall.admin and request.settings['remember_me_allow'], request=request) return request.theme.render_to_response( 'signin.html', { 'message': message, 'bad_password': bad_password, 'banned_account': banned_account, 'not_active': not_active, 'form': FormLayout(form), 'hide_signin': True, }, context_instance=RequestContext(request))