• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python shortcuts.get_object_or_none函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了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函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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)
开发者ID:franciskung,项目名称:myewb2,代码行数:33,代码来源:listeners.py


示例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)
开发者ID:franciskung,项目名称:myewb2,代码行数:28,代码来源:listeners.py


示例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
开发者ID:alexnjoyce,项目名称:myewb2,代码行数:35,代码来源:forms.py


示例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
开发者ID:gorner,项目名称:myewb2,代码行数:10,代码来源:address.py


示例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))
开发者ID:franciskung,项目名称:myewb2,代码行数:49,代码来源:views.py


示例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)
开发者ID:franciskung,项目名称:myewb2,代码行数:15,代码来源:listeners.py


示例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
开发者ID:franciskung,项目名称:myewb2,代码行数:32,代码来源:models.py


示例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))
开发者ID:franciskung,项目名称:myewb2,代码行数:33,代码来源:views.py


示例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")
开发者ID:alexnjoyce,项目名称:myewb2,代码行数:31,代码来源:views.py


示例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")
开发者ID:franciskung,项目名称:myewb2,代码行数:27,代码来源:evaluations.py


示例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 []        
开发者ID:franciskung,项目名称:myewb2,代码行数:25,代码来源:models.py


示例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))
开发者ID:franciskung,项目名称:myewb2,代码行数:29,代码来源:views.py


示例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)
开发者ID:franciskung,项目名称:myewb2,代码行数:35,代码来源:listeners.py


示例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")
开发者ID:franciskung,项目名称:myewb2,代码行数:28,代码来源:evaluations.py


示例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
开发者ID:adamfk,项目名称:myewb2,代码行数:26,代码来源:context_processors.py


示例16: user_update

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)
开发者ID:franciskung,项目名称:myewb2,代码行数:34,代码来源:listeners.py


示例17: resume

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)
                             )
开发者ID:franciskung,项目名称:myewb2,代码行数:29,代码来源:views.py


示例18: badge_view_ajax

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))
开发者ID:franciskung,项目名称:myewb2,代码行数:9,代码来源:views.py


示例19: flag_view_ajax

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))
开发者ID:franciskung,项目名称:myewb2,代码行数:9,代码来源:views.py


示例20: note_view_ajax

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))
开发者ID:franciskung,项目名称:myewb2,代码行数:9,代码来源:views.py



注:本文中的siteutils.shortcuts.get_object_or_none函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python six.add_metaclass函数代码示例发布时间:2022-05-27
下一篇:
Python utils.item函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap