def delete(request, id, template_name="resumes/delete.html"): resume = get_object_or_404(Resume, pk=id) if has_perm(request.user,'resumes.delete_resume'): if request.method == "POST": EventLog.objects.log(instance=resume) messages.add_message(request, messages.SUCCESS, _('Successfully deleted %(r)s' % {'r':resume})) # send notification to administrators recipients = get_notice_recipients('module', 'resumes', 'resumerecipients') if recipients: if notification: extra_context = { 'object': resume, 'request': request, } notification.send_emails(recipients,'resume_deleted', extra_context) resume.delete() return HttpResponseRedirect(reverse('resume.search')) return render_to_resp(request=request, template_name=template_name, context={'resume': resume}) else: raise Http403
def request_new(request, template_name="help_files/request_new.html"): "Request new file form" if request.method == 'POST': form = RequestForm(request.POST) if form.is_valid(): instance = form.save() # send notification to administrators recipients = get_notice_recipients('module', 'help_files', 'helpfilerecipients') if recipients: if notification: extra_context = { 'object': instance, 'request': request, } notification.send_emails(recipients, 'help_file_requested', extra_context) messages.add_message(request, messages.INFO, _('Thanks for requesting a new help file!')) EventLog.objects.log() return HttpResponseRedirect(reverse('help_files')) else: form = RequestForm() return render_to_resp(request=request, template_name=template_name, context={'form': form})
def delete(request, id, template_name="pages/delete.html"): page = get_object_or_404(Page, pk=id) if not has_perm(request.user, 'pages.delete_page'): raise Http403 if request.method == "POST": EventLog.objects.log(instance=page) messages.add_message( request, messages.SUCCESS, _('Successfully deleted %(p)s' % {'p': unicode(page)})) # send notification to administrators recipients = get_notice_recipients('module', 'pages', 'pagerecipients') if recipients: if notification: extra_context = { 'object': page, 'request': request, } notification.send_emails(recipients, 'page_deleted', extra_context) # Soft delete page.status = False page.status_detail = 'inactive' page.save() return HttpResponseRedirect(reverse('page.search')) return render_to_response(template_name, {'page': page}, context_instance=RequestContext(request))
def delete(request, id, template_name="chapters/delete.html"): chapter = get_object_or_404(Chapter, pk=id) if not has_perm(request.user, 'chapters.delete_chapter'): raise Http403 if request.method == "POST": EventLog.objects.log(instance=chapter) messages.add_message(request, messages.SUCCESS, 'Successfully deleted %s' % chapter) # send notification to administrators recipients = get_notice_recipients('module', 'chapters', 'chapterrecipients') if recipients: if notification: extra_context = { 'object': chapter, 'request': request, } notification.send_emails(recipients, 'chapter_deleted', extra_context) chapter.delete() return HttpResponseRedirect(reverse('chapters.search')) return render_to_resp(request=request, template_name=template_name, context={'chapter': chapter})
def delete(request, id, template_name="news/delete.html"): news = get_object_or_404(News, pk=id) # check permission if not has_perm(request.user, 'news.delete_news'): raise Http403 if request.method == "POST": msg_string = 'Successfully deleted %s' % unicode(news) messages.add_message(request, messages.SUCCESS, _(msg_string)) # send notification to administrators recipients = get_notice_recipients('module', 'news', 'newsrecipients') if recipients: if notification: extra_context = { 'object': news, 'request': request, } notification.send_emails(recipients, 'news_deleted', extra_context) news.delete() return HttpResponseRedirect(reverse('news.search')) return render_to_response(template_name, {'news': news}, context_instance=RequestContext(request))
def delete(request, id, template_name="articles/delete.html"): article = get_object_or_404(Article, pk=id) if has_perm(request.user, 'articles.delete_article'): if request.method == "POST": msg_string = 'Successfully deleted %s' % str(article) messages.add_message(request, messages.SUCCESS, _(msg_string)) # send notification to administrators recipients = get_notice_recipients('module', 'articles', 'articlerecipients') if recipients: if notification: extra_context = { 'object': article, 'request': request, } notification.send_emails(recipients, 'article_deleted', extra_context) article.delete() return HttpResponseRedirect(reverse('article.search')) return render_to_resp(request=request, template_name=template_name, context={'article': article}) else: raise Http403
def delete(request, id, template_name="committees/delete.html"): committee = get_object_or_404(Committee, pk=id) if not has_perm(request.user, 'committees.delete_committee'): raise Http403 if request.method == "POST": EventLog.objects.log(instance=committee) messages.add_message(request, messages.SUCCESS, 'Successfully deleted %s' % committee) # send notification to administrators recipients = get_notice_recipients('module', 'committees', 'committeerecipients') if recipients: if notification: extra_context = { 'object': committee, 'request': request, } notification.send_emails(recipients, 'committee_deleted', extra_context) committee.delete() return HttpResponseRedirect(reverse('committees.search')) return render_to_response(template_name, {'committee': committee}, context_instance=RequestContext(request))
def delete(request, id, template_name="directories/delete.html"): directory = get_object_or_404(Directory, pk=id) if has_perm(request.user,'directories.delete_directory'): if request.method == "POST": msg_string = 'Successfully deleted %s' % directory messages.add_message(request, messages.SUCCESS, _(msg_string)) # send notification to administrators recipients = get_notice_recipients('module', 'directories', 'directoryrecipients') if recipients: if notification: extra_context = { 'object': directory, 'request': request, } notification.send_emails(recipients,'directory_deleted', extra_context) directory.delete() return HttpResponseRedirect(reverse('directory.search')) return render_to_response(template_name, {'directory': directory}, context_instance=RequestContext(request)) else: raise Http403
def save_model(self, request, object, form, change): instance = form.save(commit=False) instance = update_perms_and_save(request, form, instance) if instance.meta: meta = instance.meta else: meta = MetaTags() meta.title = form.cleaned_data["meta_title"] meta.description = form.cleaned_data["meta_description"] meta.keywords = form.cleaned_data["meta_keywords"] meta.canonical_url = form.cleaned_data["meta_canonical_url"] meta.save() instance.meta = meta instance.save() # notifications if not request.user.profile.is_superuser: # send notification to administrators recipients = get_notice_recipients("module", "pages", "pagerecipients") notice_type = "page_added" if change: notice_type = "page_edited" if recipients: if notification: extra_context = {"object": instance, "request": request} notification.send_emails(recipients, notice_type, extra_context) return instance
def delete(request, id, template_name="studygroups/delete.html"): study_group = get_object_or_404(StudyGroup, pk=id) if not has_perm(request.user, 'studygroups.delete_studygroup'): raise Http403 if request.method == "POST": EventLog.objects.log(instance=study_group) messages.add_message(request, messages.SUCCESS, 'Successfully deleted %s' % study_group) # send notification to administrators recipients = get_notice_recipients('module', 'studygroups', 'studygrouprecipients') if recipients: if notification: extra_context = { 'object': study_group, 'request': request, } notification.send_emails(recipients, 'studygroup_deleted', extra_context) study_group.delete() return HttpResponseRedirect(reverse('studygroups.search')) return render_to_response(template_name, {'study_group': study_group}, context_instance=RequestContext(request))
def add(request, form_class=ResumeForm, template_name="resumes/add.html"): can_add_active = has_perm(request.user, 'resumes.add_resume') if not any([ request.user.profile.is_superuser, can_add_active, get_setting('module', 'resumes', 'usercanadd'), (request.user.profile.is_member and get_setting('module', 'resumes', 'userresumesrequiresmembership')) ]): raise Http403 if request.method == "POST": form = form_class(request.POST or None, user=request.user) if form.is_valid(): resume = form.save(commit=False) # set it to pending if the user does not have add permission if not can_add_active: resume.status_detail = 'pending' # set up the expiration time based on requested duration now = datetime.now() resume.expiration_dt = now + timedelta( days=resume.requested_duration) resume = update_perms_and_save(request, form, resume) # we need to save instance first since we need the id for the file path if request.FILES: resume.resume_file = request.FILES['resume_file'] resume.resume_file.file.seek(0) resume.save() EventLog.objects.log(instance=resume) if request.user.is_authenticated(): messages.add_message( request, messages.SUCCESS, _('Successfully added %(r)s' % {'r': resume})) # send notification to administrators recipients = get_notice_recipients('module', 'resumes', 'resumerecipients') if recipients: if notification: extra_context = { 'object': resume, 'request': request, } notification.send_emails(recipients, 'resume_added', extra_context) if not request.user.is_authenticated(): return HttpResponseRedirect(reverse('resume.thank_you')) else: return HttpResponseRedirect( reverse('resume', args=[resume.slug])) else: form = form_class(user=request.user) return render_to_response(template_name, {'form': form}, context_instance=RequestContext(request))
def add(request, form_class=HelpFileForm, template_name="help_files/add.html"): if has_perm(request.user,'help_files.add_helpfile'): if request.method == "POST": form = form_class(request.POST, user=request.user) if form.is_valid(): help_file = form.save(commit=False) # add all permissions and save the model help_file = update_perms_and_save(request, form, help_file) form.save_m2m() msg_string = 'Successfully added %s' % help_file messages.add_message(request, messages.SUCCESS, _(msg_string)) # send notification to administrator(s) and module recipient(s) recipients = get_notice_recipients('module', 'help_files', 'helpfilerecipients') # if recipients and notification: # notification.send_emails(recipients,'help_file_added', { # 'object': help_file, # 'request': request, # }) return HttpResponseRedirect(reverse('help_file.details', args=[help_file.slug])) else: form = form_class(user=request.user) return render_to_response(template_name, {'form':form}, context_instance=RequestContext(request)) else: raise Http403
def delete(request, id, template_name="pages/delete.html"): page = get_object_or_404(Page, pk=id) if not has_perm(request.user, 'pages.delete_page'): raise Http403 if request.method == "POST": EventLog.objects.log(instance=page) messages.add_message(request, messages.SUCCESS, _('Successfully deleted %(p)s' % { 'p': unicode(page)})) # send notification to administrators recipients = get_notice_recipients('module', 'pages', 'pagerecipients') if recipients: if notification: extra_context = { 'object': page, 'request': request, } notification.send_emails(recipients, 'page_deleted', extra_context) # Soft delete page.status = False page.status_detail = 'inactive' page.save() return HttpResponseRedirect(reverse('page.search')) return render_to_response(template_name, {'page': page}, context_instance=RequestContext(request))
def delete(request, id, template_name="jobs/delete.html"): job = get_object_or_404(Job, pk=id) if has_perm(request.user, 'jobs.delete_job', job): if request.method == "POST": msg_string = u'Successfully deleted {}'.format(str(job)) messages.add_message(request, messages.SUCCESS, _(msg_string)) # send notification to administrators recipients = get_notice_recipients('module', 'jobs', 'jobrecipients') if recipients: if notification: extra_context = { 'object': job, 'request': request, } notification.send_emails(recipients, 'job_deleted', extra_context) job.delete() return HttpResponseRedirect(reverse('job.search')) return render_to_resp(request=request, template_name=template_name, context={'job': job}) else: raise Http403
def add(request, form_class=HelpFileForm, template_name="help_files/add.html"): if has_perm(request.user, 'help_files.add_helpfile'): if request.method == "POST": form = form_class(request.POST, user=request.user) if form.is_valid(): help_file = form.save(commit=False) # add all permissions and save the model help_file = update_perms_and_save(request, form, help_file) form.save_m2m() msg_string = 'Successfully added %s' % help_file messages.add_message(request, messages.SUCCESS, _(msg_string)) # send notification to administrator(s) and module recipient(s) recipients = get_notice_recipients('module', 'help_files', 'helpfilerecipients') # if recipients and notification: # notification.send_emails(recipients,'help_file_added', { # 'object': help_file, # 'request': request, # }) return HttpResponseRedirect( reverse('help_file.details', args=[help_file.slug])) else: form = form_class(user=request.user) return render_to_response(template_name, {'form': form}, context_instance=RequestContext(request)) else: raise Http403
def save_model(self, request, object, form, change): instance = form.save(commit=False) instance = update_perms_and_save(request, form, instance) if 'meta_title' in form.cleaned_data: if instance.meta: meta = instance.meta else: meta = MetaTags() meta.title = form.cleaned_data['meta_title'] meta.description = form.cleaned_data['meta_description'] meta.keywords = form.cleaned_data['meta_keywords'] meta.canonical_url = form.cleaned_data['meta_canonical_url'] meta.save() instance.meta = meta instance.save() # notifications if not request.user.profile.is_superuser: # send notification to administrators recipients = get_notice_recipients('module', 'pages', 'pagerecipients') notice_type = 'page_added' if change: notice_type = 'page_edited' if recipients: if notification: extra_context = { 'object': instance, 'request': request, } notification.send_emails(recipients, notice_type, extra_context) return instance
def send_notifications(scope, scope_category, name, label, extra_context=None): """ a small wrapper for sending notification emails to recipients specified in site_settings. """ recipients = get_notice_recipients(scope, scope_category, name) if recipients: send_emails(recipients, label, extra_context)
def add(request, form_class=ArticleForm, category_form_class=CategoryForm, template_name="articles/add.html"): content_type = get_object_or_404(ContentType, app_label='articles', model='article') if has_perm(request.user, 'articles.add_article'): if request.method == "POST": form = form_class(request.POST, request.FILES or None, user=request.user) categoryform = category_form_class( content_type, request.POST, ) if form.is_valid() and categoryform.is_valid(): article = form.save() article.update_category_subcategory( categoryform.cleaned_data['category'], categoryform.cleaned_data['sub_category']) # add all permissions and save the model update_perms_and_save(request, form, article) msg_string = 'Successfully added %s' % str(article) messages.add_message(request, messages.SUCCESS, _(msg_string)) # send notification to administrator(s) and module recipient(s) recipients = get_notice_recipients('module', 'articles', 'articlerecipients') if recipients and notification: notification.send_emails(recipients, 'article_added', { 'object': article, 'request': request, }) return HttpResponseRedirect( reverse('article', args=[article.slug])) else: form = form_class(user=request.user) initial_category_form_data = { 'app_label': 'articles', 'model': 'article', 'pk': 0, } categoryform = category_form_class( content_type, initial=initial_category_form_data, ) return render_to_resp(request=request, template_name=template_name, context={ 'form': form, 'categoryform': categoryform, }) else: raise Http403
def group_add_edit(request, group_slug=None, form_class=GroupForm, template_name="user_groups/add_edit.html"): add, edit = False, False if group_slug: group = get_object_or_404(Group, slug=group_slug) if not has_perm(request.user,'user_groups.change_group',group): raise Http403 title = _("Edit Group") edit = True else: group = None if not has_perm(request.user,'user_groups.add_group'):raise Http403 title = _("Add Group") add = True if request.method == 'POST': if edit: form = form_class(request.POST, instance=group, user=request.user) else: form = form_class(request.POST, user=request.user) if form.is_valid(): group = form.save(commit=False) if not group.id: group.creator = request.user group.creator_username = request.user.username # set up user permission group.allow_user_view, group.allow_user_edit = form.cleaned_data['user_perms'] group.owner = request.user group.owner_username = request.user.username group = form.save() if add: # send notification to administrators recipients = get_notice_recipients('module', 'groups', 'grouprecipients') if recipients: if notification: extra_context = { 'object': group, 'request': request, } notification.send_emails(recipients,'group_added', extra_context) EventLog.objects.log(instance=group) return HttpResponseRedirect(group.get_absolute_url()) else: if edit: form = form_class(instance=group, user=request.user) else: form = form_class(user=request.user) return render_to_response(template_name, {'form':form, 'titie':title, 'group':group}, context_instance=RequestContext(request))
def add(request, form_class=ResumeForm, template_name="resumes/add.html"): can_add_active = has_perm(request.user, 'resumes.add_resume') if not any([request.user.profile.is_superuser, can_add_active, get_setting('module', 'resumes', 'usercanadd'), (request.user.profile.is_member and get_setting('module', 'resumes', 'userresumesrequiresmembership')) ]): raise Http403 if request.method == "POST": form = form_class(request.POST or None, user=request.user) if form.is_valid(): resume = form.save(commit=False) # set it to pending if the user does not have add permission if not can_add_active: resume.status_detail = 'pending' # set up the expiration time based on requested duration now = datetime.now() resume.expiration_dt = now + timedelta(days=resume.requested_duration) resume = update_perms_and_save(request, form, resume) # we need to save instance first since we need the id for the file path if request.FILES: resume.resume_file = request.FILES['resume_file'] resume.resume_file.file.seek(0) resume.save() EventLog.objects.log(instance=resume) if request.user.is_authenticated(): messages.add_message(request, messages.SUCCESS, _('Successfully added %(r)s' % {'r':resume})) # send notification to administrators recipients = get_notice_recipients('module', 'resumes', 'resumerecipients') if recipients: if notification: extra_context = { 'object': resume, 'request': request, } notification.send_emails(recipients,'resume_added', extra_context) if not request.user.is_authenticated(): return HttpResponseRedirect(reverse('resume.thank_you')) else: return HttpResponseRedirect(reverse('resume', args=[resume.slug])) else: form = form_class(user=request.user) return render_to_response(template_name, {'form':form}, context_instance=RequestContext(request))
def delete(self, *args, **kwargs): # Related objects # Import related objects here to prevent circular references from tendenci.apps.pages.models import Page from tendenci.apps.events.models import Event from tendenci.apps.stories.models import Story pages = Page.objects.filter(header_image=self.pk) events = Event.objects.filter(image=self.pk) stories = Story.objects.filter(image=self.pk) # Set foreign key of related objects to None for page in pages: page.header_image = None page.save() for event in events: event.image = None event.save() for story in stories: story.image = None story.save() # roll back the transaction to fix the error for postgresql #"current transaction is aborted, commands ignored until # end of transaction block" #connection._rollback() # comment it out because this line of code leads to IntegrityError for files that inherit File's model. # send notification to administrator(s) and module recipient(s) if self.file: recipients = get_notice_recipients('module', 'files', 'filerecipients') site_display_name = get_setting('site', 'global', 'sitedisplayname') if self.owner: owner = self.owner.get_full_name() or self.owner else: owner = "Unknown" if recipients and notification: notification.send_emails( recipients, 'file_deleted', { 'object': self, 'author': owner, 'SITE_GLOBAL_SITEDISPLAYNAME': site_display_name, }) # delete actual file; do not save() self.instance self.file.delete(save=False) # delete database record super(File, self).delete(*args, **kwargs)
def add(request, form_class=ArticleForm, category_form_class=CategoryForm, template_name="articles/add.html"): content_type = get_object_or_404(ContentType, app_label='articles', model='article') if has_perm(request.user, 'articles.add_article'): if request.method == "POST": form = form_class(request.POST, request.FILES or None, user=request.user) categoryform = category_form_class(content_type, request.POST,) if form.is_valid() and categoryform.is_valid(): article = form.save() article.update_category_subcategory( categoryform.cleaned_data['category'], categoryform.cleaned_data['sub_category'] ) # add all permissions and save the model update_perms_and_save(request, form, article) msg_string = 'Successfully added %s' % str(article) messages.add_message(request, messages.SUCCESS, _(msg_string)) # send notification to administrator(s) and module recipient(s) recipients = get_notice_recipients('module', 'articles', 'articlerecipients') if recipients and notification: notification.send_emails(recipients, 'article_added', { 'object': article, 'request': request, }) return HttpResponseRedirect(reverse('article', args=[article.slug])) else: form = form_class(user=request.user) initial_category_form_data = { 'app_label': 'articles', 'model': 'article', 'pk': 0, } categoryform = category_form_class(content_type, initial=initial_category_form_data,) return render_to_resp(request=request, template_name=template_name, context={'form': form, 'categoryform': categoryform,}) else: raise Http403
def delete(self, *args, **kwargs): # Related objects # Import related objects here to prevent circular references from tendenci.apps.pages.models import Page from tendenci.apps.events.models import Event from tendenci.apps.stories.models import Story pages = Page.objects.filter(header_image=self.pk) events = Event.objects.filter(image=self.pk) stories = Story.objects.filter(image=self.pk) # Set foreign key of related objects to None for page in pages: page.header_image = None page.save() for event in events: event.image = None event.save() for story in stories: story.image = None story.save() # roll back the transaction to fix the error for postgresql #"current transaction is aborted, commands ignored until # end of transaction block" #connection._rollback() # comment it out because this line of code leads to IntegrityError for files that inherit File's model. # send notification to administrator(s) and module recipient(s) if self.file: recipients = get_notice_recipients('module', 'files', 'filerecipients') site_display_name = get_setting('site', 'global', 'sitedisplayname') if self.owner: owner = self.owner.get_full_name() or self.owner else: owner = "Unknown" if recipients and notification: notification.send_emails(recipients, 'file_deleted', { 'object': self, 'author': owner, 'SITE_GLOBAL_SITEDISPLAYNAME': site_display_name, }) # delete actual file; do not save() self.instance self.file.delete(save=False) # delete database record super(File, self).delete(*args, **kwargs)
def group_delete(request, id, template_name="user_groups/delete.html"): group = get_object_or_404(Group, pk=id) if not has_perm(request.user, 'user_groups.delete_group', group): raise Http403 if request.method == "POST": # send notification to administrators recipients = get_notice_recipients('module', 'groups', 'grouprecipients') if recipients: if notification: extra_context = { 'object': group, 'request': request, } notification.send_emails(recipients, 'group_deleted', extra_context) EventLog.objects.log(instance=group) group.delete() return HttpResponseRedirect(reverse('group.search')) (deleted_objects, count, perms_needed, protected) = get_deleted_objects([group], request.user) object_name = group.label or group.name if perms_needed or protected: title = _("Cannot delete %(name)s") % {"name": object_name} else: title = _("Are you sure?") return render_to_resp(request=request, template_name=template_name, context={ 'group': group, "title": title, "object_name": object_name, "deleted_objects": deleted_objects, "perms_lacking": perms_needed, "protected": protected, "opts": group._meta, })
def save(self, *args, **kwargs): created = False if not self.id: self.guid = str(uuid.uuid4()) created = True self.f_type = self.type() if not self.group: self.group_id = get_default_group() super(File, self).save(*args, **kwargs) if self.is_public_file(): set_s3_file_permission(self.file, public=True) else: set_s3_file_permission(self.file, public=False) cache_set = cache.get("files_cache_set.%s" % self.pk) if cache_set is not None: # TODO remove cached images cache.delete_many(cache.get("files_cache_set.%s" % self.pk)) cache.delete("files_cache_set.%s" % self.pk) # send notification to administrator(s) and module recipient(s) if created: recipients = get_notice_recipients('module', 'files', 'filerecipients') site_display_name = get_setting('site', 'global', 'sitedisplayname') site_url = get_setting('site', 'global', 'siteurl') if recipients and notification: notification_params = { 'object': self, 'SITE_GLOBAL_SITEDISPLAYNAME': site_display_name, 'SITE_GLOBAL_SITEURL': site_url, } if self.owner: notification_params['author'] = self.owner.get_full_name( ) or self.owner notification.send_emails(recipients, 'file_added', notification_params)
def save_model(self, request, object, form, change): instance = form.save(commit=False) # update all permissions and save the model instance = update_perms_and_save(request, form, instance) # notifications if not request.user.profile.is_superuser: # send notification to administrators recipients = get_notice_recipients('site', 'global', 'allnoticerecipients') if recipients: if notification: extra_context = { 'object': instance, 'request': request, } notification.send_emails(recipients, notice_type, extra_context) return instance
def add(request, form_class=NewsForm, template_name="news/add.html"): # check permission if not has_perm(request.user, 'news.add_news'): raise Http403 if request.method == "POST": form = form_class(request.POST, request.FILES, user=request.user) if form.is_valid(): news = form.save(commit=False) # update all permissions and save the model news = update_perms_and_save(request, form, news) form.save_m2m() # save photo photo = form.cleaned_data['photo_upload'] if photo: news.save(photo=photo) assign_files_perms(news, files=[news.thumbnail]) msg_string = 'Successfully added %s' % str(news) messages.add_message(request, messages.SUCCESS, _(msg_string)) # send notification to administrators recipients = get_notice_recipients('module', 'news', 'newsrecipients') if recipients: if notification: extra_context = { 'object': news, 'request': request, } notification.send_emails(recipients, 'news_added', extra_context) return HttpResponseRedirect( reverse('news.detail', args=[news.slug])) else: form = form_class(user=request.user) return render_to_resp(request=request, template_name=template_name, context={'form': form})
def auto_update_paid_object(self, request, payment): """ Update the object after online payment is received. """ # email to admin try: from tendenci.apps.notifications import models as notification except: notification = None from tendenci.apps.perms.utils import get_notice_recipients recipients = get_notice_recipients('module', 'donations', 'donationsrecipients') if recipients: if notification: extra_context = { 'donation': self, 'invoice': payment.invoice, 'request': request, } notification.send_emails(recipients,'donation_added', extra_context)
def group_delete(request, id, template_name="user_groups/delete.html"): group = get_object_or_404(Group, pk=id) if not has_perm(request.user,'user_groups.delete_group',group): raise Http403 if request.method == "POST": # send notification to administrators recipients = get_notice_recipients('module', 'groups', 'grouprecipients') if recipients: if notification: extra_context = { 'object': group, 'request': request, } notification.send_emails(recipients,'group_deleted', extra_context) EventLog.objects.log(instance=group) group.delete() return HttpResponseRedirect(reverse('group.search')) (deleted_objects, count, perms_needed, protected) = get_deleted_objects( [group], request.user) object_name = group.label or group.name if perms_needed or protected: title = _("Cannot delete %(name)s") % {"name": object_name} else: title = _("Are you sure?") return render_to_response(template_name, {'group':group, "title": title, "object_name": object_name, "deleted_objects": deleted_objects, "perms_lacking": perms_needed, "protected": protected, "opts": group._meta, }, context_instance=RequestContext(request))
def save(self, *args, **kwargs): created = False if not self.id: self.guid = str(uuid.uuid4()) created = True self.f_type = self.type() if not self.group: self.group_id = get_default_group() super(File, self).save(*args, **kwargs) if self.is_public_file(): set_s3_file_permission(self.file, public=True) else: set_s3_file_permission(self.file, public=False) cache_set = cache.get("files_cache_set.%s" % self.pk) if cache_set is not None: # TODO remove cached images cache.delete_many(cache.get("files_cache_set.%s" % self.pk)) cache.delete("files_cache_set.%s" % self.pk) # send notification to administrator(s) and module recipient(s) if created: recipients = get_notice_recipients('module', 'files', 'filerecipients') site_display_name = get_setting('site', 'global', 'sitedisplayname') site_url = get_setting('site', 'global', 'siteurl') if recipients and notification: notification_params = { 'object': self, 'SITE_GLOBAL_SITEDISPLAYNAME': site_display_name, 'SITE_GLOBAL_SITEURL': site_url, } if self.owner: notification_params['author'] = self.owner.get_full_name() or self.owner notification.send_emails(recipients, 'file_added', notification_params)
def add(request, form_class=NewsForm, template_name="news/add.html"): # check permission if not has_perm(request.user, 'news.add_news'): raise Http403 if request.method == "POST": form = form_class(request.POST, request.FILES, user=request.user) if form.is_valid(): news = form.save(commit=False) # update all permissions and save the model news = update_perms_and_save(request, form, news) form.save_m2m() # save photo photo = form.cleaned_data['photo_upload'] if photo: news.save(photo=photo) assign_files_perms(news, files=[news.thumbnail]) msg_string = 'Successfully added %s' % unicode(news) messages.add_message(request, messages.SUCCESS, _(msg_string)) # send notification to administrators recipients = get_notice_recipients('module', 'news', 'newsrecipients') if recipients: if notification: extra_context = { 'object': news, 'request': request, } notification.send_emails(recipients, 'news_added', extra_context) return HttpResponseRedirect(reverse('news.detail', args=[news.slug])) else: form = form_class(user=request.user) return render_to_response(template_name, {'form': form}, context_instance=RequestContext(request))
def add(request, form_class=VideoFrontEndForm, template_name="videos/edit.html"): # check permission if not has_perm(request.user, 'videos.add_video'): raise Http403 if request.method == "POST": form = form_class(request.POST, request.FILES, user=request.user) if form.is_valid(): video = form.save(commit=False) video.creator = request.user video.creator_username = request.user.username if not request.user.is_superuser: video.status_detail = 'pending' # update all permissions and save the model video = update_perms_and_save(request, form, video) form.save_m2m() msg_string = _(f'Successfully added {str(video)}') if not request.user.is_superuser: msg_string += _('... Pending on Admin approval.') messages.add_message(request, messages.SUCCESS, msg_string) # send notification to administrator(s) and module recipient(s) recipients = get_notice_recipients('module', 'videos', 'videorecipients') if recipients and notification: notification.send_emails(recipients, 'video_added', { 'object': video, 'request': request, }) return HttpResponseRedirect(reverse('video.details', args=[video.slug])) else: form = form_class(user=request.user) return render_to_resp(request=request, template_name=template_name, context={'form': form, 'edit_mode': False})
def request_new(request, template_name="help_files/request_new.html"): "Request new file form" if request.method == 'POST': form = RequestForm(request.POST) if form.is_valid(): instance = form.save() # send notification to administrators recipients = get_notice_recipients('module', 'help_files', 'helpfilerecipients') if recipients: if notification: extra_context = { 'object': instance, 'request': request, } notification.send_emails(recipients,'help_file_requested', extra_context) messages.add_message(request, messages.INFO, _('Thanks for requesting a new help file!')) EventLog.objects.log() return HttpResponseRedirect(reverse('help_files')) else: form = RequestForm() return render_to_resp(request=request, template_name=template_name, context={'form': form})
def delete(request, id, template_name="pages/delete.html"): page = get_object_or_404(Page, pk=id) if not has_perm(request.user, "pages.delete_page"): raise Http403 if request.method == "POST": EventLog.objects.log(instance=page) messages.add_message(request, messages.SUCCESS, _("Successfully deleted %(p)s" % {"p": unicode(page)})) # send notification to administrators recipients = get_notice_recipients("module", "pages", "pagerecipients") if recipients: if notification: extra_context = {"object": page, "request": request} notification.send_emails(recipients, "page_deleted", extra_context) # Soft delete page.status = False page.status_detail = "inactive" page.save() return HttpResponseRedirect(reverse("page.search")) return render_to_response(template_name, {"page": page}, context_instance=RequestContext(request))
def add(request, form_class=JobForm, template_name="jobs/add.html", object_type=Job, success_redirect='job', thankyou_redirect='job.thank_you'): require_payment = get_setting('module', 'jobs', 'jobsrequirespayment') can_add_active = has_perm(request.user, 'jobs.add_job') get_object_or_404(ContentType, app_label=object_type._meta.app_label, model=object_type._meta.model_name) form = form_class(request.POST or None, request.FILES or None, user=request.user) # adjust the fields depending on user type if not require_payment: del form.fields['payment_method'] del form.fields['list_type'] if request.method == "POST": if require_payment: is_free = is_free_listing(request.user, request.POST.get('pricing', 0), request.POST.get('list_type')) if is_free: del form.fields['payment_method'] if form.is_valid(): job = form.save(commit=False) pricing = form.cleaned_data['pricing'] if require_payment and is_free: job.payment_method = 'paid - cc' # set it to pending if the user is anonymous or not an admin if not can_add_active: #job.status = 1 job.status_detail = 'pending' # list types and duration if not job.requested_duration: job.requested_duration = 30 if not job.list_type: job.list_type = 'regular' # set up all the times now = datetime.now() job.activation_dt = now if not job.post_dt: job.post_dt = now # set the expiration date job.expiration_dt = job.activation_dt + timedelta( days=job.requested_duration) # semi-anon job posts don't get a slug field on the form # see __init__ method in JobForm if not job.slug: #job.slug = get_job_unique_slug(slugify(job.title)) job.slug = '%s-%s' % (slugify( job.title), object_type.objects.count()) job = update_perms_and_save(request, form, job) # create invoice job_set_inv_payment(request.user, job, pricing) #save relationships job.save() msg_string = u'Successfully added %s' % str(job) messages.add_message(request, messages.SUCCESS, _(msg_string)) # send notification to administrators recipients = get_notice_recipients('module', 'jobs', 'jobrecipients') if recipients: if notification: extra_context = { 'object': job, 'request': request, } notification.send_emails(recipients, 'job_added', extra_context) # send user to the payment page if payment is required if require_payment: if job.payment_method.lower() in [ 'credit card', 'cc', 'online payment' ]: if job.invoice and job.invoice.balance > 0: return HttpResponseRedirect( reverse('payment.pay_online', args=[job.invoice.id, job.invoice.guid])) # send user to thank you or view page if request.user.profile.is_superuser: return HttpResponseRedirect( reverse(success_redirect, args=[job.slug])) else: return HttpResponseRedirect(reverse(thankyou_redirect)) else: # Redirect user w/perms to create pricing if none exist pricings = JobPricing.objects.all() if not pricings and has_perm(request.user, 'jobs.add_jobpricing'): msg_string = 'You need to add a %s Pricing before you can add a %s.' % ( get_setting('module', 'jobs', 'label_plural'), get_setting('module', 'jobs', 'label')) messages.add_message(request, messages.WARNING, _(msg_string)) return HttpResponseRedirect(reverse('job_pricing.add')) return render_to_resp(request=request, template_name=template_name, context={ 'form': form, 'require_payment': require_payment })
def edit( request, id, form_class=PageForm, meta_form_class=MetaForm, category_form_class=CategoryForm, template_name="pages/edit.html", ): page = get_object_or_404(Page, pk=id) if not has_perm(request.user, "pages.change_page", page): raise Http403 content_type = get_object_or_404(ContentType, app_label="pages", model="page") if request.method == "POST": form = form_class(request.POST, request.FILES, instance=page, user=request.user) metaform = meta_form_class(request.POST, instance=page.meta, prefix="meta") categoryform = category_form_class(content_type, request.POST, prefix="category") if form.is_valid() and metaform.is_valid() and categoryform.is_valid(): page = form.save() # handle header image f = form.cleaned_data["header_image"] if f: header = HeaderImage() header.content_type = ContentType.objects.get_for_model(Page) header.object_id = page.id header.creator = request.user header.creator_username = request.user.username header.owner = request.user header.owner_username = request.user.username filename = "%s-%s" % (page.slug, f.name) f.file.seek(0) header.file.save(filename, f) page.header_image = header # save meta meta = metaform.save() page.meta = meta ## update the category and subcategory page.update_category_subcategory( categoryform.cleaned_data["category"], categoryform.cleaned_data["sub_category"] ) # update all permissions page = update_perms_and_save(request, form, page) if page.pk == 1: # the about page has id 1 in the npo defaults fixture checklist_update("update-about") messages.add_message(request, messages.SUCCESS, _("Successfully updated %(p)s" % {"p": unicode(page)})) if not request.user.profile.is_superuser: # send notification to administrators recipients = get_notice_recipients("module", "pages", "pagerecipients") if recipients: if notification: extra_context = {"object": page, "request": request} notification.send_emails(recipients, "page_edited", extra_context) return HttpResponseRedirect(reverse("page", args=[page.slug])) else: form = form_class(instance=page, user=request.user) metaform = meta_form_class(instance=page.meta, prefix="meta") # setup categories category = Category.objects.get_for_object(page, "category") sub_category = Category.objects.get_for_object(page, "sub_category") initial_category_form_data = { "app_label": "pages", "model": "page", "pk": page.pk, "category": getattr(category, "name", "0"), "sub_category": getattr(sub_category, "name", "0"), } categoryform = category_form_class(content_type, initial=initial_category_form_data, prefix="category") return render_to_response( template_name, {"page": page, "form": form, "metaform": metaform, "categoryform": categoryform}, context_instance=RequestContext(request), )
def activate(request, activation_key, template_name='registration/activate.html', extra_context=None): """ Activate a ``User``'s account from an activation key, if their key is valid and hasn't expired. By default, use the template ``registration/activate.html``; to change this, pass the name of a template as the keyword argument ``template_name``. **Required arguments** ``activation_key`` The activation key to validate and use for activating the ``User``. **Optional arguments** ``extra_context`` A dictionary of variables to add to the template context. Any callable object in this dictionary will be called to produce the end result which appears in the context. ``template_name`` A custom template to use. **Context:** ``account`` The ``User`` object corresponding to the account, if the activation was successful. ``False`` if the activation was not successful. ``expiration_days`` The number of days for which activation keys stay valid after registration. Any extra variables supplied in the ``extra_context`` argument (see above). **Template:** registration/activate.html or ``template_name`` keyword argument. """ activation_key = activation_key.lower() # Normalize before trying anything with it. account = RegistrationProfile.objects.activate_user(activation_key) if account: account.auto_login = True credentials = { 'username': '', 'password': '', 'user': account } user = authenticate(**credentials) login(request, user) # send notification to administrators recipients = get_notice_recipients('module', 'users', 'userrecipients') if recipients: if notification: extra_context = { 'object': user.profile, 'request': request, } notification.send_emails(recipients,'user_added', extra_context) if extra_context is None: extra_context = {} context = RequestContext(request) for key, value in extra_context.items(): context[key] = callable(value) and value() or value next_url = request.GET.get('next', '') if account and next_url: return HttpResponseRedirect(next_url) return render_to_response(template_name, { 'account': account, 'expiration_days': settings.ACCOUNT_ACTIVATION_DAYS }, context_instance=context)
def renew(request, id, form_class=DirectoryRenewForm, template_name="directories/renew.html"): can_add_active = has_perm(request.user,'directories.add_directory') require_approval = get_setting('module', 'directories', 'renewalrequiresapproval') directory = get_object_or_404(Directory, pk=id) if not has_perm(request.user,'directories.change_directory', directory) or not request.user == directory.creator: raise Http403 # pop payment fields if not required require_payment = get_setting('module', 'directories', 'directoriesrequirespayment') form = form_class(request.POST or None, request.FILES or None, instance=directory, user=request.user) if not require_payment: del form.fields['payment_method'] del form.fields['list_type'] if request.method == "POST": if form.is_valid(): directory = form.save(commit=False) pricing = form.cleaned_data['pricing'] if directory.payment_method: directory.payment_method = directory.payment_method.lower() if not directory.requested_duration: directory.requested_duration = 30 if not directory.list_type: directory.list_type = 'regular' if not directory.slug: directory.slug = '%s-%s' % (slugify(directory.headline), Directory.objects.count()) if not can_add_active and require_approval: directory.status = True directory.status_detail = 'pending' else: directory.activation_dt = datetime.now() # set the expiration date directory.expiration_dt = directory.activation_dt + timedelta(days=directory.requested_duration) # mark renewal as not sent for new exp date directory.renewal_notice_sent = False # update all permissions and save the model directory = update_perms_and_save(request, form, directory) # create invoice directory_set_inv_payment(request.user, directory, pricing) msg_string = 'Successfully renewed %s' % directory messages.add_message(request, messages.SUCCESS, _(msg_string)) # send notification to administrators # get admin notice recipients recipients = get_notice_recipients('module', 'directories', 'directoryrecipients') if recipients: if notification: extra_context = { 'object': directory, 'request': request, } notification.send_emails(recipients,'directory_renewed', extra_context) if directory.payment_method.lower() in ['credit card', 'cc']: if directory.invoice and directory.invoice.balance > 0: return HttpResponseRedirect(reverse('payments.views.pay_online', args=[directory.invoice.id, directory.invoice.guid])) if can_add_active: return HttpResponseRedirect(reverse('directory', args=[directory.slug])) else: return HttpResponseRedirect(reverse('directory.thank_you')) return render_to_response(template_name, {'directory':directory, 'form':form}, context_instance=RequestContext(request))
def add(request, form_class=MakePaymentForm, template_name="make_payments/add.html"): if request.method == "POST": form = form_class(request.user, request.POST) if form.is_valid(): mp = form.save(commit=False) # we might need to create a user record if not exist if request.user.is_authenticated(): user = request.user else: try: user = User.objects.get(email=mp.email) except: user = request.user if not user.is_anonymous(): mp.user = user mp.creator = user mp.creator_username = user.username mp.save(user) # create invoice invoice = make_payment_inv_add(user, mp) EventLog.objects.log(instance=invoice) # updated the invoice_id for mp, so save again mp.save(user) EventLog.objects.log(instance=mp) # send notification to administrators # get admin notice recipients recipients = get_notice_recipients('module', 'payments', 'paymentrecipients') if recipients: if notification: extra_context = { 'mp': mp, 'invoice': invoice, 'request': request, } notification.send_emails(recipients,'make_payment_added', extra_context) # email to user email_receipt = form.cleaned_data['email_receipt'] if email_receipt: make_payment_email_user(request, mp, invoice) # redirect to online payment or confirmation page if mp.payment_method == 'cc' or mp.payment_method == 'credit card': return HttpResponseRedirect(reverse('payment.pay_online', args=[invoice.id, invoice.guid])) else: return HttpResponseRedirect(reverse('make_payment.add_confirm', args=[mp.id])) else: form = form_class(request.user) # check for initial payment_amount and clean up payment_amount = request.GET.get('payment_amount', 0) try: payment_amount = float(payment_amount) except: payment_amount = 0 if payment_amount > 0: form.fields['payment_amount'].initial = payment_amount # check for initial comment and clean up comments = request.GET.get('comments','') if comments: comments = strip_tags(comments) comments = strip_entities(comments) form.fields['comments'].initial = comments currency_symbol = get_setting("site", "global", "currencysymbol") if not currency_symbol: currency_symbol = "$" return render_to_response(template_name, {'form':form, 'currency_symbol': currency_symbol}, context_instance=RequestContext(request))
def add(request, form_class=DirectoryForm, template_name="directories/add.html"): can_add_active = has_perm(request.user,'directories.add_directory') if not any([request.user.profile.is_superuser, can_add_active, get_setting('module', 'directories', 'usercanadd'), (request.user.profile.is_member and get_setting('module', 'directories', 'directoriesrequiresmembership')) ]): raise Http403 pricings = DirectoryPricing.objects.filter(status=True) if not pricings and has_perm(request.user, 'directories.add_directorypricing'): msg_string = 'You need to add a %s Pricing before you can add %s.' % (get_setting('module', 'directories', 'label_plural'),get_setting('module', 'directories', 'label')) messages.add_message(request, messages.WARNING, _(msg_string)) return HttpResponseRedirect(reverse('directory_pricing.add')) require_payment = get_setting('module', 'directories', 'directoriesrequirespayment') form = form_class(request.POST or None, request.FILES or None, user=request.user) if not require_payment: del form.fields['payment_method'] del form.fields['list_type'] if request.method == "POST": if require_payment: is_free = is_free_listing(request.user, request.POST.get('pricing', 0), request.POST.get('list_type')) if is_free: del form.fields['payment_method'] if form.is_valid(): directory = form.save(commit=False) pricing = form.cleaned_data['pricing'] if require_payment and is_free: directory.payment_method = 'paid - cc' if directory.payment_method: directory.payment_method = directory.payment_method.lower() if not directory.requested_duration: directory.requested_duration = 30 if not directory.list_type: directory.list_type = 'regular' if not directory.slug: directory.slug = '%s-%s' % (slugify(directory.headline), Directory.objects.count()) if not can_add_active: directory.status = True directory.status_detail = 'pending' else: directory.activation_dt = datetime.now() # set the expiration date directory.expiration_dt = directory.activation_dt + timedelta(days=directory.requested_duration) directory = update_perms_and_save(request, form, directory) # create invoice directory_set_inv_payment(request.user, directory, pricing) msg_string = 'Successfully added %s' % directory messages.add_message(request, messages.SUCCESS, _(msg_string)) # send notification to administrators # get admin notice recipients recipients = get_notice_recipients('module', 'directories', 'directoryrecipients') if recipients: if notification: extra_context = { 'object': directory, 'request': request, } notification.send_emails(recipients,'directory_added', extra_context) if directory.payment_method.lower() in ['credit card', 'cc']: if directory.invoice and directory.invoice.balance > 0: return HttpResponseRedirect(reverse('payment.pay_online', args=[directory.invoice.id, directory.invoice.guid])) if can_add_active: return HttpResponseRedirect(reverse('directory', args=[directory.slug])) else: return HttpResponseRedirect(reverse('directory.thank_you')) return render_to_response(template_name, {'form': form, 'require_payment': require_payment}, context_instance=RequestContext(request))
def add(request, form_class=JobForm, template_name="jobs/add.html", object_type=Job, success_redirect='job', thankyou_redirect='job.thank_you'): require_payment = get_setting('module', 'jobs', 'jobsrequirespayment') can_add_active = has_perm(request.user, 'jobs.add_job') content_type = get_object_or_404( ContentType, app_label=object_type._meta.app_label, model=object_type._meta.model_name ) if request.user.profile.is_superuser: category_form_class = CategoryForm else: category_form_class = CategoryForm2 form = form_class(request.POST or None, request.FILES or None, user=request.user) # adjust the fields depending on user type if not require_payment: del form.fields['payment_method'] del form.fields['list_type'] if request.method == "POST": if require_payment: is_free = is_free_listing(request.user, request.POST.get('pricing', 0), request.POST.get('list_type')) if is_free: del form.fields['payment_method'] categoryform = category_form_class( content_type, request.POST,) if form.is_valid() and categoryform.is_valid(): job = form.save(commit=False) pricing = form.cleaned_data['pricing'] if require_payment and is_free: job.payment_method = 'paid - cc' # set it to pending if the user is anonymous or not an admin if not can_add_active: #job.status = 1 job.status_detail = 'pending' # list types and duration if not job.requested_duration: job.requested_duration = 30 if not job.list_type: job.list_type = 'regular' # set up all the times now = datetime.now() job.activation_dt = now if not job.post_dt: job.post_dt = now # set the expiration date job.expiration_dt = job.activation_dt + timedelta( days=job.requested_duration) # semi-anon job posts don't get a slug field on the form # see __init__ method in JobForm if not job.slug: #job.slug = get_job_unique_slug(slugify(job.title)) job.slug = '%s-%s' % (slugify(job.title), object_type.objects.count()) job = update_perms_and_save(request, form, job) # create invoice job_set_inv_payment(request.user, job, pricing) #setup categories category = Category.objects.get_for_object(job, 'category') sub_category = Category.objects.get_for_object( job, 'sub_category') ## update the category of the job category_removed = False category = categoryform.cleaned_data['category'] if category != '0': Category.objects.update(job, category, 'category') else: # remove category_removed = True Category.objects.remove(job, 'category') Category.objects.remove(job, 'sub_category') if not category_removed: # update the sub category of the job sub_category = categoryform.cleaned_data['sub_category'] if sub_category != '0': Category.objects.update(job, sub_category, 'sub_category') else: # remove Category.objects.remove(job,'sub_category') #save relationships job.save() msg_string = 'Successfully added %s' % job messages.add_message(request, messages.SUCCESS,_(msg_string)) # send notification to administrators recipients = get_notice_recipients( 'module', 'jobs', 'jobrecipients') if recipients: if notification: extra_context = { 'object': job, 'request': request, } notification.send_emails(recipients, 'job_added', extra_context) # send user to the payment page if payment is required if require_payment: if job.payment_method.lower() in ['credit card', 'cc']: if job.invoice and job.invoice.balance > 0: return HttpResponseRedirect(reverse( 'payment.pay_online', args=[job.invoice.id, job.invoice.guid]) ) # send user to thank you or view page if request.user.profile.is_superuser: return HttpResponseRedirect( reverse(success_redirect, args=[job.slug])) else: return HttpResponseRedirect(reverse(thankyou_redirect)) else: # Redirect user w/perms to create pricing if none exist pricings = JobPricing.objects.all() if not pricings and has_perm(request.user, 'jobs.add_jobpricing'): msg_string = 'You need to add a %s Pricing before you can add a %s.' % (get_setting('module', 'jobs', 'label_plural'),get_setting('module', 'jobs', 'label')) messages.add_message(request, messages.WARNING, _(msg_string)) return HttpResponseRedirect(reverse('job_pricing.add')) initial_category_form_data = { 'app_label': 'jobs', 'model': 'job', 'pk': 0, #not used for this view but is required for the form } categoryform = category_form_class( content_type, initial=initial_category_form_data,) return render_to_response(template_name, {'form': form, 'require_payment': require_payment, 'categoryform': categoryform}, context_instance=RequestContext(request))
def edit(request, id, form_class=StudyGroupForm, meta_form_class=MetaForm, category_form_class=CategoryForm, template_name="studygroups/edit.html"): study_group = get_object_or_404(StudyGroup, pk=id) if not has_perm(request.user, 'studygroups.change_studygroup', study_group): raise Http403 content_type = get_object_or_404(ContentType, app_label='studygroups', model='studygroup') #setup categories category = Category.objects.get_for_object(study_group, 'category') sub_category = Category.objects.get_for_object(study_group, 'sub_category') initial_category_form_data = { 'app_label': 'studygroups', 'model': 'studygroup', 'pk': study_group.pk, 'category': getattr(category, 'name', '0'), 'sub_category': getattr(sub_category, 'name', '0') } OfficerFormSet = inlineformset_factory(StudyGroup, Officer, form=OfficerForm, extra=1) OfficerFormSet.form = staticmethod( curry(OfficerForm, study_group_group=study_group.group)) if request.method == "POST": form = form_class(request.POST, request.FILES, instance=study_group, user=request.user) metaform = meta_form_class(request.POST, instance=study_group.meta, prefix='meta') categoryform = category_form_class(content_type, request.POST, initial=initial_category_form_data, prefix='category') formset = OfficerFormSet(request.POST, instance=study_group, prefix="officers") if form.is_valid() and metaform.is_valid() and categoryform.is_valid( ) and formset.is_valid(): study_group = form.save(commit=False) # update all permissions and save the model study_group = update_perms_and_save(request, form, study_group) #save meta meta = metaform.save() study_group.meta = meta officers = formset.save() ## update the category of the studygroup category_removed = False category = categoryform.cleaned_data['category'] if category != '0': Category.objects.update(study_group, category, 'category') else: # remove category_removed = True Category.objects.remove(study_group, 'category') Category.objects.remove(study_group, 'sub_category') if not category_removed: # update the sub category of the studygroup sub_category = categoryform.cleaned_data['sub_category'] if sub_category != '0': Category.objects.update(study_group, sub_category, 'sub_category') else: # remove Category.objects.remove(study_group, 'sub_category') #save relationships study_group.save() EventLog.objects.log(instance=study_group) messages.add_message(request, messages.SUCCESS, 'Successfully updated %s' % study_group) if not request.user.profile.is_superuser: # send notification to administrators recipients = get_notice_recipients('module', 'studygroups', 'studygrouprecipients') if recipients: if notification: extra_context = { 'object': study_group, 'request': request, } notification.send_emails(recipients, 'study_group_edited', extra_context) return HttpResponseRedirect( reverse('studygroups.detail', args=[study_group.slug])) else: form = form_class(instance=study_group, user=request.user) metaform = meta_form_class(instance=study_group.meta, prefix='meta') categoryform = category_form_class(content_type, initial=initial_category_form_data, prefix='category') formset = OfficerFormSet(instance=study_group, prefix="officers") #formset.form = staticmethod(curry(OfficerForm, study_group_group=study_group.group)) return render_to_response(template_name, { 'study_group': study_group, 'form': form, 'metaform': metaform, 'categoryform': categoryform, 'formset': formset, }, context_instance=RequestContext(request))
def edit(request, id, form_class=PageForm, meta_form_class=MetaForm, category_form_class=CategoryForm, template_name="pages/edit.html"): page = get_object_or_404(Page, pk=id) if not has_perm(request.user, 'pages.change_page', page): raise Http403 content_type = get_object_or_404(ContentType, app_label='pages', model='page') if request.method == "POST": form = form_class(request.POST, request.FILES, instance=page, user=request.user) # metaform = meta_form_class(request.POST, # instance=page.meta, # prefix='meta') # categoryform = category_form_class(content_type, # request.POST,) if form.is_valid( ): # and metaform.is_valid() and categoryform.is_valid(): page = form.save() # handle header image # f = form.cleaned_data['header_image'] # if f: # header = HeaderImage() # header.content_type = ContentType.objects.get_for_model(Page) # header.object_id = page.id # header.creator = request.user # header.creator_username = request.user.username # header.owner = request.user # header.owner_username = request.user.username # filename = "%s-%s" % (page.slug, f.name) # f.file.seek(0) # header.file.save(filename, f) # page.header_image = header #save meta # meta = metaform.save() # page.meta = meta ## update the category and subcategory # page.update_category_subcategory( # categoryform.cleaned_data['category'], # categoryform.cleaned_data['sub_category'] # ) # update all permissions page = update_perms_and_save(request, form, page) if page.pk == 1: # the about page has id 1 in the npo defaults fixture checklist_update('update-about') messages.add_message( request, messages.SUCCESS, _('Successfully updated %(p)s' % {'p': unicode(page)})) if not request.user.profile.is_superuser: # send notification to administrators recipients = get_notice_recipients('module', 'pages', 'pagerecipients') if recipients: if notification: extra_context = { 'object': page, 'request': request, } notification.send_emails(recipients, 'page_edited', extra_context) return HttpResponseRedirect(reverse('page', args=[page.slug])) else: form = form_class(instance=page, user=request.user) # metaform = meta_form_class(instance=page.meta, prefix='meta') #setup categories # category = Category.objects.get_for_object(page, 'category') # sub_category = Category.objects.get_for_object(page, 'sub_category') # initial_category_form_data = { # 'app_label': 'pages', # 'model': 'page', # 'pk': page.pk, # 'category': getattr(category, 'name', '0'), # 'sub_category': getattr(sub_category, 'name', '0') # } # # categoryform = category_form_class(content_type, # initial=initial_category_form_data,) return render_to_response( template_name, { 'page': page, 'form': form, # 'metaform': metaform, # 'categoryform': categoryform, }, context_instance=RequestContext(request))
def add(request, form_class=PageForm, meta_form_class=MetaForm, category_form_class=CategoryForm, template_name="pages/add.html"): if not has_perm(request.user, 'pages.add_page'): raise Http403 content_type = get_object_or_404(ContentType, app_label='pages', model='page') if request.method == "POST": form = form_class(request.POST, request.FILES, user=request.user) metaform = meta_form_class(request.POST, prefix='meta') categoryform = category_form_class( content_type, request.POST, ) if form.is_valid() and metaform.is_valid() and categoryform.is_valid(): page = form.save() # handle header image # f = form.cleaned_data['header_image'] # if f: # header = HeaderImage() # header.content_type = ContentType.objects.get_for_model(Page) # header.object_id = page.id # header.creator = request.user # header.creator_username = request.user.username # header.owner = request.user # header.owner_username = request.user.username # filename = "%s-%s" % (page.slug, f.name) # f.file.seek(0) # header.file.save(filename, f) # page.header_image = header #save meta meta = metaform.save() page.meta = meta ## update the category and subcategory page.update_category_subcategory( categoryform.cleaned_data['category'], categoryform.cleaned_data['sub_category']) # add all permissions page = update_perms_and_save(request, form, page) messages.add_message( request, messages.SUCCESS, _('Successfully added %(p)s' % {'p': unicode(page)})) checklist_update('add-page') if not request.user.profile.is_superuser: # send notification to administrators recipients = get_notice_recipients('module', 'pages', 'pagerecipients') if recipients: if notification: extra_context = { 'object': page, 'request': request, } notification.send_emails(recipients, 'page_added', extra_context) if page.status and page.status_detail == 'active': return HttpResponseRedirect(reverse('page', args=[page.slug])) return HttpResponseRedirect(reverse('page.search')) else: initial_category_form_data = { 'app_label': 'pages', 'model': 'page', 'pk': 0, } form = form_class(user=request.user) metaform = meta_form_class(prefix='meta') categoryform = category_form_class( content_type, initial=initial_category_form_data, ) return render_to_response(template_name, { 'form': form, 'metaform': metaform, 'categoryform': categoryform, }, context_instance=RequestContext(request))
def add(request, id=None, form_class=SponsorshipForm, template_name="sponsorships/add.html"): use_captcha = get_setting('site', 'global', 'captcha') if request.method == "POST": form = form_class(request.POST, user=request.user, event_id=id) captcha_form = CaptchaForm(request.POST) if not use_captcha: del captcha_form.fields['captcha'] if form.is_valid() and captcha_form.is_valid(): sponsorship = form.save(commit=False) sponsorship.payment_method = sponsorship.payment_method.lower() # we might need to create a user record if not exist if request.user.is_authenticated(): user = request.user else: try: user = User.objects.get(email=sponsorship.email) except: user = request.user if not user.is_anonymous(): sponsorship.user = user sponsorship.creator = user sponsorship.creator_username = user.username else: # this is anonymous user donating and we didn't find their user record in the system, # so add a new user user = User() user.first_name = sponsorship.first_name user.last_name = sponsorship.last_name user.email = sponsorship.email user.username = get_unique_username(user) user.set_password(User.objects.make_random_password(length=8)) user.is_active = 0 user.save() profile_kwarg = {'user':user, 'company':sponsorship.company, 'address':sponsorship.address, 'address2':sponsorship.address2, 'city':sponsorship.city, 'state':sponsorship.state, 'zipcode':sponsorship.zip_code, 'phone':sponsorship.phone} if request.user.is_anonymous(): profile_kwarg['creator'] = user profile_kwarg['creator_username'] = user.username profile_kwarg['owner'] = user profile_kwarg['owner_username'] = user.username else: profile_kwarg['creator'] = request.user profile_kwarg['creator_username'] = request.user.username profile_kwarg['owner'] = request.user profile_kwarg['owner_username'] = request.user.username profile = Profile.objects.create(**profile_kwarg) profile.save() sponsorship.save(user) # create invoice invoice = sponsorship_inv_add(user, sponsorship) # looks for the event an adds it to the sponsorship event = sponsorship_event_add(sponsorship.allocation, sponsorship) # updated the invoice_id for mp, so save again sponsorship.save(user) if request.user.profile.is_superuser: if sponsorship.payment_method in ['paid - check', 'paid - cc']: # the admin accepted payment - mark the invoice paid invoice.tender(request.user) invoice.make_payment(request.user, sponsorship.sponsorship_amount) # send notification to administrators # get admin notice recipients if not sponsorship.payment_method.lower() in ['cc', 'credit card', 'paypal']: # email to admin (if payment type is credit card email is not sent until payment confirmed) recipients = get_notice_recipients('module', 'sponsorships', 'sponsorshipsrecipients') if recipients: if notification: extra_context = { 'sponsorship': sponsorship, 'invoice': invoice, 'request': request, } notification.send_emails(recipients,'sponsorship_added', extra_context) # email to user email_receipt = form.cleaned_data['email_receipt'] if email_receipt: sponsorship_email_user(request, sponsorship, invoice) EventLog.objects.log(instance=sponsorship) # redirect to online payment or confirmation page if sponsorship.payment_method.lower() in ['cc', 'credit card', 'paypal']: return HttpResponseRedirect(reverse('payment.pay_online', args=[invoice.id, invoice.guid])) else: return HttpResponseRedirect(reverse('sponsorship.add_confirm', args=[sponsorship.id])) else: form = form_class(user=request.user, event_id=id) captcha_form = CaptchaForm() currency_symbol = get_setting("site", "global", "currencysymbol") if not currency_symbol: currency_symbol = "$" return render_to_response(template_name, { 'form':form, 'captcha_form' : captcha_form, 'use_captcha' : use_captcha, 'currency_symbol': currency_symbol}, context_instance=RequestContext(request))
def edit(request, id, form_class=CommitteeForm, meta_form_class=MetaForm, category_form_class=CategoryForm, template_name="committees/edit.html"): committee = get_object_or_404(Committee, pk=id) if not has_perm(request.user,'committees.change_committee',committee): raise Http403 content_type = get_object_or_404(ContentType, app_label='committees',model='committee') #setup categories category = Category.objects.get_for_object(committee,'category') sub_category = Category.objects.get_for_object(committee,'sub_category') initial_category_form_data = { 'app_label': 'committees', 'model': 'committee', 'pk': committee.pk, 'category': getattr(category,'name','0'), 'sub_category': getattr(sub_category,'name','0') } OfficerFormSet = inlineformset_factory(Committee, Officer, form=OfficerForm, extra=1) OfficerFormSet.form = staticmethod(curry(OfficerForm, committee_group=committee.group)) if request.method == "POST": form = form_class(request.POST, request.FILES, instance=committee, user=request.user) metaform = meta_form_class(request.POST, instance=committee.meta, prefix='meta') categoryform = category_form_class(content_type, request.POST, initial= initial_category_form_data, prefix='category') formset = OfficerFormSet(request.POST, instance=committee, prefix="officers") if form.is_valid() and metaform.is_valid() and categoryform.is_valid() and formset.is_valid(): committee = form.save(commit=False) # update all permissions and save the model committee = update_perms_and_save(request, form, committee) #save meta meta = metaform.save() committee.meta = meta officers = formset.save() ## update the category of the committee category_removed = False category = categoryform.cleaned_data['category'] if category != '0': Category.objects.update(committee ,category,'category') else: # remove category_removed = True Category.objects.remove(committee ,'category') Category.objects.remove(committee ,'sub_category') if not category_removed: # update the sub category of the committee sub_category = categoryform.cleaned_data['sub_category'] if sub_category != '0': Category.objects.update(committee, sub_category,'sub_category') else: # remove Category.objects.remove(committee,'sub_category') #save relationships committee.save() EventLog.objects.log(instance=committee) messages.add_message(request, messages.SUCCESS, 'Successfully updated %s' % committee) if not request.user.profile.is_superuser: # send notification to administrators recipients = get_notice_recipients('module', 'committees', 'committeerecipients') if recipients: if notification: extra_context = { 'object': committee, 'request': request, } notification.send_emails(recipients, 'committee_edited', extra_context) return HttpResponseRedirect(reverse('committees.detail', args=[committee.slug])) else: form = form_class(instance=committee, user=request.user) metaform = meta_form_class(instance=committee.meta, prefix='meta') categoryform = category_form_class(content_type, initial=initial_category_form_data, prefix='category') formset = OfficerFormSet(instance=committee, prefix="officers") #formset.form = staticmethod(curry(OfficerForm, committee_group=committee.group)) return render_to_response(template_name, { 'committee': committee, 'form': form, 'metaform': metaform, 'categoryform': categoryform, 'formset': formset, }, context_instance=RequestContext(request))
def add( request, form_class=PageForm, meta_form_class=MetaForm, category_form_class=CategoryForm, template_name="pages/add.html", ): if not has_perm(request.user, "pages.add_page"): raise Http403 content_type = get_object_or_404(ContentType, app_label="pages", model="page") if request.method == "POST": form = form_class(request.POST, request.FILES, user=request.user) metaform = meta_form_class(request.POST, prefix="meta") categoryform = category_form_class(content_type, request.POST, prefix="category") if form.is_valid() and metaform.is_valid() and categoryform.is_valid(): page = form.save() # handle header image f = form.cleaned_data["header_image"] if f: header = HeaderImage() header.content_type = ContentType.objects.get_for_model(Page) header.object_id = page.id header.creator = request.user header.creator_username = request.user.username header.owner = request.user header.owner_username = request.user.username filename = "%s-%s" % (page.slug, f.name) f.file.seek(0) header.file.save(filename, f) page.header_image = header # save meta meta = metaform.save() page.meta = meta ## update the category and subcategory page.update_category_subcategory( categoryform.cleaned_data["category"], categoryform.cleaned_data["sub_category"] ) # add all permissions page = update_perms_and_save(request, form, page) messages.add_message(request, messages.SUCCESS, _("Successfully added %(p)s" % {"p": unicode(page)})) checklist_update("add-page") if not request.user.profile.is_superuser: # send notification to administrators recipients = get_notice_recipients("module", "pages", "pagerecipients") if recipients: if notification: extra_context = {"object": page, "request": request} notification.send_emails(recipients, "page_added", extra_context) if page.status and page.status_detail == "active": return HttpResponseRedirect(reverse("page", args=[page.slug])) return HttpResponseRedirect(reverse("page.search")) else: initial_category_form_data = {"app_label": "pages", "model": "page", "pk": 0} form = form_class(user=request.user) metaform = meta_form_class(prefix="meta") categoryform = category_form_class(content_type, initial=initial_category_form_data, prefix="category") return render_to_response( template_name, {"form": form, "metaform": metaform, "categoryform": categoryform}, context_instance=RequestContext(request), )
def add(request, form_class=CommitteeForm, meta_form_class=MetaForm, category_form_class=CategoryForm, template_name="committees/add.html"): if not has_perm(request.user,'committees.add_committee'): raise Http403 content_type = get_object_or_404(ContentType, app_label='committees',model='committee') #OfficerFormSet = inlineformset_factory(Committee, Officer, form=OfficerForm, extra=1) if request.method == 'POST': form = form_class(request.POST, request.FILES, user=request.user) metaform = meta_form_class(request.POST, prefix='meta') categoryform = category_form_class(content_type, request.POST, prefix='category') #formset = OfficerFormSet(request.POST, prefix="officers") if form.is_valid() and metaform.is_valid() and categoryform.is_valid(): committee = form.save(commit=False) committee = update_perms_and_save(request, form, committee) #save meta meta = metaform.save() committee.meta = meta #setup categories category = Category.objects.get_for_object(committee,'category') sub_category = Category.objects.get_for_object(committee,'sub_category') ## update the category of the committee category_removed = False category = categoryform.cleaned_data['category'] if category != '0': Category.objects.update(committee ,category,'category') else: # remove category_removed = True Category.objects.remove(committee ,'category') Category.objects.remove(committee ,'sub_category') if not category_removed: # update the sub category of the committee sub_category = categoryform.cleaned_data['sub_category'] if sub_category != '0': Category.objects.update(committee, sub_category,'sub_category') else: # remove Category.objects.remove(committee,'sub_category') #save relationships committee.save() EventLog.objects.log() messages.add_message(request, messages.SUCCESS, 'Successfully added %s' % committee) if not request.user.profile.is_superuser: # send notification to administrators recipients = get_notice_recipients('module', 'committees', 'committeerecipients') if recipients: if notification: extra_context = { 'object': committee, 'request': request, } notification.send_emails(recipients,'committee_added', extra_context) return HttpResponseRedirect(reverse('committees.detail', args=[committee.slug])) else: initial_category_form_data = { 'app_label': 'committees', 'model': 'committee', 'pk': 0, #not used for this view but is required for the form } form = form_class(user=request.user) metaform = meta_form_class(prefix='meta') categoryform = category_form_class(content_type, initial=initial_category_form_data, prefix='category') return render_to_response(template_name, { 'form':form, 'metaform':metaform, 'categoryform':categoryform, }, context_instance=RequestContext(request))
def add(request, form_class=StudyGroupForm, meta_form_class=MetaForm, category_form_class=CategoryForm, template_name="studygroups/add.html"): if not has_perm(request.user, 'studygroups.add_studygroup'): raise Http403 content_type = get_object_or_404(ContentType, app_label='studygroups', model='studygroup') #OfficerFormSet = inlineformset_factory(StudyGroup, Officer, form=OfficerForm, extra=1) if request.method == 'POST': form = form_class(request.POST, request.FILES, user=request.user) metaform = meta_form_class(request.POST, prefix='meta') categoryform = category_form_class(content_type, request.POST, prefix='category') #formset = OfficerFormSet(request.POST, prefix="officers") if form.is_valid() and metaform.is_valid() and categoryform.is_valid(): study_group = form.save(commit=False) study_group = update_perms_and_save(request, form, study_group) #save meta meta = metaform.save() study_group.meta = meta #setup categories category = Category.objects.get_for_object(study_group, 'category') sub_category = Category.objects.get_for_object( study_group, 'sub_category') ## update the category of the studygroup category_removed = False category = categoryform.cleaned_data['category'] if category != '0': Category.objects.update(study_group, category, 'category') else: # remove category_removed = True Category.objects.remove(study_group, 'category') Category.objects.remove(study_group, 'sub_category') if not category_removed: # update the sub category of the studygroup sub_category = categoryform.cleaned_data['sub_category'] if sub_category != '0': Category.objects.update(study_group, sub_category, 'sub_category') else: # remove Category.objects.remove(study_group, 'sub_category') #save relationships study_group.save() EventLog.objects.log() messages.add_message(request, messages.SUCCESS, 'Successfully added %s' % study_group) if not request.user.profile.is_superuser: # send notification to administrators recipients = get_notice_recipients('module', 'studygroups', 'studygrouprecipients') if recipients: if notification: extra_context = { 'object': study_group, 'request': request, } notification.send_emails(recipients, 'study_group_added', extra_context) return HttpResponseRedirect( reverse('studygroups.detail', args=[study_group.slug])) else: initial_category_form_data = { 'app_label': 'studygroups', 'model': 'studygroup', 'pk': 0, #not used for this view but is required for the form } form = form_class(user=request.user) metaform = meta_form_class(prefix='meta') categoryform = category_form_class(content_type, initial=initial_category_form_data, prefix='category') return render_to_response(template_name, { 'form': form, 'metaform': metaform, 'categoryform': categoryform, }, context_instance=RequestContext(request))