def phone_update(sender, instance, **kwargs): # quick hack to see if the address (instance.content_object) is connected to a MemberProfile if hasattr(instance.content_object, 'user2'): memberprofile = instance.content_object user = memberprofile.user2 profile = get_object_or_none(TrackingProfile, user=user) if not profile: return profile_pickle = pickle.dumps(profile.to_dict()) # this address is already in the rolodex; just update it phone = get_object_or_none(Phone, myewbphone=instance) if phone: phone.phone = instance.number phone.save() # add new address to rolodex else: phoneddress = Phone.objects.create(phone=instance.number, profile = profile, myewbphone=instance) history = ProfileHistory.objects.create(profile=profile, editor=user, revision=profile_pickle)
def address_update(sender, instance, **kwargs): # quick hack to see if the address (instance.content_object) is connected to a MemberProfile if hasattr(instance.content_object, 'user2'): memberprofile = instance.content_object user = memberprofile.user2 profile = get_object_or_none(TrackingProfile, user=user) if not profile: return profile_pickle = pickle.dumps(profile.to_dict()) # this address is already in the rolodex; just update it address = get_object_or_none(Address, myewbaddress=instance) if address: address.address = "%s\n%s %s\n%s\n%s" % (instance.street, instance.city, instance.province, instance.postal_code, instance.country) address.save() # add new address to rolodex else: address = Address.objects.create(address = "%s\n%s %s\n%s\n%s" % (instance.street, instance.city, instance.province, instance.postal_code, instance.country), profile = profile, myewbaddress=instance) # update rolodex profile city too? if not profile.city and instance.city: profile.city = instance.city profile.save() history = ProfileHistory.objects.create(profile=profile, editor=user, revision=profile_pickle)
def clean(self, value): value = super(AutocompleteField, self).clean(value) if self.multi: objects = [] for v in value.split(','): v = v.strip() if v: obj = get_object_or_none(self.model, name=v) if obj: objects.append(obj) elif self.create: obj = self.model(name=v) obj.save() objects.append(obj) else: raise forms.ValidationError("Invalid choice") return objects elif value: obj = get_object_or_none(self.model, name=value) if obj: return obj if self.create: obj = self.model(name=value) obj.save() return obj else: raise forms.ValidationError("Invalid choice") return None
def clean(self, value): value = super(AutocompleteField, self).clean(value) if self.multi: objects = [] for v in value.split(','): v = v.strip() if v: obj = get_object_or_none(self.model, name=v) if obj: objects.append(obj) elif self.create: obj = self.model(name=v) obj.save() objects.append(obj) else: raise forms.ValidationError("Invalid choice") return objects elif value: obj = get_object_or_none(self.model, name=value) if obj: return obj if self.create: obj = self.model(name=value) obj.save() return obj else: raise forms.ValidationError("Invalid choice") return None
def get_address_or_404(user, label): profile = user.get_profile() content_type = ContentType.objects.get_for_model(profile) address = get_object_or_none(Address, content_type__pk=content_type.id, object_id=profile.id, label=label) if not address: address = get_object_or_none(Address, content_type__pk=content_type.id, object_id=profile.id, id=label) # TODO: if address is None: return 404 return address
def custom_fields(request): if not perm(request): return HttpResponseRedirect(reverse('rolodex_login')) form = CustomFieldForm() if request.method == 'POST': if request.POST.get('action', None) == 'add': form = CustomFieldForm(request.POST) if form.is_valid(): field = form.save(commit=False) field.owner = request.user field.save() request.user.message_set.create(message='Field added.') return HttpResponseRedirect(reverse('rolodex_custom_fields')) elif request.POST.get('action', None) == 'update': field = get_object_or_none(CustomField, id=request.POST['field_id']) if field and (field.visibility == 'everyone' or (field.visibility == 'private' and field.owner == request.user)): form = CustomFieldForm(request.POST, instance=field) if form.is_valid(): field = form.save() request.user.message_set.create(message='Field updated.') return HttpResponseRedirect(reverse('rolodex_custom_fields')) elif request.POST.get('action', None) == 'delete' & request.POST.get('field_id', None): field = get_object_or_none(CustomField, id=request.POST['field_id']) if field and (field.visibility == 'everyone' or (field.visibility == 'private' and field.owner == request.user)): field.delete() request.user.message_set.create(message='Field deleted.') return HttpResponseRedirect(reverse('rolodex_custom_fields')) qry = Q(visibility='anyone') | (Q(visibility='private') & Q(owner=request.user)) fields = CustomField.objects.filter(qry).order_by('name') badges = Badge.objects.all() flags = Flag.objects.all() return render_to_response("rolodex/custom_fields.html", {'fields': fields, 'badges': badges, 'flags': flags}, context_instance=RequestContext(request))
def email_delete(sender, instance, **kwargs): user = instance.user profile = get_object_or_none(TrackingProfile, user=user) if not profile: return profile_pickle = pickle.dumps(profile.to_dict()) email = get_object_or_none(Email, myewbemail=instance) if email: email.delete() history = ProfileHistory.objects.create(profile=profile, editor=user, revision=profile_pickle)
def dashboard(self, user): u = get_object_or_none(User, username=user) if u: filter1 = Q(user=u) filter2 = Q(dashboard=True) | Q(is_admin=True) mrecords = GroupMember.objects.filter(filter1, filter2) groups = [] for m in mrecords: if m.group not in groups: groups.append(m.group) chapter = u.get_profile().get_chapter() if chapter: chapter = BaseGroup.objects.get(slug=chapter.slug) if chapter and chapter not in groups: groups.insert(0, chapter) return groups #return self.get_query_set().filter(member_users=u, # groupmember__dashboard=True) else: return []
def removal_notice(self, resource, user): m = get_object_or_none(Membership, collection=self, resource=resource) if not m: curator = self.owner message = render_to_string( "library/emails/removal.html", {"resource": resource, "collection": self, "user": user} ) ctx = { "body": message, "title": "Recommendation for your EWB Library collection", "topic_id": None, "event": None, "attachments": None, } sender = "myEWB <*****@*****.**>" send_mail( subject="Recommendation for your EWB Library collection", txtMessage=None, htmlMessage=message, fromemail=sender, recipients=[curator.email], context=ctx, content_object=self, ) return True return False
def user_update(sender, instance, created=None, **kwargs): user = instance profile = get_object_or_none(TrackingProfile, user=user) if profile: modified = False profile_pickle = pickle.dumps(profile.to_dict()) if profile.primary_email() != user.email: profile.update_email(user.email) modified = True if profile.first_name != user.first_name: profile.first_name = user.first_name modified = True if profile.last_name != user.last_name: profile.last_name = user.last_name modified = True if modified: profile.save() history = ProfileHistory.objects.create(profile=profile, editor=user, revision=profile_pickle) else: profile = TrackingProfile.objects.create(user=user, profile=user.get_profile(), first_name=user.first_name, last_name=user.last_name, updated_by=user) profile.update_email(user.email)
def evaluation_interview_answer(request, app_id): application = get_object_or_404(Application, id=app_id) if request.method == 'POST': if request.POST.get('key', None): key = request.POST.get('key', None) question = get_object_or_404(InterviewQuestion, id=key, session=application.session) comment = request.POST.get('comment', None) if comment: answer, created = Answer.objects.get_or_create( application=application, question=question) answer.answer = comment answer.save() else: answer = get_object_or_none(Answer, application=application, question=question) if answer: answer.delete() return HttpResponse("success") elif request.is_ajax(): answers = Answer.objects.filter(application=application) json = serializers.get_serializer('json')() response = HttpResponse(mimetype='application/json') json.serialize(comments, stream=response) return response return HttpResponse("invalid")
def browse_event(request, event_id=None): if not event_id and not request.POST.get('event', None): request.user.message_set.create(message='Enter an event into the search') return HttpResponseRedirect(reverse('rolodex_home')) if not event_id: #events = Event.objects.filter(name__icontains=request.POST['event']).order_by('-date') # support space-deliminated search terms qry = Q(name__icontains=request.POST['event'].split()[0]) for term in request.POST['event'].split()[1:]: qry = qry & Q(name__icontains=term) events = Event.objects.filter(qry).order_by('-date') if events.count() == 1: return HttpResponseRedirect(reverse('rolodex_browse_event', \ kwargs={'event_id': events[0].id})) return render_to_response("rolodex/browse_event_search.html", {'events': events}, context_instance=RequestContext(request)) event = get_object_or_none(Event, id=event_id) results = EventAttendance.objects.filter(event=event) results = results.order_by('profile__last_name') return render_to_response("rolodex/browse_event.html", {'event': event, 'results': results}, context_instance=RequestContext(request))
def browse_chapter(request, chapter=None): if request.GET.get('chapter') and not chapter: chapter = request.GET['chapter'] return HttpResponseRedirect(reverse('rolodex_browse_chapter', \ kwargs={'chapter': chapter})) chapter = get_object_or_none(Network, slug=chapter) if not chapter: request.user.message_set.create(message='Chapter not found') return HttpResponseRedirect(reverse('rolodex_home')) results = TrackingProfile.objects.filter(chapter=chapter) filters = request.GET.get('filters', '') if filters: if filters == 'role': results = results.filter(profilebadge__current=True, profilebadge__active=True).distinct() if filters == 'past': results = results.filter(profilebadge__current=False, profilebadge__active=True).distinct() if filters == 'flag': results = results.filter(profileflag__active=True).distinct() results = results.order_by('last_name') return render_to_response("rolodex/browse_chapter.html", {'chapter': chapter, 'results': results, 'filters': filters}, context_instance=RequestContext(request))
def group_join(sender, instance, created, **kwargs): user = instance.user group = instance.group profile = get_object_or_none(TrackingProfile, user=user) if not profile: return # messy hack. but what the heck, it'll work... badge = None if group.slug == 'exec': badge = Badge.objects.get(name='Exec') elif group.slug == 'presidents' or group.slug == 'citynetworkpres': badge = Badge.objects.get(name='President') if badge: pb = ProfileBadge.objects.filter(profile=profile, badge=badge, active=True, current=True) if not pb.count(): ProfileBadge.objects.create(profile=profile, badge=badge, added_by=user, note='Automatic addition - sync from myEWB') # basically... "if they're a chapter exec, update their title" if instance.is_admin and hasattr(group, 'network'): if profile.chapter != group.network or profile.role != instance.admin_title: profile_pickle = pickle.dumps(profile.to_dict()) profile.chapter = group.network profile.role = instance.admin_title profile.save() history = ProfileHistory.objects.create(profile=profile, editor=user, revision=profile_pickle)
def resume(request): registration = get_object_or_none(ConferenceRegistration, user=request.user, submitted=True, cancelled=False) if not registration: request.user.message_set.create("You aren't registered for conference...") return HttpResponseRedirect(reverse('confreg')) if request.method == 'POST': form = ConferenceResumeForm(request.POST, request.FILES) if form.is_valid(): resume = Attachment() resume.creator = request.user resume.content_type = ContentType.objects.get_for_model(registration) resume.object_id = registration.id resume.attachment_file = form.cleaned_data['resume'] resume.save() request.user.message_set.create(message="Thank you!") return HttpResponseRedirect(reverse('confreg')) else: form = ConferenceResumeForm() return render_to_response('conference/resume.html', {'registration': registration, 'form': form, 'user': request.user, }, context_instance=RequestContext(request) )
def preview(request, workspace_id): workspace = get_object_or_404(Workspace, id=workspace_id) if request.method == 'POST' and request.POST.get('dir', None): # load up the requested file file = WorkspaceFile.objects.load(workspace, request.POST['dir']) if file: # check to see if we want a past revision rev_id = request.POST.get('revision', None) if rev_id and rev_id != 'current': revision = get_object_or_none(WorkspaceRevision, id=rev_id, workspace=workspace, parent_file=file) if revision: file = revision.get_file() # normalize the extension ext = file.get_extension() if preview_aliases.get(ext, None): ext = preview_aliases[ext] # load up the preview template if ext in preview_extensions: return render_to_response("workspace/preview/%s.html" % ext, {'file': file, 'workspace': workspace}, context_instance=RequestContext(request)) return HttpResponse("preview not available")
def get_address_or_404(user, label): profile = user.get_profile() content_type = ContentType.objects.get_for_model(profile) address = get_object_or_none(Address, content_type__pk=content_type.id, object_id=profile.id, label=label) if not address: address = get_object_or_none(Address, content_type__pk=content_type.id, object_id=profile.id, id=label) # TODO: if address is None: return 404 return address
def evaluation_interview_answer(request, app_id): application = get_object_or_404(Application, id=app_id) if request.method == 'POST': if request.POST.get('key', None): key = request.POST.get('key', None) question = get_object_or_404(InterviewQuestion, id=key, session=application.session) comment = request.POST.get('comment', None) if comment: answer, created = Answer.objects.get_or_create(application=application, question=question) answer.answer = comment answer.save() else: answer = get_object_or_none(Answer, application=application, question=question) if answer: answer.delete() return HttpResponse("success") elif request.is_ajax(): answers = Answer.objects.filter(application=application) json = serializers.get_serializer('json')() response = HttpResponse(mimetype='application/json') json.serialize(comments, stream=response) return response return HttpResponse("invalid")
def evaluation_comment(request, app_id): application = get_object_or_404(Application, id=app_id) if request.method == 'POST': if request.POST.get('key', None): key = request.POST.get('key', None) comment = request.POST.get('comment', None) if comment: evalcomment, created = EvaluationComment.objects.get_or_create(evaluation=application.evaluation, key=key) evalcomment.comment = comment evalcomment.save() else: comment = get_object_or_none(EvaluationComment, evaluation=application.evaluation, key=key) if comment: comment.delete() return HttpResponse("success") elif request.is_ajax(): comments = EvaluationComment.objects.filter(evaluation=application.evaluation) json = serializers.get_serializer('json')() response = HttpResponse(mimetype='application/json') json.serialize(comments, stream=response) return response return HttpResponse("invalid")
def is_exec(request): """ Sets a flag for whether a user is a chapter exec member """ user = request.user if user.is_staff or user.is_superuser: return {'is_exec': True} ctx = {'is_exec': False} if user.is_authenticated(): cache_key = "is_exec_%s" % user.username is_exec = cache.get(cache_key) if is_exec is None: # wrapped "get" since this needs sample data to be loaded execlist = get_object_or_none(Community, slug='exec') if execlist and execlist.user_is_member(user): is_exec = True else: is_exec = False cache.set(cache_key, is_exec, 5*60) ctx['is_exec'] = is_exec return ctx
def is_exec(request): """ Sets a flag for whether a user is a chapter exec member """ user = request.user if user.is_staff or user.is_superuser: return {'is_exec': True} ctx = {'is_exec': False} if user.is_authenticated(): cache_key = "is_exec_%s" % user.username is_exec = cache.get(cache_key) if is_exec is None: # wrapped "get" since this needs sample data to be loaded execlist = get_object_or_none(Community, slug='exec') if execlist and execlist.user_is_member(user): is_exec = True else: is_exec = False cache.set(cache_key, is_exec, 5 * 60) ctx['is_exec'] = is_exec return ctx
def evaluation_comment(request, app_id): application = get_object_or_404(Application, id=app_id) if request.method == 'POST': if request.POST.get('key', None): key = request.POST.get('key', None) comment = request.POST.get('comment', None) if comment: evalcomment, created = EvaluationComment.objects.get_or_create( evaluation=application.evaluation, key=key) evalcomment.comment = comment evalcomment.save() else: comment = get_object_or_none(EvaluationComment, evaluation=application.evaluation, key=key) if comment: comment.delete() return HttpResponse("success") elif request.is_ajax(): comments = EvaluationComment.objects.filter( evaluation=application.evaluation) json = serializers.get_serializer('json')() response = HttpResponse(mimetype='application/json') json.serialize(comments, stream=response) return response return HttpResponse("invalid")
def get_organization_role(user): ctx = { 'role_chapter_member': False, 'role_is_exec': False, 'role_is_president': False, 'role_is_jf': False, 'role_is_aps': False, 'role_is_office': False, 'role_is_alumni': False, 'role_is_guest': True } if user.is_authenticated(): ctx['role_is_guest'] = False cache_key = "role_breakdown_%s" % user.username roles = cache.get(cache_key) if roles is None: # wrapped "get" since this needs sample data to be loaded execlist = get_object_or_none(Community, slug='exec') if execlist and execlist.user_is_member(user): ctx['role_is_exec'] = True preslist = get_object_or_none(Community, slug='Presidents') if preslist and preslist.user_is_member(user): ctx['role_is_president'] = True else: preslist = get_object_or_none(Community, slug='citynetworkpres') if preslist and preslist.user_is_member(user): ctx['role_is_president'] = True officelist = get_object_or_none(BaseGroup, slug='natloffice') if officelist and officelist.user_is_member(user): ctx['role_is_office'] = True if execlist and not ctx['role_is_exec']: alumni = GroupMemberRecord.objects.filter(user=user, group=execlist) if alumni.count(): ctx['role_is_alumni'] = True cache.set(cache_key, ctx, 5 * 60) return ctx
def phone_delete(sender, instance, **kwargs): if hasattr(instance.content_object, 'user2'): memberprofile = instance.content_object user = memberprofile.user2 profile = get_object_or_none(TrackingProfile, user=user) if not profile: return profile_pickle = pickle.dumps(profile.to_dict()) phone = get_object_or_none(Phone, myewbphone=instance) if phone: phone.delete() history = ProfileHistory.objects.create(profile=profile, editor=user, revision=profile_pickle)
def flag_view_ajax(request, flag_id): if not perm(request): return HttpResponseRedirect(reverse('rolodex_login')) flag = get_object_or_none(ProfileFlag, id=flag_id) return render_to_response("rolodex/flag_view_ajax.html", {'flag': flag}, context_instance=RequestContext(request))
def badge_view_ajax(request, badge_id): if not perm(request): return HttpResponseRedirect(reverse('rolodex_login')) badge = get_object_or_none(ProfileBadge, id=badge_id) return render_to_response("rolodex/badge_view_ajax.html", {'badge': badge}, context_instance=RequestContext(request))
def note_view_ajax(request, note_id): if not perm(request): return HttpResponseRedirect(reverse('rolodex_login')) note = get_object_or_none(Interaction, id=note_id) return render_to_response("rolodex/note_view_ajax.html", {'note': note}, context_instance=RequestContext(request))
def get_organization_role(user): ctx = {'role_chapter_member': False, 'role_is_exec': False, 'role_is_president': False, 'role_is_jf': False, 'role_is_aps': False, 'role_is_office': False, 'role_is_alumni': False, 'role_is_guest': True} if user.is_authenticated(): ctx['role_is_guest'] = False cache_key = "role_breakdown_%s" % user.username roles = cache.get(cache_key) if roles is None: # wrapped "get" since this needs sample data to be loaded execlist = get_object_or_none(Community, slug='exec') if execlist and execlist.user_is_member(user): ctx['role_is_exec'] = True preslist = get_object_or_none(Community, slug='Presidents') if preslist and preslist.user_is_member(user): ctx['role_is_president'] = True else: preslist = get_object_or_none(Community, slug='citynetworkpres') if preslist and preslist.user_is_member(user): ctx['role_is_president'] = True officelist = get_object_or_none(BaseGroup, slug='natloffice') if officelist and officelist.user_is_member(user): ctx['role_is_office'] = True if execlist and not ctx['role_is_exec']: alumni = GroupMemberRecord.objects.filter(user=user, group=execlist) if alumni.count(): ctx['role_is_alumni'] = True cache.set(cache_key, ctx, 5*60) return ctx
def note_unpin(request, note_id): if not perm(request): return HttpResponseRedirect(reverse('rolodex_login')) note = get_object_or_none(Interaction, id=note_id) if note.pinned: note.pinned = False note.save() request.user.message_set.create(message='Un-pinned') return HttpResponseRedirect(reverse('rolodex_view', kwargs={'profile_id': note.profile.id}))
def parse_recipient(recipient): pattern = '(?:.*<)?([^>@]*)@my.ewb.ca(?:>.*)?' # TODO: un-hardcode the my.ewb.ca domain! slug = re.findall(pattern, recipient) if len(slug): group = get_object_or_none(BaseGroup, slug=slug[0]) if group: return group # TODO: modify to handle private-message replies raise BounceException("I wasn't able to figure out which group you want to post to! %s didn't make any sense to me." % recipient)
def remove_resource(self, resource, user=None): m = get_object_or_none(Membership, collection=self, resource=resource) if m: orderings = Membership.objects.filter(collection=self, ordering__gt=m.ordering) m.delete() for o in orderings: o.ordering = o.ordering - 1 o.save() Activity.objects.create(resource=resource, user=user, activity_type="decollect", content_object=self) return True
def email_update(sender, instance, **kwargs): if not instance.verified: return user = instance.user profile = get_object_or_none(TrackingProfile, user=user) if not profile: return profile_pickle = pickle.dumps(profile.to_dict()) # this address is already in the rolodex; just update it email = get_object_or_none(Email, myewbemail=instance) if email: email.email = instance.email email.save() else: email = get_object_or_none(Email, email=instance.email) # or, is the address there, but not linked to the myEWB object? if email: email.myewbemail=instance email.save() # add new address to rolodex else: email = Email.objects.create(email=instance.email, profile = profile, myewbemail=instance) if instance.primary: profile.update_email(instance.email) history = ProfileHistory.objects.create(profile=profile, editor=user, revision=profile_pickle)
def clean(self, value): value = super(AutocompleteField, self).clean(value) obj = get_object_or_none(self.model, name=value) if obj: return obj if self.create: obj = self.model(name=value) obj.save() return obj else: raise forms.ValidationError("Invalid choice")
def update_phone(self, phone): if phone: phone_obj = get_object_or_none(Phone, phone=phone, profile=self) if not phone_obj: phone_obj = Phone.objects.create(phone=phone, profile=self, updated=datetime.now()) if not phone_obj.primary: other_phones = Phone.objects.filter(profile=self) for e in other_phones: e.primary = False e.save() phone_obj.primary = True phone_obj.save()
def update_email(self, email): if email: email_obj = get_object_or_none(Email, email=email, profile=self) if not email_obj: email_obj = Email.objects.create(email=email, profile=self, updated=datetime.now()) if not email_obj.primary: other_emails = Email.objects.filter(profile=self) for e in other_emails: e.primary = False e.save() email_obj.primary = True email_obj.save()
def email_forwards_delete(request, group_slug, fwd_id): network = get_object_or_404(Network, slug=group_slug) # no need for security check: the get_ob ject_or_404 will fail since it's # impossible to create a non-chapter-forward in the first place if request.method == "POST": fwd = get_object_or_404(EmailForward, id=fwd_id, network=network) email = get_object_or_none(EmailAddress, email=fwd.address) fwd.delete() if email: email.delete() request.user.message_set.create(message="Deleted") #should template-ize? return HttpResponseRedirect(reverse('email_forwards_index', kwargs={'group_slug': group_slug}))
def newf(request, *args, **kwargs): user = request.user if user.has_module_perms("base_groups"): return f(request, *args, **kwargs) if not user.is_authenticated(): # deny access - would set this to redirect # to a custom template eventually return render_to_response('denied.html', context_instance=RequestContext(request)) execlist = get_object_or_none(Community, slug='exec') if execlist and execlist.user_is_member(user): return f(request, *args, **kwargs) return render_to_response('denied.html', context_instance=RequestContext(request))
def email_forwards_delete(request, group_slug, fwd_id): network = get_object_or_404(Network, slug=group_slug) # no need for security check: the get_ob ject_or_404 will fail since it's # impossible to create a non-chapter-forward in the first place if request.method == "POST": fwd = get_object_or_404(EmailForward, id=fwd_id, network=network) email = get_object_or_none(EmailAddress, email=fwd.address) fwd.delete() if email: email.delete() request.user.message_set.create( message="Deleted") #should template-ize? return HttpResponseRedirect( reverse('email_forwards_index', kwargs={'group_slug': group_slug}))
def create_queryset(user): # ideally we'd do it this way, and not mention specific models here # (instead doing visibility checking in their respective search_index.py files), # but there's no way to pass a user into serach_index.load_all_queryset. yet. # # return RelatedSearchQuerySet() qs = RelatedSearchQuerySet().load_all_queryset( GroupTopic, GroupTopic.objects.visible(user)) qs = qs.load_all_queryset(Whiteboard, Whiteboard.objects.visible(user)) qs = qs.load_all_queryset(Event, Event.objects.visible(user)) # TODO: centralize this somewhere? execlist = get_object_or_none(Community, slug='exec') if execlist and execlist.user_is_member(user, True): qs = qs.load_all_queryset(Activity, Activity.objects.all()) else: qs = qs.load_all_queryset(Activity, Activity.objects.none()) return qs
def lookup_code(request): if request.user.has_module_perms('conference'): if request.method == 'POST' and request.POST.get('code', None): code = get_object_or_none(ConferenceCode, code=request.POST['code']) if code and code.expired: return HttpResponse("voided") elif code: reg = ConferenceRegistration.objects.filter(code=code, cancelled=False) if reg.count(): return HttpResponse("used") else: return HttpResponse("available") else: if ConferenceCode.isValid(request.POST['code']): return HttpResponse("not issued") else: return HttpResponse("invalid code") return HttpResponse("lookup error")
def filters_save(request): if request.method == 'POST': kwargs = {} kwargs['user'] = request.user if request.POST.get('deadline', None) and request.POST.get( 'deadline2', None): kwargs['deadline_comparison'] = request.POST['deadline'] kwargs['deadline'] = request.POST['deadline2'] if request.POST.get('urgency', None) and request.POST.get( 'urgency2', None): kwargs['urgency_comparison'] = request.POST['urgency'] kwargs['urgency'] = request.POST['urgency2'] if request.POST.get('skills', None) and request.POST.get( 'skills2', None): kwargs['skills_comparison'] = request.POST['skills'] if request.POST.get('location', None) and request.POST.get( 'location2', None): kwargs['location_comparison'] = request.POST['location'] if request.POST.get('time_required', None) and request.POST.get( 'time_required2', None): kwargs['time_required_comparison'] = request.POST['time_required'] kwargs['time_required'] = request.POST['time_required2'] if request.POST.get('search', None): kwargs['search'] = request.POST['search'] filter = JobFilter.objects.filter(**kwargs) skills = [] for s in request.POST.getlist('skills2'): skill = get_object_or_none(Skill, id=s) if skill: skills.append(skill) filter = filter.filter(skills=skill) if request.POST.get('skills', None) and request.POST.get( 'skills2', None): filter = filter.exclude(~Q(skills__in=skills)) locations = [] for l in request.POST.getlist('location2'): location = get_object_or_none(Location, id=l) if location: locations.append(location) filter = filter.filter(location=location) if request.POST.get('location', None) and request.POST.get( 'location2', None): filter = filter.exclude(~Q(location__in=locations)) if filter.count(): filter = filter[0] else: filter = JobFilter.objects.create(**kwargs) for s in skills: filter.skills.add(s) for l in locations: filter.location.add(l) filter.name = request.POST.get('name', '') if request.POST.get('email', None): filter.email = True else: filter.email = False filter.save() return HttpResponse("success") else: return render_to_response("jobboard/filters_save.html", {}, context_instance=RequestContext(request))
def done(self, request, cleaned_data): #product = Product.objects.get(sku=cleaned_data['products']) address = get_object_or_none(Address, pk=cleaned_data['address']) if not address or not request.user.get_profile() == address.content_object: address = Address() address.street = '366 Adelaide' address.city = 'Toronto' address.province = 'ON' address.postal_code = 'M5V1R9' address.country = 'CA' # stuff necessary values into dictionary... to be encoded. param = {'trnCardOwner': cleaned_data['billing_name'], 'trnCardNumber': cleaned_data['cc_number'], 'trnExpMonth': cleaned_data['cc_expiry'].split('/')[0], 'trnExpYear': cleaned_data['cc_expiry'].split('/')[1], 'ordName': cleaned_data['billing_name'], 'ordEmailAddress': cleaned_data['email'], 'ordPhoneNumber': cleaned_data['phone'], 'ordAddress1': address.street, 'ordAddress2': '', 'ordCity':address.city, 'ordProvince': address.province, 'ordPostalCode': address.postal_code, 'ordCountry': address.country, 'requestType': 'BACKEND', 'trnOrderNumber': '%s' % int(time.time()), 'merchant_id': settings.TD_MERCHANT_ID, } product_count = 1 total_cost = 0 product_list = [] if isinstance(cleaned_data['products'],ListType): for sku in cleaned_data['products']: product = Product.objects.get(sku=sku) param['prod_id_%s' % product_count] = product.sku param['prod_quantity_%s' % product_count] = '1' param['prod_name_%s' % product_count] = product.name param['prod_cost_%s' % product_count] = product.amount total_cost += Decimal(product.amount) product_count = product_count + 1 product_list.append(product) else: product = Product.objects.get(sku=cleaned_data['products']) param['prod_id_1'] = product.sku param['prod_quantity_1'] = '1' param['prod_name_1'] = product.name param['prod_cost_1'] = product.amount total_cost += Decimal(product.amount) product_list.append(product) param['trnAmount'] = total_cost if total_cost > 0: #param = [fix_encoding(p) for p in param] fixed_param = {} for x, y in param.items(): fixed_param[x] = fix_encoding(y) encoded = urllib.urlencode(fixed_param) # push the transaction to the bank handle = urllib.urlopen(settings.TD_MERCHANT_URL, encoded) result = handle.read().split('&') # parse the result string back into a dictionary results = {} for r in result: r2 = r.split('=') r2[0] = urllib.unquote_plus(r2[0]) r2[1] = urllib.unquote_plus(r2[1]) results[r2[0]] = r2[1] # TODO: any other processing/recordkeeping we want to do? # do I want to save this into the db? p = Payment() p.cc_type = cleaned_data['cc_type'] p.billing_name=cleaned_data['billing_name'] p.phone=cleaned_data['phone'] p.email=cleaned_data['email'] p.approved=results['trnApproved'] p.response="\n".join(result) p.amount = total_cost p.save() for prod in product_list: p.products.add(prod) p.save() # return based on value if results['trnApproved'] == '1': # send receipt message = loader.get_template("creditcard/receipt.html") c = Context({'name': cleaned_data['billing_name'], 'date': datetime.today(), 'txid': results['trnOrderNumber'], 'product': product_list, 'amount': total_cost}) body = message.render(c) send_mail(subject='Credit Card Receipt', txtMessage=body, htmlMessage=None, fromemail='Engineers Without Borders Canada <*****@*****.**>', recipients=[cleaned_data['email']], use_template=False) # return success return (True, results['trnId'], results['trnOrderNumber']) else: return (False, results['messageText']) else: return (True, '00000', '00000')
def save(self): # username = self.cleaned_data["username"] firstname = self.cleaned_data['firstname'] lastname = self.cleaned_data['lastname'] email = self.cleaned_data["email"] password = self.cleaned_data["password1"] username = User.objects.make_random_password() # not a password per se, just a random string while User.objects.filter(username=username).count() > 0: # ensure uniqueness username = User.objects.make_random_password() if self.cleaned_data["confirmation_key"]: from friends.models import JoinInvitation # @@@ temporary fix for issue 93 (-- Pinax comment) try: join_invitation = JoinInvitation.objects.get(confirmation_key = self.cleaned_data["confirmation_key"]) confirmed = True except JoinInvitation.DoesNotExist: confirmed = False else: confirmed = False # @@@ clean up some of the repetition below -- DRY! (-- Pinax comment) add_email = None if confirmed: if email == join_invitation.contact.email: new_user = User.objects.create_user(username, email, password) join_invitation.accept(new_user) # should go before creation of EmailAddress below new_user.message_set.create(message=ugettext(u"Your email address has already been verified")) # already verified so can just create EmailAddress(user=new_user, email=email, verified=True, primary=True).save() else: new_user = User.objects.create_user(username, "", password) join_invitation.accept(new_user) # should go before creation of EmailAddress below if email: new_user.message_set.create(message=ugettext(u"Confirmation email sent to %(email)s") % {'email': email}) add_email = email else: try: new_user = User.objects.get(email=email, is_bulk=True) signals.listupgrade.send(sender=new_user, user=new_user) except User.DoesNotExist: new_user = User.objects.create_user(username, "", password) signals.signup.send(sender=new_user, user=new_user) if email: # new_user.message_set.create(message=ugettext(u"Confirmation email sent to %(email)s") % {'email': email}) add_email = email profile = new_user.get_profile() profile.first_name = firstname profile.last_name = lastname profile.save() new_user.first_name = firstname new_user.last_name = lastname if settings.ACCOUNT_EMAIL_VERIFICATION: new_user.is_active = False new_user.save() # needs to be moved down after user is saved, so that the email # confirmation message has the peron's actual name in it if add_email: # email already exists in system? re-send verification... email_address = get_object_or_none(EmailAddress, user=new_user, email=add_email) if email_address: EmailConfirmation.objects.send_confirmation(email_address, template="emailconfirmation/newuser.txt") # otherwise, create a new email (verification will be sent automatically) else: EmailAddress.objects.add_email(new_user, add_email, confirmation_template="emailconfirmation/newuser.txt") if self.cleaned_data['chapter'] != "none" and self.cleaned_data['chapter'] != "": chapter = get_object_or_404(Network, slug=self.cleaned_data['chapter']) chapter.add_member(new_user) return username, password # required for authenticate()
def send_sms(request, session=None): if not request.user.has_module_perms("conference"): return HttpResponseRedirect(reverse('conference_schedule')) s = get_object_or_none(ConferenceSession, id=session) response = None if request.method == 'POST': api = settings.TWILIO_API_VERSION sid = settings.TWILIO_ACCOUNT_SID token = settings.TWILIO_ACCOUNT_TOKEN form = ConferenceSmsForm(request.POST) if s: del (form.fields['grouping']) if form.is_valid(): success = 0 failed = 0 registrations = [] if s: registrations = ConferenceRegistration.objects.filter( user__in=list(s.attendees.all())) elif form.cleaned_data['grouping'] == 'all': registrations = ConferenceRegistration.objects.all() elif form.cleaned_data['grouping'] == 'internal': registrations = ConferenceRegistration.objects.filter(~Q( type__contains='day')) elif form.cleaned_data['grouping'] == 'external': registrations = ConferenceRegistration.objects.filter( type__contains='day') elif form.cleaned_data['grouping'] == 'alumni': registrations = ConferenceRegistration.objects.filter( type__contains='alumni') elif form.cleaned_data['grouping'] == 'hotel': registrations = ConferenceRegistration.objects.filter( Q(type__contains='single') | Q(type__contains='double')) elif form.cleaned_data['grouping'] == 'nohotel': registrations = ConferenceRegistration.objects.filter( Q(type__contains='nohotel') | Q(type__contains='alumni')) elif form.cleaned_data['grouping'] == 'nohotel-all': registrations = ConferenceRegistration.objects.filter( ~Q(type__contains='single'), ~Q(type__contains='double')) registrations = registrations.filter(cancelled=False, cellphone__isnull=False, cellphone_optout__isnull=True) if not s and form.cleaned_data['grouping'] == 'all': registrations = list(registrations) registrations.extend( list( ConferenceCellNumber.objects.filter( cellphone_optout__isnull=True))) # Twilio account = twilio.Account(sid, token) thread_list = {} for r in registrations: if r.cellphone_optout or not r.cellphone: continue fromnumber = r.cellphone_from if not fromnumber: numbers = ConferencePhoneFrom.objects.order_by('accounts') fromnumber = numbers[0] r.cellphone_from = fromnumber r.save() fromnumber.accounts = fromnumber.accounts + 1 fromnumber.save() d = { 'From': fromnumber.number, # '415-599-2671', 'To': r.cellphone, 'Body': form.cleaned_data['message'] } if fromnumber.number not in thread_list: thread_list[fromnumber.number] = [] thread_list[fromnumber.number].append(d) try: for i in thread_list: t = Thread(target=do_send_sms, args=(thread_list[i], )) t.start() except Exception, e: #response = e.read() failed = failed + 1 else: success = success + 1 response = "" if failed: response = "%s<br/>Messages queued for sending, but some errors encountered =(" % response else: response = "%s<br/>Messages queued for sending!" % response """ # ThunderTexting, simple GET import urllib try: params = {} params['CellNumber'] = '000-000-0000' params['MessageBody'] = form.cleaned_data['message'] params['AccountKey'] = 'PPD843rw14' encoded = urllib.urlencode(params) handle = urllib.urlopen("http://thundertexting.com/sendsms.aspx?%s" % encoded) response = handle.read() #response = "http://thundertexting.com/sendsms.aspx?%s" % encoded except Exception, e: response = r.read() """ """ # ThunderTexting, SOAP from suds.client import Client try: url = 'http://thundertexting.com/SendSMS.asmx?WSDL' client = Client(url) response = client.service.SendMessageWithReference(CellNumber='000-000-0000', MessageBody=form.cleaned_data['message'], AccountKey=settings.THUNDERTEXTING_KEY, Reference='test1') except Exception, e: response = r.read() """ """ # ThunderTexting, SOAP batch send try: from suds.client import Client url = 'http://thundertexting.com/SendSMS.asmx?WSDL' client = Client(url) numbers = [] for r in registrations: if r.cellphone and not r.cellphone_optout: numbers.append(r.cellphone) # cell number should already be normalized to 123-456-7890 response = client.service.SendBulkMessage(CellNumbers=numbers, MessageBody=form.cleaned_data['message'], AccountKey=settings.THUNDERTEXTING_KEY, Reference=datetime.now()) except Exception, e: response = r.read() """ """
def email_event(request, eventid): """ Lets you email an event reminder. Email goes to the parent group (if one exists). Later this would be great for "email all RSVPs" and such. """ event = get_object_or_404(Event, id=eventid) parent = event.content_object if not helpers.is_visible(request.user, parent): return render_to_response('denied.html', context_instance=RequestContext(request)) if BaseGroup not in parent.__class__.__bases__: request.user.message_set.create( message="You can only send emails to group-owned events.") return HttpResponseRedirect(reverse(event.get_absolute_url())) if not parent.user_is_admin(request.user): request.user.message_set.create( message="You cannot send emails to the parent group.") return HttpResponseRedirect(reverse(event.get_absolute_url())) confirm = None if request.method == 'POST': form = EventEmailForm(request.POST, user=request.user, group=parent) if form.is_valid(): if request.POST.get('confirmed', None) and request.POST.get( 'action', 'back') == "send": # extra security check that sender isn't forged. # can't hurt... # copied from group_topics.views.topics.new_topic - can we combine? sender_valid = False if parent.user_is_admin(request.user): if form.cleaned_data['sender'] == parent.from_email: sender_valid = True sender = '"%s" <%s>' % (parent.from_name, parent.from_email) elif get_object_or_none( EmailAddress, email=form.cleaned_data['sender'] ) in request.user.get_profile().email_addresses(): sender_valid = True sender = '"%s %s" <%s>' % (request.user.get_profile( ).first_name, request.user.get_profile().last_name, form.cleaned_data['sender']) elif request.user.is_staff and form.cleaned_data[ 'sender'] == "*****@*****.**": sender_valid = True sender = '"EWB-ISF Canada" <*****@*****.**>' # and this is all copied from group_topics.models.GroupTopic.send_email ... =( tmpl = loader.get_template("email_template.html") c = Context({ 'group': parent, 'title': form.cleaned_data['subject'], 'body': form.cleaned_data['body'], 'topic_id': None, 'event': event, 'attachments': None }) message = tmpl.render(c) parent.send_mail_to_members(form.cleaned_data['subject'], message, sender=sender) request.user.message_set.create(message="Email sent.") return HttpResponseRedirect(event.get_absolute_url()) if not request.POST.get('action', None): confirm = request.POST else: form = EventEmailForm(user=request.user, group=parent) return render_to_response( 'events/email.html', { 'event': event, 'form': form, 'confirm': confirm }, context_instance=RequestContext(request), )
def new_topic(request, group_slug=None, bridge=None): is_member = False group = None if group_slug is None: group_slug = "ewb" group = get_object_or_404(BaseGroup, slug=group_slug) is_member = group.user_is_member(request.user, admin_override=True) if not group.is_visible(request.user): return HttpResponseForbidden() attach_count = 0 if request.method == "POST": if not request.user.is_authenticated(): return HttpResponseForbidden() try: attach_count = int(request.POST.get("attach_count", 0)) except ValueError: attach_count = 0 if group.slug == "ewb" or is_member: # has been previewed. mark it as good to go! if request.POST.get("previewed", None) and request.POST.get( "postid", None): topic = GroupTopic.objects.get(id=request.POST['postid'], creator=request.user) if topic.pending: topic.pending = False topic.save() # extra security check that sender isn't forged. # can't hurt... sender_valid = False if group.user_is_admin(request.user) and request.POST.get( 'sender', None): if request.POST['sender'] == group.from_email: sender_valid = True sender = '"%s" <%s>' % (group.from_name, group.from_email) elif get_object_or_none( EmailAddress, email=request.POST['sender'] ) in request.user.get_profile().email_addresses(): sender_valid = True sender = '"%s %s" <%s>' % ( request.user.get_profile().first_name, request.user.get_profile().last_name, request.POST['sender']) elif request.user.is_staff and request.POST[ 'sender'] == "*****@*****.**": sender_valid = True sender = '"EWB-ISF Canada" <*****@*****.**>' if topic.send_as_email: if sender_valid: request.user.message_set.create( message=escape("Sent as %s" % sender)) topic.send_email(sender=sender) else: request.user.message_set.create( message="Unable to send email.") # redirect out. request.user.message_set.create( message=_("You have started the topic %(topic_title)s") % {"topic_title": topic.title}) else: # probably double-clicked the submit button and this is the dupe request... pass return HttpResponseRedirect(topic.get_absolute_url()) # confirmation was cancelled, so delete the temp post and bump back to edit screen topic = None if request.POST.get("goback", None) and request.POST.get( "postid", None): topic = get_object_or_none(GroupTopic, id=request.POST['postid'], pending=True, creator=request.user) if topic: topic_form = GroupTopicForm(instance=topic, user=request.user, group=group) attach_forms = [] topic.delete() # validate form and show preview... else: topic_form = GroupTopicForm(request.POST, user=request.user, group=group) attach_forms = [ AttachmentForm(request.POST, request.FILES, prefix=str(x), instance=Attachment()) for x in range(0, attach_count) ] # do not take blank attachment forms into account for af in attach_forms: if not af.is_valid() and not af['attachment_file'].data: attach_forms.remove(af) attach_count = attach_count - 1 # all good. save it! if topic_form.is_valid() and all([ af.is_valid() for af in attach_forms ]) and not request.POST.get("goback", None): # save the post but mark it as "pending".... and display a confirmation. topic = topic_form.save(commit=False) if group: group.associate(topic, commit=False) topic.creator = request.user topic.pending = True topic.save() # save the attachments. # We need the "Topic" object in order to retrieve attachments properly # since other functions only get the Topic object base_topic = GroupTopic.objects.get(id=topic.id) attachments = [] for af in attach_forms: attachment = af.save(request, base_topic) attachments.append( af.cleaned_data['attachment_file'].name) sender = None if topic_form.cleaned_data.get('send_as_email', None): sender = topic_form.cleaned_data.get('sender', None) is_large_group = False if group.members.count() > 50: is_large_group = True return render_to_response( "topics/preview.html", { "group": group, "topic": topic, "is_member": is_member, "sender": sender, "attachments": attachments, "is_large_group": is_large_group, }, context_instance=RequestContext(request)) else: # if they can't start a topic, why are we still loading up a form? request.user.message_set.create(message=_( "You are not a member and so cannot start a new topic")) topic_form = GroupTopicForm(instance=GroupTopic()) attach_forms = [ AttachmentForm(prefix=str(x), instance=Attachment()) for x in range(0, attach_count) ] else: topic_form = GroupTopicForm(instance=GroupTopic(), user=request.user, group=group) attach_forms = [] return render_to_response("topics/new_topic.html", { "group": group, "topic_form": topic_form, "attach_forms": attach_forms, "attach_count": attach_count, "is_member": is_member, }, context_instance=RequestContext(request))
def login(request, details=False): if request.method == 'POST': if request.POST.get('user', None) and request.POST.get('password', None) and \ (request.META['REMOTE_ADDR'] == '127.0.0.1' or request.META['REMOTE_ADDR'] == '69.77.162.110'): username = request.POST['user'] password = request.POST['password'] if User.objects.filter(username=username).count() == 0: if EmailAddress.objects.filter(email=username, verified=True).count() == 0: if User.objects.filter( google_username=username).count() == 0: return HttpResponse("false") else: u = User.objects.get(google_username=username) username = u.username else: email = EmailAddress.objects.get(email=username, verified=True) username = email.user.username user = authenticate(username=username, password=password) if user and user.is_active: if request.POST.get('group', None): slug = request.POST['group'] group = get_object_or_none(BaseGroup, slug=slug) if not group or not group.user_is_member(user): return HttpResponse("false") if request.POST.get('level', None): level = request.POST['level'] if level == 'admin': if not user.is_staff: return HttpResponse("false") elif level == 'email': if not user.google_username: return HttpResponse("false") else: return HttpResponse("false") if details: response = {} response['userid'] = str(user.id) response['email'] = user.email response['firstname'] = user.first_name response['lastname'] = user.last_name response['myewbprofilelink'] = "http://%s%s" % ( Site.objects.get_current().domain, user.get_profile().get_absolute_url()) #response['myewbprofilephoto'] response['phonenumber'] = user.get_profile().default_phone( ).number response['addresslineone'] = user.get_profile( ).default_address().street response['city'] = user.get_profile().default_address( ).city response['postalcode'] = user.get_profile( ).default_address().postal_code response['province'] = user.get_profile().default_address( ).province response['country'] = user.get_profile().default_address( ).country response['preferredlanguage'] = user.get_profile().language avatars = Avatar.objects.filter( user=user).order_by('-primary') if avatars.count() > 0: avatar = avatars[0] response['myewbprofilephoto'] = "http://%s%s" % ( Site.objects.get_current().domain, avatar.avatar_url(200)) if user.get_profile().get_chapter(): response['chapter'] = user.get_profile().get_chapter( ).name return JsonResponse(response) else: return HttpResponse(str(user.id)) return HttpResponse("false") return HttpResponseForbidden()