本文整理汇总了Python中siteutils.shortcuts.get_object_or_none函数的典型用法代码示例。如果您正苦于以下问题:Python get_object_or_none函数的具体用法?Python get_object_or_none怎么用?Python get_object_or_none使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了get_object_or_none函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: address_update
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)
示例2: phone_update
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)
示例3: clean
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
示例4: get_address_or_404
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
示例5: custom_fields
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))
示例6: email_delete
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)
示例7: removal_notice
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 <[email protected]>"
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
示例8: browse_event
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))
示例9: preview
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")
示例10: evaluation_comment
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")
示例11: dashboard
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 []
示例12: browse_chapter
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))
示例13: group_join
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)
示例14: evaluation_interview_answer
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")
示例15: is_exec
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