def delete(request): profile = request.user.get_profile() current_projects = profile.get_current_projects() pending_projects = [] for project in current_projects['organizing']: if not project.archived and project.organizers().count() == 1: pending_projects.append(project) msg = _('You are the only organizer of %s active ') msg += _('study groups, courses, ...') if request.method == 'POST': if pending_projects: messages.error(request, msg % len(pending_projects)) return HttpResponseRedirect(reverse('preferences_delete')) profile.deleted = True profile.user.is_active = False profile.save() profile.user.save() # logout the user. for s in Session.objects.all(): if s.get_decoded().get('_auth_user_id') == profile.user.id: s.delete() return HttpResponseRedirect(reverse('users_logout')) return render_to_response('users/settings_delete.html', {'pending_projects': pending_projects, 'delete_tab': True}, context_instance=RequestContext(request))
def projects_reviews_list(request, toggled_under_review=False, toggled_accepted=False): reviews = Review.objects.values('project_id') accepted_reviews = Review.objects.filter( accepted=True).values('project_id') projects_pending = Project.objects.exclude( id__in=reviews) projects_under_review = Project.objects.filter( id__in=reviews).exclude(id__in=accepted_reviews) projects_accepted = Project.objects.filter( id__in=accepted_reviews) context = { 'toggled_under_review': toggled_under_review, 'toggled_accepted': toggled_accepted, 'pending_page_url': reverse('projects_pending_review'), 'under_review_page_url': reverse('projects_under_review'), 'accepted_page_url': reverse('accepted_projects') } context.update(get_pagination_context(request, projects_pending, 24, prefix='pending_')) context.update(get_pagination_context(request, projects_under_review, 24, prefix='under_review_')) context.update(get_pagination_context(request, projects_accepted, 24, prefix='accepted_')) return render_to_response('reviews/projects_reviews_list.html', context, context_instance=RequestContext(request))
def show_page(request, slug, page_slug): page = get_object_or_404(Page, project__slug=slug, slug=page_slug) can_edit = page.can_edit(request.user) if page.deleted: messages.error(request, _('This task was deleted.')) if can_edit: return http.HttpResponseRedirect(reverse('page_history', kwargs={'slug': page.project.slug, 'page_slug': page.slug})) else: return http.HttpResponseRedirect(page.project.get_absolute_url()) new_comment_url = reverse('page_comment', kwargs=dict( scope_app_label='projects', scope_model='project', scope_pk=page.project.id, page_app_label='content', page_model='page', page_pk=page.id)) first_level_comments = page.first_level_comments() context = { 'page': page, 'project': page.project, 'can_edit': can_edit, 'can_comment': page.can_comment(request.user), 'new_comment_url': new_comment_url, } context.update(get_pagination_context(request, first_level_comments)) return render_to_response('content/page.html', context, context_instance=RequestContext(request))
def show_page(request, slug, page_slug): page = get_object_or_404(Page, project__slug=slug, slug=page_slug) is_challenge = (page.project.category == Project.CHALLENGE) if is_challenge and not page.listed: msg = _("This page is not accesible on a %s.") return http.HttpResponseForbidden(msg % page.project.kind.lower()) can_edit = page.can_edit(request.user) if page.deleted: messages.error(request, _('This task was deleted.')) if can_edit: return http.HttpResponseRedirect(reverse('page_history', kwargs={'slug': page.project.slug, 'page_slug': page.slug})) else: return http.HttpResponseRedirect(page.project.get_absolute_url()) new_comment_url = reverse('page_comment', kwargs=dict( scope_app_label='projects', scope_model='project', scope_pk=page.project.id, page_app_label='content', page_model='page', page_pk=page.id)) first_level_comments = page.first_level_comments() all_listed_pages = page.project.pages.filter(deleted=False, listed=True).order_by('index') context = { 'page': page, 'project': page.project, 'can_edit': can_edit, 'can_comment': page.can_comment(request.user), 'new_comment_url': new_comment_url, 'is_challenge': is_challenge, 'all_listed_pages': all_listed_pages, } context.update(get_pagination_context(request, first_level_comments)) context.update(get_google_tracking_context(page.project)) return render_to_response('content/page.html', context, context_instance=RequestContext(request))
def create_project_status(request, project_id): if request.method != 'POST' or 'status' not in request.POST: return HttpResponseRedirect(reverse('dashboard_index')) project = get_object_or_404(Project, id=project_id) profile = request.user.get_profile() if profile != project.created_by and not profile.user.is_superuser \ and not project.participants().filter(user=profile).exists(): return HttpResponseRedirect(reverse('dashboard_index')) if profile == project.created_by or profile.user.is_superuser: form = ImportantStatusForm(data=request.POST) else: form = StatusForm(data=request.POST) if form.is_valid(): status = form.save(commit=False) status.author = request.user.get_profile() status.project = project status.save() log.debug("Saved status by user (%d) to study group (%d): %s" % ( profile.id, project.id, status)) else: log.debug("form error: %s" % (str(form.errors))) messages.error(request, _('There was an error posting ' 'your status update')) return HttpResponseRedirect( reverse('projects_show', kwargs=dict(slug=project.slug)))
def profile_create(request): try: request.user.get_profile() return http.HttpResponseRedirect(reverse('dashboard')) except UserProfile.DoesNotExist: pass form = forms.CreateProfileForm(request.POST) if form.is_valid(): profile = form.save(commit=False) profile.user = request.user profile.id = profile.user.id profile.user.email = profile.email profile.user.save() profile.confirmation_code = profile.generate_confirmation_code() profile.save() path = reverse('users_confirm_registration', kwargs={ 'username': profile.username, 'token': profile.confirmation_code, }) url = request.build_absolute_uri(path) profile.email_confirmation_code(url) msg = _('Thanks! We have sent an email to %s with ' 'instructions for completing your ' 'registration.') % profile.email messages.info(request, msg) return http.HttpResponseRedirect(reverse('dashboard')) else: messages.error(request, _('There are errors in this form. Please ' 'correct them and resubmit.')) return render_to_response('dashboard/setup_profile.html', { 'form': form, 'domain': Site.objects.get_current().domain, }, context_instance=RequestContext(request))
def profile_create(request): try: request.user.get_profile() return http.HttpResponseRedirect(reverse("dashboard")) except UserProfile.DoesNotExist: pass form = forms.CreateProfileForm(request.POST) if form.is_valid(): profile = form.save(commit=False) profile.user = request.user profile.id = profile.user.id profile.user.email = profile.email profile.user.save() profile.confirmation_code = profile.generate_confirmation_code() profile.save() path = reverse( "users_confirm_registration", kwargs={"username": profile.username, "token": profile.confirmation_code} ) url = request.build_absolute_uri(path) profile.email_confirmation_code(url) auth.logout(request) msg = _( "Thanks! We have sent an email to {0} with " "instructions for completing your " "registration." ).format(profile.email) messages.info(request, msg) return http.HttpResponseRedirect(reverse("splash")) else: messages.error(request, _("There are errors in this form. Please " "correct them and resubmit.")) return render_to_response( "dashboard/setup_profile.html", {"form": form, "domain": Site.objects.get_current().domain}, context_instance=RequestContext(request), )
def serialize(inbox, sent_view=False): """Serialize messages for xhr.""" data = [] for msg in inbox: sender = msg.sender if sent_view: sender = msg.recipient img = sender.get_profile().image_or_default() if isinstance(img, ImageFieldFile): img = img.name serialized = { 'abuse_url': reverse('drumbeat_abuse', kwargs=dict( model='message', app_label='messages', pk=msg.id)), 'reply_url': reverse('drumbeatmail_reply', kwargs=dict( message=msg.id)), 'sender_url': sender.get_profile().get_absolute_url(), 'sender_img': img, 'sender_name': sender.get_profile().display_name, 'subject': msg.subject, 'body': msg.body, 'sent_at': msg.sent_at.strftime('%b. %d, %Y, %I:%M %p').replace( 'PM', 'p.m.').replace('AM', 'a.m.'), } if sent_view: del serialized['abuse_url'] del serialized['reply_url'] data.append(serialized) return simplejson.dumps(data)
def _get_redirect_url(request): url = request.session.get(REDIRECT_FIELD_NAME, None) if url == reverse("splash"): url = reverse("dashboard") if url: del request.session[REDIRECT_FIELD_NAME] if not url.startswith("/") and "://" not in url: url = "/%s" % (url,) return url
def _get_redirect_url(request): url = request.session.get(REDIRECT_FIELD_NAME, None) if url == reverse('splash'): url = reverse('dashboard') if url: del request.session[REDIRECT_FIELD_NAME] if not url.startswith('/'): url = '/%s' % (url,) return url
def delete(request): return HttpResponseRedirect(reverse('preferences_settings')) if request.method == 'POST': profile = request.user.get_profile() profile.user.delete() profile.delete() return HttpResponseRedirect(reverse('users_logout')) return render_to_response('users/settings_delete.html', { }, context_instance=RequestContext(request))
def redirect_urls(request): path = urlquote(request.get_full_path()) login_url = '%s?%s=%s' % ( reverse('users_login'), REDIRECT_FIELD_NAME, path) register_url = '%s?%s=%s' % ( reverse('users_register'), REDIRECT_FIELD_NAME, path) return { 'login_with_redirect_url': login_url, 'register_with_redirect_url': register_url, }
def _get_redirect_url(request): url = request.session.get(REDIRECT_FIELD_NAME, reverse('dashboard')) if not url or url == reverse('splash'): url = reverse('dashboard') if url: if REDIRECT_FIELD_NAME in request.session: del request.session[REDIRECT_FIELD_NAME] if not url.startswith('/') and '://' not in url: url = '/%s' % (url,) return url
def confirm_registration(request, token, username): """Confirm a users registration.""" profile = get_object_or_404(UserProfile, username=username) if profile.confirmation_code != token: messages.error(request, _("Hmm, that doesn't look like the correct confirmation code")) log.info("Account confirmation failed for %s" % (profile,)) return http.HttpResponseRedirect(reverse("users_login")) profile.confirmation_code = "" profile.save() messages.success(request, _("Success! You have verified your account. " "You may now sign in.")) return http.HttpResponseRedirect(reverse("users_login"))
def create(request): user = request.user.get_profile() school = None if request.method == 'POST': form = project_forms.CreateProjectForm(request.POST) if form.is_valid(): project = form.save() act = Activity(actor=user, verb='http://activitystrea.ms/schema/1.0/post', project=project, target_project=project) act.save() participation = Participation(project= project, user=user, organizing=True) participation.save() new_rel = Relationship(source=user, target_project=project) try: new_rel.save() except IntegrityError: pass detailed_description_content = render_to_string( "projects/detailed_description_initial_content.html", {}) detailed_description = Page(title=_('Full Description'), slug='full-description', content=detailed_description_content, listed=False, author_id=user.id, project_id=project.id) detailed_description.save() project.detailed_description_id = detailed_description.id sign_up_content = render_to_string("projects/sign_up_initial_content.html", {}) sign_up = Page(title=_('Sign-Up'), slug='sign-up', content=sign_up_content, listed=False, editable=False, author_id=user.id, project_id=project.id) sign_up.save() project.sign_up_id = sign_up.id project.save() messages.success(request, _('The study group has been created.')) return http.HttpResponseRedirect(reverse('projects_show', kwargs={ 'slug': project.slug, })) else: messages.error(request, _("There was a problem creating the study group.")) else: if 'school' in request.GET: try: school = School.objects.get(slug=request.GET['school']) form = project_forms.CreateProjectForm(initial={'school': school}) except School.DoesNotExist: return http.HttpResponseRedirect(reverse('projects_create')) else: form = project_forms.CreateProjectForm() return render_to_response('projects/project_edit_summary.html', { 'form': form, 'new_tab': True, 'school': school, }, context_instance=RequestContext(request))
def confirm_resend(request, username): """Resend a confirmation code.""" profile = get_object_or_404(UserProfile, username=username) if profile.confirmation_code: path = reverse( "users_confirm_registration", kwargs={"username": profile.username, "token": profile.confirmation_code} ) url = request.build_absolute_uri(path) profile.email_confirmation_code(url) msg = _("A confirmation code has been sent to the email address " "associated with your account.") messages.info(request, msg) return http.HttpResponseRedirect(reverse("users_login"))
def create(request): if request.method != "POST" or "status" not in request.POST: return HttpResponseRedirect(reverse("dashboard")) form = StatusForm(data=request.POST) if form.is_valid(): status = form.save(commit=False) status.author = request.user.get_profile() status.save() else: log.debug("form error: %s" % (str(form.errors))) messages.error(request, _("There was an error posting " "your status update")) return HttpResponseRedirect(reverse("dashboard"))
def confirm_registration(request, token, username): """Confirm a users registration.""" profile = get_object_or_404(UserProfile, username=username) if profile.confirmation_code != token: messages.error( request, _('Hmm, that doesn\'t look like the correct confirmation code')) log.info('Email address confirmation failed for %s' % (profile,)) return http.HttpResponseRedirect(reverse('users_login')) profile.confirmation_code = '' profile.save() messages.success(request, _('Success! You have verified your email address.')) return http.HttpResponseRedirect(reverse('dashboard'))
def profile_edit_image(request): profile = request.user.get_profile() if request.method == "POST": form = forms.ProfileImageForm(request.POST, request.FILES, instance=profile) if form.is_valid(): messages.success(request, _("Profile image updated")) form.save() return http.HttpResponseRedirect(reverse("users_profile_edit_image")) else: messages.error(request, _("There was an error uploading " "your image.")) else: return http.HttpResponseRedirect(reverse("users_profile_edit"))
def render(self, name, value, attrs={}): if value is None: value = '' # Not charing locale info between different instance of the form. config = self.config.copy() config['language'] = get_language() final_attrs = self.build_attrs(attrs, name=name) self.config['filebrowserUploadUrl'] = reverse('ckeditor_upload') self.config['filebrowserBrowseUrl'] = reverse('ckeditor_browse') return mark_safe(u'''<textarea%s>%s</textarea> <script type="text/javascript"> CKEDITOR.replace("%s", %s); </script>''' % (flatatt(final_attrs), conditional_escape(force_unicode(value)), final_attrs['id'], json_encode(config)))
def process_request(self, request): if request.user.is_authenticated(): try: profile = request.user.get_profile() except UserProfile.DoesNotExist: dashboard_url = reverse("dashboard_index") profile_create_url = reverse("users_profile_create") logout_url = reverse("users_logout") if request.path in (dashboard_url, profile_create_url, logout_url): return None for prefix in settings.NO_PROFILE_URLS: if request.path.startswith(prefix): return None return HttpResponseRedirect(dashboard_url)
def learn_default(tag=None, school=None): """ return the default URL for the learn page """ learn_url = reverse('learn_featured', kwargs={'feature':'community'}) params = [] if school: learn_url = reverse('learn_schools', kwargs={'school_slug':school.slug}) if tag: learn_url = reverse('learn_all') params += ['filter_tags=%s' % tag.name] if len(params): learn_url += "?" learn_url += "&".join(params) return learn_url
def confirm_resend(request): """Resend a confirmation code.""" profile = request.user.get_profile() if profile.confirmation_code: path = reverse('users_confirm_registration', kwargs={ 'username': profile.username, 'token': profile.confirmation_code, }) url = request.build_absolute_uri(path) profile.email_confirmation_code(url, new_user=False) msg = _('A link to confirm your email address was sent ' 'to %s.') messages.info(request, msg % profile.email) return http.HttpResponseRedirect(reverse('preferences_email'))
def submissions_list(request, toggled_awards=False, toggled_mine=False): pending_page_url = reverse('submissions_list') awarded_page_url = reverse('awarded_submissions_list') mine_page_url = reverse('mine_submissions_list') context = { 'badge': None, 'toggled_awards': toggled_awards, 'toggled_mine': toggled_mine, 'pending_page_url': pending_page_url, 'awarded_page_url': awarded_page_url, 'mine_page_url': mine_page_url, } return render_to_response('badges/submissions_list.html', context, context_instance=RequestContext(request))
def register(request): """Present user registration form and handle registrations.""" request = _process_redirect(request) if request.method == 'POST': form = forms.RegisterForm(data=request.POST) if form.is_valid(): django_user = form.save(commit=False) user = create_profile(django_user) user.set_password(form.cleaned_data['password']) user.generate_confirmation_code() user.full_name = form.cleaned_data['full_name'] user.preflang = form.cleaned_data['preflang'] user.save() log.info(u"Registered new account for user (%s)", user) messages.success(request, _('Congratulations! Your user account ' 'was successfully created.')) path = reverse('users_confirm_registration', kwargs={ 'username': user.username, 'token': user.confirmation_code, }) url = request.build_absolute_uri(path) user.email_confirmation_code(url) msg = _('Thanks! We have sent an email to {0} with ' 'instructions for completing your ' 'registration.').format(user.email) messages.info(request, msg) response = login(request) request.session['send_registration_event'] = True return response else: messages.error(request, _('There are errors in this form. Please ' 'correct them and resubmit.')) else: form = forms.RegisterForm() redirect_field_value = request.session.get( REDIRECT_FIELD_NAME, reverse('dashboard')) return render_to_response('users/register.html', { 'form': form, 'domain': Site.objects.get_current().domain, 'redirect_field_name': REDIRECT_FIELD_NAME, 'redirect_field_value': urllib2.quote(redirect_field_value), }, context_instance=RequestContext(request))
def _populate_course_context( request, course_id, context ): course_uri = course_model.course_id2uri(course_id) course = _get_course_or_404(course_uri) course['author'] = course['author_uri'].strip('/').split('/')[-1] context['course'] = course context['course_url'] = reverse('courses_show', kwargs={'course_id': course['id'], 'slug': course['slug']} ) if 'image_uri' in course: context['course']['image'] = media_model.get_image(course['image_uri']) #NOTE if performance becomes a problem dont fetch cohort cohort = course_model.get_course_cohort(course_uri) context['cohort'] = cohort user_uri = u"/uri/user/{0}".format(request.user.username) context['organizer'] = course_model.is_cohort_organizer( user_uri, cohort['uri'] ) context['organizer'] |= request.user.is_superuser context['admin'] = request.user.is_superuser context['can_edit'] = context['organizer'] and not course['status'] == 'archived' context['trusted_user'] = request.user.has_perm('users.trusted_user') if course_model.user_in_cohort(user_uri, cohort['uri']): if not context['organizer']: context['show_leave_course'] = True context['learner'] = True elif cohort['signup'] == "OPEN": context['show_signup'] = True try: course_lists = learn_model.get_lists_for_course(reverse( 'courses_slug_redirect', kwargs={'course_id': course_id} )) f = lambda l: l['name'] not in ['drafts', 'listed', 'archived'] context['lists'] = filter(f, course_lists) except: log.error("Could not get lists for course!") if 'based_on_uri' in course: course['based_on'] = course_model.get_course(course['based_on_uri']) context['meta_data'] = lrmi_model.get_tags(course_uri) if 'educational_alignment' in context['meta_data']: context['educational_alignment'] = json.loads(context['meta_data']['educational_alignment']) del context['meta_data']['educational_alignment'] return context
def edit_membership(request, slug): school = get_object_or_404(School, slug=slug) if request.method == 'POST': form = school_forms.SchoolAddProjectForm(school, request.POST) if form.is_valid(): project = form.cleaned_data['project'] project.school = school project.save() messages.success( request, _('The %s was added to this school.') % project.kind.lower()) return http.HttpResponseRedirect( reverse('schools_edit_membership', kwargs=dict(slug=school.slug))) else: messages.error( request, _("There was an error adding %s to this school.") % slug) else: form = school_forms.SchoolAddProjectForm(school) return render_to_response('schools/school_edit_membership.html', { 'school': school, 'form': form, 'projects': school.projects.all(), 'membership_tab': True, }, context_instance=RequestContext(request))
def edit_featured(request, slug): school = get_object_or_404(School, slug=slug) if request.method == 'POST': form = school_forms.SchoolAddFeaturedForm(school, request.POST) if form.is_valid(): project = form.cleaned_data['project'] school.featured.add(project) school.save() msg = _('The %s is now featured for this school.') messages.success(request, msg % project.kind.lower()) return http.HttpResponseRedirect( reverse('schools_edit_featured', kwargs=dict(slug=school.slug))) else: msg = _("There was an error marking %s as featured.") messages.error(request, msg % slug) else: form = school_forms.SchoolAddFeaturedForm(school) return render_to_response('schools/school_edit_featured.html', { 'school': school, 'form': form, 'featured': school.featured.all(), 'featured_tab': True, }, context_instance=RequestContext(request))
def edit_links(request, slug): project = get_object_or_404(Project, slug=slug) metric_permissions = project.get_metrics_permissions(request.user) profile = request.user.get_profile() if request.method == 'POST': form = project_forms.ProjectLinksForm(request.POST) if form.is_valid(): link = form.save(commit=False) link.project = project link.user = profile link.save() messages.success(request, _('Link added.')) return http.HttpResponseRedirect( reverse('projects_edit_links', kwargs=dict(slug=project.slug))) else: messages.error(request, _('There was an error adding your link.')) else: form = project_forms.ProjectLinksForm() links = Link.objects.select_related('subscription').filter(project=project) return render_to_response('projects/project_edit_links.html', { 'project': project, 'form': form, 'links': links, 'links_tab': True, 'can_view_metric_overview': metric_permissions[0], }, context_instance=RequestContext(request))
def message_sent_handler(sender, **kwargs): message = kwargs.get('instance', None) created = kwargs.get('created', False) if not created or not isinstance(message, Message): return user = message.recipient preferences = AccountPreferences.objects.filter(user=user.get_profile()) for preference in preferences: if preference.value and preference.key == 'no_email_message_received': return sender = message.sender.get_profile().display_name ulang = get_language() activate(user.get_profile().preflang or settings.LANGUAGE_CODE) subject = ugettext('New Message from %(display_name)s') % { 'display_name': sender, } body = render_to_string( 'drumbeatmail/emails/direct_message.txt', { 'sender': sender, 'message': message.body, 'domain': Site.objects.get_current().domain, 'reply_url': reverse('drumbeatmail_reply', kwargs={ 'message': message.pk, }), }) activate(ulang) SendUserEmail.apply_async((user.get_profile(), subject, body))
def test_protected_usernames(self): """ Ensure that users cannot register using usernames that would conflict with other urlpatterns. """ path = reverse('users_register') bad = ('groups', 'admin', 'people', 'about') for username in bad: response = self.client.post( path, { 'username': username, 'password': '******', 'password_confirm': 'foobar123', 'email': '*****@*****.**', 'preflang': 'en' }) self.assertContains(response, 'Please choose another') ok = self.client.post( path, { 'username': '******', 'password': '******', 'password_confirm': 'foobar123', 'email': '*****@*****.**', 'preflang': 'en', }) self.assertEqual(302, ok.status_code)
def edit_links_edit(request, slug, link): link = get_object_or_404(Link, id=link) form = project_forms.ProjectLinksForm(request.POST or None, instance=link) profile = get_object_or_404(UserProfile, user=request.user) project = get_object_or_404(Project, slug=slug) if link.project != project: return http.HttpResponseForbidden(_("You can't edit this link")) metric_permissions = project.get_metrics_permissions(request.user) if form.is_valid(): if link.subscription: #links_tasks.UnsubscribeFromFeed.apply_async(args=(link,)) link.subscription = None link.save() link = form.save(commit=False) link.user = profile link.project = project link.save() messages.success(request, _('Link updated.')) return http.HttpResponseRedirect( reverse('projects_edit_links', kwargs=dict(slug=project.slug))) else: form = project_forms.ProjectLinksForm(instance=link) return render_to_response('projects/project_edit_links_edit.html', { 'project': project, 'form': form, 'link': link, 'links_tab': True, 'can_view_metric_overview': metric_permissions[0], }, context_instance=RequestContext(request))
def edit_participants(request, slug): project = get_object_or_404(Project, slug=slug) metric_permissions = project.get_metrics_permissions(request.user) if request.method == 'POST': form = project_forms.ProjectAddParticipantForm(project, request.POST) if form.is_valid(): user = form.cleaned_data['user'] organizing = form.cleaned_data['organizer'] participation = Participation(project=project, user=user, organizing=organizing) participation.save() new_rel, created = Relationship.objects.get_or_create( source=user, target_project=project) new_rel.deleted = False new_rel.save() messages.success(request, _('Participant added.')) return http.HttpResponseRedirect(reverse( 'projects_edit_participants', kwargs=dict(slug=project.slug))) else: messages.error(request, _('There was an error adding the participant.')) else: form = project_forms.ProjectAddParticipantForm(project) return render_to_response('projects/project_edit_participants.html', { 'project': project, 'form': form, 'participations': project.participants().order_by('joined_on'), 'participants_tab': True, 'can_view_metric_overview': metric_permissions[0], 'is_challenge': (project.category == project.CHALLENGE), }, context_instance=RequestContext(request))
def edit_next_steps(request, slug): project = get_object_or_404(Project, slug=slug) metric_permissions = project.get_metrics_permissions(request.user) if request.method == 'POST': form = project_forms.ProjectAddNextProjectForm(project, request.POST) if form.is_valid(): next_project = form.cleaned_data['next_project'] project.next_projects.add(next_project) messages.success(request, _('Next step added.')) return http.HttpResponseRedirect(reverse( 'projects_edit_next_steps', kwargs=dict(slug=project.slug))) else: messages.error(request, _('There was an error adding that next step.')) else: form = project_forms.ProjectAddNextProjectForm(project) return render_to_response('projects/project_edit_next_steps.html', { 'project': project, 'form': form, 'next_steps': project.next_projects.all(), 'next_steps_tab': True, 'can_view_metric_overview': metric_permissions[0], 'is_challenge': (project.category == project.CHALLENGE), }, context_instance=RequestContext(request))
def reply(request, message): message = get_object_or_404(Message, id=message) if message.recipient != request.user: return http.HttpResponseForbidden(_("Can't send email")) if request.method == 'POST': form = forms.ComposeReplyForm(data=request.POST, sender=request.user.get_profile()) if form.is_valid(): form.save(sender=request.user) messages.success(request, _('Message successfully sent.')) return http.HttpResponseRedirect(reverse('drumbeatmail_inbox')) else: messages.error(request, _('There was an error sending your message' '. Please try again.')) else: if not message.subject.startswith('Re: '): subject = 'Re: %s' % (message.subject,) else: subject = message.subject form = forms.ComposeReplyForm(initial={ 'recipient': message.sender.get_profile().username, 'subject': subject, }) return render_to_response('drumbeatmail/reply.html', { 'form': form, 'message': message, }, context_instance=RequestContext(request))
def decorator(*args, **kwargs): request = args[0] if request.user.is_authenticated(): messages.info(request, _("You are already logged into an account.")) return HttpResponseRedirect(reverse('dashboard')) return func(*args, **kwargs)
def outbox(request, page_number=1): func = Message.objects.outbox_for func_args = (request.user,) more_link_name = 'drumbeatmail_outbox_offset' return generic_inbox( request, func, func_args, page_number, more_link_name, {}, reverse('drumbeatmail_outbox'), sent_view=True)
def import_from_old_site(request): user = request.user.get_profile() if request.method == 'POST': form = project_forms.ImportProjectForm(request.POST) if form.is_valid(): course = form.cleaned_data['course'] project = Project(name=course['name'], kind=course['kind'], short_description=course['short_description'], long_description=course['long_description'], imported_from=course['slug']) project.save() act = Activity(actor=user, verb=verbs['post'], scope_object=project, target_object=project) act.save() participation = Participation(project=project, user=user, organizing=True) participation.save() new_rel, created = Relationship.objects.get_or_create(source=user, target_project=project) new_rel.deleted = False new_rel.save() if course['detailed_description']: detailed_description_content = course['detailed_description'] else: detailed_description_content = render_to_string( "projects/detailed_description_initial_content.html", {}) detailed_description = Page(title=_('Full Description'), slug='full-description', content=detailed_description_content, listed=False, author_id=user.id, project_id=project.id) detailed_description.save() project.detailed_description_id = detailed_description.id sign_up = Signup(between_participants=course['sign_up'], author_id=user.id, project_id=project.id) sign_up.save() project.save() for title, content in course['tasks']: new_task = Page(title=title, content=content, author=user, project=project) new_task.save() for name, url in course['links']: new_link = Link(name=name, url=url, user=user, project=project) new_link.save() project.create() messages.success(request, _('The %s has been imported.') % project.kind.lower()) return http.HttpResponseRedirect(reverse('projects_show', kwargs={ 'slug': project.slug, })) else: msg = _("Problem importing the study group, course, ...") messages.error(request, msg) else: form = project_forms.ImportProjectForm() return render_to_response('projects/project_import.html', { 'form': form, 'import_tab': True}, context_instance=RequestContext(request))
def show_page(request, slug, page_slug): page = get_object_or_404(Page, project__slug=slug, slug=page_slug) is_challenge = (page.project.category == Project.CHALLENGE) if is_challenge and not page.listed: msg = _("This page is not accesible on a %s.") return http.HttpResponseForbidden(msg % page.project.kind.lower()) can_edit = page.can_edit(request.user) if page.deleted: messages.error(request, _('This task was deleted.')) if can_edit: return http.HttpResponseRedirect( reverse('page_history', kwargs={ 'slug': page.project.slug, 'page_slug': page.slug })) else: return http.HttpResponseRedirect(page.project.get_absolute_url()) new_comment_url = reverse('page_comment', kwargs=dict(scope_app_label='projects', scope_model='project', scope_pk=page.project.id, page_app_label='content', page_model='page', page_pk=page.id)) first_level_comments = page.first_level_comments() all_listed_pages = page.project.pages.filter(deleted=False, listed=True).order_by('index') if is_challenge and request.user.is_authenticated(): profile = request.user.get_profile() page.is_done = PerUserTaskCompletion.objects.filter( user=profile, page=page, unchecked_on__isnull=True) context = { 'page': page, 'project': page.project, 'can_edit': can_edit, 'can_comment': page.can_comment(request.user), 'new_comment_url': new_comment_url, 'is_challenge': is_challenge, 'all_listed_pages': all_listed_pages, 'next_page': page.get_next_page(), } context.update(get_pagination_context(request, first_level_comments)) return render_to_response('content/page.html', context, context_instance=RequestContext(request))
def render(self, name, value, attrs={}): if value is None: value = '' # Not charing locale info between different instance of the form. config = self.config.copy() config['language'] = get_language() final_attrs = self.build_attrs(attrs, name=name) self.config['filebrowserUploadUrl'] = reverse('ckeditor_upload') self.config['filebrowserBrowseUrl'] = reverse('ckeditor_browse') return mark_safe( u'''<textarea%s>%s</textarea> <script type="text/javascript"> CKEDITOR.replace("%s", %s); </script>''' % (flatatt(final_attrs), conditional_escape( force_unicode(value)), final_attrs['id'], json_encode(config)))
def hide_welcome(request): profile = request.user.get_profile() if not profile.discard_welcome: profile.discard_welcome = True profile.save() if request.is_ajax(): return HttpResponse() return HttpResponseRedirect(reverse('dashboard_index'))
def profile_edit_openids_delete(request, openid_pk): if request.method == 'POST': openid = get_object_or_404(UserOpenID, pk=openid_pk) if openid.user != request.user: return http.HttpResponseForbidden(_("You can't edit this openid")) openid.delete() messages.success(request, _('The openid was deleted.')) return http.HttpResponseRedirect(reverse('users_profile_edit_openids'))
def create(request, category=None): user = request.user.get_profile() if request.method == 'POST': form = project_forms.ProjectForm(category, request.POST) image_form = None if form.is_valid(): project = form.save() if category: project.category = category image_form = project_forms.ProjectImageForm(request.POST, request.FILES, instance=project) if image_form.is_valid(): image_form.save() project.set_duration(form.cleaned_data['duration'] or 0) #CS - too much logic in view act = Activity(actor=user, verb=verbs['post'], scope_object=project, target_object=project) act.save() participation = Participation(project=project, user=user, organizing=True) participation.save() new_rel, created = Relationship.objects.get_or_create(source=user, target_project=project) new_rel.deleted = False new_rel.save() detailed_description_content = render_to_string( "projects/detailed_description_initial_content.html", {'project': project}) detailed_description = Page(title=_('Full Description'), slug='full-description', content=detailed_description_content, listed=False, author_id=user.id, project_id=project.id) if project.category != Project.STUDY_GROUP: detailed_description.collaborative = False detailed_description.save() project.detailed_description_id = detailed_description.id sign_up = Signup(author_id=user.id, project_id=project.id) sign_up.save() project.create() messages.success(request, _('The %s has been created.') % project.kind.lower()) return http.HttpResponseRedirect(reverse('projects_create_tasks', kwargs={'slug': project.slug,})) else: msg = _("Problem creating the course") messages.error(request, msg) else: form = project_forms.ProjectForm(category, initial={'test':True}) image_form = project_forms.ProjectImageForm() context = { 'form': form, 'image_form': image_form, 'category': category, 'is_challenge': (category == Project.CHALLENGE), } return render_to_response('projects/project_create_overview.html', context, context_instance=RequestContext(request))
def create(request): user = request.user.get_profile() if request.method == 'POST': form = project_forms.CreateProjectForm(request.POST) if form.is_valid(): project = form.save() act = Activity(actor=user, verb=verbs['post'], scope_object=project, target_object=project) act.save() participation = Participation(project=project, user=user, organizing=True) participation.save() new_rel, created = Relationship.objects.get_or_create( source=user, target_project=project) new_rel.deleted = False new_rel.save() detailed_description_content = render_to_string( "projects/detailed_description_initial_content.html", {}) detailed_description = Page(title=_('Full Description'), slug='full-description', content=detailed_description_content, listed=False, author_id=user.id, project_id=project.id) detailed_description.save() project.detailed_description_id = detailed_description.id sign_up_content = render_to_string( "projects/sign_up_initial_content.html", {}) sign_up = Page(title=_('Sign-Up'), slug='sign-up', content=sign_up_content, listed=False, editable=False, author_id=user.id, project_id=project.id) sign_up.save() project.sign_up_id = sign_up.id project.create() messages.success( request, _('The %s has been created.') % project.kind.lower()) return http.HttpResponseRedirect( reverse('projects_show', kwargs={ 'slug': project.slug, })) else: msg = _("Problem creating the study group, course, ...") messages.error(request, msg) else: form = project_forms.CreateProjectForm() return render_to_response('projects/project_edit_summary.html', { 'form': form, 'new_tab': True, }, context_instance=RequestContext(request))
def register(request): """Present user registration form and handle registrations.""" if request.method == 'POST': form = forms.RegisterForm(data=request.POST) if form.is_valid(): django_user = form.save(commit=False) user = create_profile(django_user) user.set_password(form.cleaned_data['password']) user.generate_confirmation_code() user.full_name = form.cleaned_data['full_name'] user.preflang = form.cleaned_data['preflang'] user.newsletter = form.cleaned_data['newsletter'] user.save() log.info(u"Registered new account for user (%s)", user) messages.success( request, _('Congratulations! Your user account ' 'was successfully created.')) path = reverse('users_confirm_registration', kwargs={ 'username': user.username, 'token': user.confirmation_code, }) url = request.build_absolute_uri(path) user.email_confirmation_code(url) msg = _('Thanks! We have sent an email to {0} with ' 'instructions for completing your ' 'registration.').format(user.email) messages.info(request, msg) return http.HttpResponseRedirect(reverse('users_login')) else: messages.error( request, _('There are errors in this form. Please ' 'correct them and resubmit.')) else: form = forms.RegisterForm() return render_to_response('users/register.html', { 'form': form, }, context_instance=RequestContext(request))
def publish(request, slug): project = get_object_or_404(Project, slug=slug) project.publish() msg = _('Congratulations, you sucessfully published your {0}!\ It will now show up on the learning page!') messages.success(request, msg.format(project.kind.lower())) return http.HttpResponseRedirect(reverse('projects_show', kwargs={ 'slug': project.slug, }))
def profile_edit_links_delete(request, link): if request.method == 'POST': profile = get_object_or_404(UserProfile, user=request.user) link = get_object_or_404(Link, pk=link) if link.user != profile: return http.HttpResponseForbidden(_("You can't edit this link")) link.delete() messages.success(request, _('The link was deleted.')) return http.HttpResponseRedirect(reverse('users_profile_edit_links'))
def move_content_down( request, course_id, content_id ): try: course_model.reorder_course_content( "/uri/content/{0}".format(content_id), "DOWN" ) except: messages.error(request, _("Could not move content down!")) redirect_url = reverse('courses_admin_content', kwargs={'course_id': course_id}) return http.HttpResponseRedirect(redirect_url)
def profile_edit_image(request): profile = request.user.get_profile() if request.method == 'POST': form = forms.ProfileImageForm(request.POST, request.FILES, instance=profile) if form.is_valid(): messages.success(request, _('Profile image updated')) form.save() return http.HttpResponseRedirect( reverse('users_profile_edit_image')) else: messages.error(request, _('There was an error uploading ' 'your image.')) else: return http.HttpResponseRedirect(reverse('users_profile_edit'))
def render(self, name, value, attrs={}): self.config = DEFAULT_CONFIG.copy() self.config.update(CKEDITOR_CONFIGS[self.config_name]) self.config['language'] = get_language() if value is None: value = '' final_attrs = self.build_attrs(attrs, name=name) self.config['filebrowserImageUploadUrl'] = reverse('ckeditor_upload') self.config['filebrowserImageBrowseUrl'] = reverse('ckeditor_browse') self.config['filebrowserUploadUrl'] = reverse('richtext_upload_file') self.config['filebrowserBrowseUrl'] = reverse('richtext_browse_file') return mark_safe( u'''<textarea%s>%s</textarea> <script type="text/javascript"> CKEDITOR.replace("%s", %s); </script>''' % (flatatt(final_attrs), conditional_escape(force_unicode(value)), final_attrs['id'], json_encode(self.config)))
def email(request): profile = request.user.get_profile() email = profile.user.email if request.method == "POST": form = forms.EmailEditForm(profile.username, request.POST, request.FILES, instance=profile) if form.is_valid(): profile = form.save(commit=False) profile.user.email = profile.email profile.user.save() profile.confirmation_code = profile.generate_confirmation_code() profile.save() path = reverse('users_confirm_registration', kwargs={ 'username': profile.username, 'token': profile.confirmation_code, }) url = request.build_absolute_uri(path) profile.email_confirmation_code(url, new_user=False) msg1 = _('A link to confirm your email address was sent ' 'to %s.') % profile.email messages.info(request, msg1) form = forms.EmailEditForm(profile.username, instance=profile) else: form = forms.EmailEditForm(profile.username, instance=profile) if profile.confirmation_code and not form.is_bound: url = request.build_absolute_uri(reverse('users_confirm_resend')) msg2 = _('If you did not receive the confirmation email, make ' 'sure your email service did not mark it as "junk ' 'mail" or "spam". If you need to, you can have us ' '<a href="%s">resend the confirmation message</a> ' 'to your email address.') % url messages.info(request, msg2, safe=True) return render_to_response('users/settings_email.html', { 'profile': profile, 'email': email, 'form': form, 'email_tab': True, }, context_instance=RequestContext(request))
def course_update_attribute( request, course_id, attribute): course_uri = course_model.course_id2uri(course_id) form = CourseUpdateForm(request.POST) if form.is_valid(): kwargs = { attribute: form.cleaned_data[attribute] } course_model.update_course( course_uri, **kwargs ) else: messages.error(request, _("Could not update {0}.".format(attribute))) redirect_url = reverse('courses_settings', kwargs={'course_id': course_id}) return http.HttpResponseRedirect(redirect_url)
def edit_participants_make_organizer(request, slug, username): participation = get_object_or_404(Participation, project__slug=slug, user__username=username, left_on__isnull=True) if participation.organizing or request.method != 'POST': return HttpResponseForbidden(_("You can't make that person an organizer")) participation.organizing = True participation.save() messages.success(request, _('The participant is now an organizer.')) return http.HttpResponseRedirect(reverse('projects_edit_participants', kwargs=dict(slug=participation.project.slug)))
def project_list(request): school = None project_list_url = reverse('projects_gallery') if 'school' in request.GET: try: school = School.objects.get(slug=request.GET['school']) except School.DoesNotExist: return http.HttpResponseRedirect(project_list_url) return render_to_response('projects/gallery.html', {'school': school}, context_instance=RequestContext(request))
def edit_declined_delete(request, slug, project_slug): school = get_object_or_404(School, slug=slug) project = get_object_or_404(Project, slug=project_slug) if request.method == 'POST': school.declined.remove(project) messages.success(request, _( "The study group stopped being declined for this school.")) return http.HttpResponseRedirect(reverse('schools_edit_declined', kwargs={ 'slug': school.slug, }))
def inbox_filtered(request, filter, page_number=1): sender = get_object_or_404(UserProfile, username=filter) func = Message.objects.inbox_for func_args = (request.user, ) redirect_url = reverse('drumbeatmail_inbox_filtered', kwargs=dict(filter=filter)) more_link_name = 'drumbeatmail_inbox_filtered_offset' more_link_kwargs = dict(filter=filter) return generic_inbox(request, func, func_args, page_number, more_link_name, more_link_kwargs, redirect_url, dict(sender=sender))
def edit_membership_delete(request, slug, project_slug): school = get_object_or_404(School, slug=slug) project = get_object_or_404(Project, slug=project_slug, school__slug=slug) if request.method == 'POST': project.school = None project.save() messages.success(request, _( "The %s is no longer part of this school.") % project.kind.lower()) return http.HttpResponseRedirect(reverse('schools_edit_membership', kwargs={'slug': school.slug}))
def edit_featured_delete(request, slug, project_slug): school = get_object_or_404(School, slug=slug) project = get_object_or_404(Project, slug=project_slug) if request.method == 'POST': school.featured.remove(project) msg = _("The %s stopped being featured for this school.") messages.success(request, msg % project.kind.lower()) return http.HttpResponseRedirect(reverse('schools_edit_featured', kwargs={ 'slug': school.slug, }))
def edit_links_delete(request, slug, link): if request.method == 'POST': project = get_object_or_404(Project, slug=slug) link = get_object_or_404(Link, pk=link) if link.project != project: return http.HttpResponseForbidden(_("You can't edit this link")) link.delete() messages.success(request, _('The link was deleted')) return http.HttpResponseRedirect( reverse('projects_edit_links', kwargs=dict(slug=slug)))
def dashboard(request): """Personalized dashboard for authenticated users.""" try: profile = request.user.get_profile() return HttpResponseRedirect( reverse("users_profile_view", kwargs={"username": request.user.username})) except UserProfile.DoesNotExist: user = request.user username = '' if user.username[:10] != 'openiduser': username = user.username form = CreateProfileForm( initial={ 'full_name': ' '.join((user.first_name, user.last_name)), 'email': user.email, 'username': username, }) messages.info( request, _('Please fill out your profile to finish registration.')) return render_to_response('dashboard/setup_profile.html', { 'form': form, }, context_instance=RequestContext(request)) show_welcome = not profile.discard_welcome activities = Activity.objects.dashboard(request.user.get_profile()) activities = filter_activities(request, activities) context = { 'profile': profile, 'current_projects': current_projects, 'users_following': users_following, 'users_followers': users_followers, 'interests': interests, 'desired_topics': desired_topics, 'links': links, 'show_welcome': show_welcome, 'domain': Site.objects.get_current().domain, 'dashboard_url': reverse('dashboard'), } context.update(get_pagination_context(request, activities)) return render_to_response('dashboard/dashboard.html', context, context_instance=RequestContext(request))