def move(self, request): import logging logging.error(request.POST) page = get_object_or_404(Page, request.POST['page_id']) target = get_object_or_404(Page, request.POST['target_id']) position = request.POST['position'] if position == 'inside': page.parent_page = target elif position == 'before': prev = target.previous_sibling() if prev: page.order = (target.order + prev.order) / 2 else: page.order = target.order / 2 page.parent_page = target.parent_page elif position == 'after': next = target.next_sibling() if next: page.order = (target.order + next.order) / 2 else: page.order = target.order + 1000 page.parent_page = target.parent_page else: raise ValueError("Incorrect position parameter") page.put() return HttpResponse('ok')
def getCachedObjectOr404(model = None,key=None,key_name=None,id = None , id_or_name = None): """ Get a object from cache. If it is not existed in the cache, it will query from database directly and save it in cache. If the object is not existed in the cache and database , it will raise Http404 exception """ if id_or_name: try: id = int(id_or_name) except ValueError: key_name = id_or_name cache_key = getCacheObjectKey(model = model , key=key , key_name = key_name,id = id) #print cache_key object = memcache.get(cache_key) if object == None: if key: object = get_object_or_404(model,key) else: object = get_object_or_404(model,key_name=key_name, id = id) if not memcache.add(cache_key, object, _default_cache_time): logging.error("Memcache set %s failed." % cache_key) return object
def station_by_city_get(request, cityId, stationId): city = get_object_or_404(City, id=int(cityId)) station = get_object_or_404(BikeStation, id=int(stationId)) if station.providerRef.cityRef != city: raise Http404 doc = utils.object_to_xml(station) return HttpResponse(doc.toxml(), content_type="text/xml")
def status_by_station_get(request, cityId, stationId):#ask about it city = get_object_or_404(City, id=int(cityId)) station = get_object_or_404(BikeStation, id=int(stationId)) if station.city != city: raise Http404 status = station.bikestationstatus_set.get() doc = utils.object_to_xml(status) return HttpResponse(doc.toxml(), content_type="text/xml")
def version_diff(request, slug, version1, version2): if int(version1) == 0: old_content = '' else: old_content = get_object_or_404(Page, key_name="page%s%s" % (slug, version1)).content page = get_object_or_404(Page, key_name="page%s%s" % (slug, version2)) diff = easy_diff(old_content, page.content) return render_to_response('wiki/version_diff.html', {'diff': diff, 'slug': slug, 'version1': version1, 'version2': version2, 'page': page})
def edit(request,kind,object_id): """ Edit model """ (model,model_form) = _getModelInfo(kind) message = "" id = None key_name = None try: id = int(object_id) except ValueError: key_name = object_id object = get_object_or_404(model,key_name = key_name , id=id) if request.method == 'POST': form = model_form(request.POST,instance=object) if form.is_valid(): #Old object was changed by the from, so it need to get a new copy object = get_object_or_404(model,key_name = key_name , id=id) new_object = form.save(commit = False) changelog = createChangelog(object,new_object,form.cleaned_data['log_message']) if changelog: db.put([new_object,changelog]) updateCachedObject(new_object) #TODO - Update loader cache return HttpResponseRedirect(new_object.get_absolute_url()) else: message = _("Nothing changed. The form will not be saved") else: form = model_form(instance=object) view_object_link = None if object : view_object_link = object.get_absolute_url() return render_to_response( request, 'gogogo/db/edit.html' ,{ "form" : form , "object" : object, "kind" : kind, "message" : message, "history_link" : _reverse('gogogo.views.db.changelog.list') + "?kind=%s" % kind, "view_object_link" : view_object_link, "action" : _reverse('gogogo.views.db.edit',args=[kind,object_id]) , })
def download_file(request, key, name): file = get_object_or_404(File, key) if file.name != name: raise Http404('Could not find file with this name!') return HttpResponse(file.file, content_type=guess_type(file.name)[0] or 'application/octet-stream')
def render_image(request, image_key): """ Serves image data. """ img = get_object_or_404(Image, image_key) #TODO[Alex Tereshkin|2009-09-23]: mime types return HttpResponse(img.data)
def history_view(self, request, object_id, extra_context=None): "The 'history' admin view for this model." from django.contrib.admin.models import LogEntry model = self.model opts = model._meta app_label = opts.app_label action_list = LogEntry.all().filter('object_id =', object_id).filter( 'content_type =', ContentType.objects.get_for_model(model).id ).order('action_time').fetch(301) # If no history was found, see whether this object even exists. obj = get_object_or_404(model, object_id) context = { 'title': _('Change history: %s') % force_unicode(obj), 'action_list': action_list, 'module_name': capfirst(force_unicode(opts.verbose_name_plural)), 'object': obj, 'root_path': self.admin_site.root_path, 'app_label': app_label, } context.update(extra_context or {}) return render_to_response(self.object_history_template or [ "admin/%s/%s/object_history.html" % (app_label, opts.object_name.lower()), "admin/%s/object_history.html" % app_label, "admin/object_history.html" ], context, context_instance=template.RequestContext(request))
def invite_friends_for_event(request, key_id): from cgi import escape key_id = int(key_id, 10) event = get_object_or_404(Event, id=key_id) # This owuld be external link, but we want it to open inside the app. # event_show_url = "http://%s%s?invitation=1"%(request.META['HTTP_HOST'], event.get_facebook_url()) event_show_url = get_facebook_app_url(event.get_facebook_url()) + '?invitation=' + str(request.facebook.uid) content = """<fb:name uid="%s" firstnameonly="true" shownetwork="false"/> wants to let you know about Art of Living event: <a href="%s">%s</a>, <fb:req-choice url="%s" label="Check out this event"/> """ % (request.facebook.uid, event_show_url, event, event_show_url) invitation_content = escape(content, True) if request.GET.has_key('next'): next = request.GET['next'] else: next = "http://" + request.META['HTTP_HOST'] + event.get_facebook_url() + '?invitation=' + str(request.facebook.uid) # FIXME: Why next doesnt work correctly in real life? Do I need to encode it? return render_to_response(request, 'invite_for_event.html', {'content':invitation_content, 'event':event, 'next':escape(next), 'in_iframe' : True} )
def user_change_password(self, request, id): if not request.user.has_perm('auth.change_user'): raise PermissionDenied user = get_object_or_404(self.model, id) if request.method == 'POST': form = self.change_password_form(user, request.POST) if form.is_valid(): new_user = form.save() msg = ugettext('Password changed successfully.') Message(user=request.user, message=msg).put() return HttpResponseRedirect('..') else: form = self.change_password_form(user) return render_to_response('admin/auth/user/change_password.html', { 'title': _('Change password: %s') % escape(user.username), 'form': form, 'is_popup': '_popup' in request.REQUEST, 'add': True, 'change': False, 'has_delete_permission': False, 'has_change_permission': True, 'has_absolute_url': False, 'opts': self.model._meta, 'original': user, 'save_as': False, 'show_save': True, 'root_path': self.admin_site.root_path, }, context_instance=RequestContext(request))
def download_file(request, key, name): file = get_object_or_404(File, key) if file.name != name: raise Http404('Could not find file with this name!') return HttpResponse( file.file, content_type=guess_type(file.name)[0] or 'application/octet-stream')
def cmspage(request, url): if not url.endswith("/") and settings.APPEND_SLASH: return HttpResponseRedirect("%s/" % request.path) if not url.startswith("/"): url = "/" + url f = get_object_or_404(Page, "url =", url) return render_page(request, f)
def detail(request, key_id): reminder = get_object_or_404(Reminder, id=int(key_id)) reminder_form = ReminderForm(request.POST or None, instance=reminder) if reminder_form.is_valid(): reminder_form.save() Message(message='<p class="success message">%s</p>' % "Your changes were saved successfully.", user=request.user).put() return render_to_response(request, 'reminders/detail.html', locals())
def delete_albumentry(request,key): userfile = get_object_or_404(UserFile,key) if userfile.author==users.get_current_user() or users.is_current_user_admin(): userfile.delete() #flush cache in order to update the file list memcache.flush_all() return HttpResponseRedirect(reverse(albumentry)) else: return HttpResponseForbidden()
def show_albumentry(request,key): userfile = get_object_or_404(UserFile,key) # if userfile.icon: # return show_icon(request,key) filebin=userfile.filebin_set.get() if not userfile or not filebin: return HttpResponseNotFound() return HttpResponse(filebin.bin,'image/JPEG')
def statuses_by_provider_get(request, providerId): provider = get_object_or_404(Provider, id=int(providerId)) statuses = [] for station in provider.bikestation_set: station_status = station.status if station_status: statuses.append(station_status) doc = utils.object_to_xml(statuses, "stationStatuses") return HttpResponse(doc.toxml(), content_type="text/xml")
def change_entity(request, key, form_class): instance = get_object_or_404(form_class.Meta.model, key) if request.method == "POST": form = form_class(request.POST, instance=instance) if form.is_valid(): form.save() return HttpResponseRedirect(reverse("dashboard")) else: form = form_class(instance=instance) return render_to_response(request, "teammail/change_entity.html", data={"form": form})
def view_event_show(request, key_id): key_id = int(key_id, 10) if request.user.is_authenticated(): event = get_object_or_404(Event, id=key_id) fav = Favourite.all().filter("event =", event).filter("user ="******"is_fav": fav} return object_detail(request, Event.all(), object_id=key_id, extra_context=extra_context)
def detail_quiz(request, key): list_questions = get_object_or_404(Quiz, key).questions quiz = [] if list_questions != None: for key_question in list_questions: item = {} answers = [] question = get_object_or_404(Question, key_question) item['question'] = question for key_answer in question.answers: answer = get_object_or_404(Answer, key_answer) answers.append(answer) item['answers'] = answers quiz.append(item) return object_detail(request, Quiz.all(), key, extra_context={ 'quiz': quiz, 'result': False })
def entry_list(request, key=None, show=None): payload = {'key': key} entries = Entry.all() if key: feed = get_object_or_404(Feed, key) payload['feed'] = feed entries.filter('feed_ref =', feed) if show: entries.filter('cat_ref =', None) entries.order('-created_at') return object_list(request, entries, paginate_by=25, extra_context=payload)
def show_animal_by_name(request, category, year, month, day, name): date_ = datetime.date(int(year), int(month), int(day)) name = urllib.unquote_plus(name) a = animal = get_object_or_404(Animal, 'brought_to_shelter =', date_, 'category =', category, 'name = ', name) # todo: also check date return render_to_response(request, "nebhs/animal_detail.html", data={ 'object': animal, 'page_title': _animal_page_title(animal), 'template_wrapper': 'section-adoptions.html' })
def show_animal_by_id(request, category, id): a = animal = get_object_or_404(Animal, 'category =', category, 'code = ', id) # todo: also check date return render_to_response( request, "nebhs/animal_detail.html", data={ 'object': animal, 'page_title': _animal_page_title(animal), 'template_wrapper': 'section-adoptions.html' } ) #Adoptable {{ object.category|capfirst }}: {{ object.name|capfirst }} pass
def upload_image(request, page_key, plugin_name): """ A view for Ajax image upload. """ page = get_object_or_404(Page, page_key) if request.method == "POST": img = Image() img.data = request.FILES['value'].read() img.put() setattr(page.storage, plugin_name, img.key()) page.put() plugin = ImagePlugin(plugin_name, page) return HttpResponse(plugin.render())
def put(request, public_key, secret_key): account = get_object_or_404(Account, 'public_key =', public_key, 'secret_key =', secret_key) request_file = request.FILES['myfile'] file = File( name = request_file.name, data = request_file.read(), owner = account, added_date = datetime.now(), size = request_file.size ) file.put() return HttpResponse(file.key())
def albumentry(request): if request.method == 'POST': if 'file' in request.FILES: file = request.FILES['file'] userfile = UserFile( mimetype=request.META['CONTENT_TYPE'], author = users.get_current_user(), size = file.size, name=file.name, comment=request.REQUEST.get('comment','')) bin=file.read() try: userfile.icon=images.resize(bin, width=60) except: pass userfile.save() filebin = FileBin(userfile=userfile, bin=db.Blob(bin)) filebin.save() file.close() if UserFile.all().count() > FILE_MAX: oldest_file = UserFile.all().order('-creationDate').get() oldest_file.delete() #flush cache in order to update the file list memcache.flush_all() return HttpResponseRedirect(reverse(albumentry)) else: return HttpResponseRedirect(reverse(albumentry)) else: filelist = UserFile.all().order('-creationDate').fetch(FILE_MAX) user = users.get_current_user() if user: sign_link = '<a href="%s">Logout</a>' % users.create_logout_url(reverse(albumentry)) else: sign_link = '<a href="%s">Login</a>' % users.create_login_url(reverse(albumentry)) displayFile=None if 'key' in request.REQUEST: displayFile=get_object_or_404(UserFile,request.REQUEST['key']) email_form=EmailForm() template_values = { 'displayFile':displayFile, # 'user': user, 'sign_link': sign_link, 'filelist': filelist, 'form':FileForm(), 'email_form':email_form, } return render_to_response('upload/show_albumentry.html',template_values,context_instance=RequestContext(request))
def result_quiz(request, key): if request.method == 'POST': quiz = [] list_questions = get_object_or_404(Quiz, key).questions if list_questions != None: i = 0 note = 0 for key_question in list_questions: i += 1 item = {} answers = [] question = get_object_or_404(Question, key_question) item['question'] = question form_response = request.POST['%s' % question.key()] good_response = '%s' % question.question_answer.key() if form_response == good_response: item['point'] = True note += 1 else: item['point'] = False for key_answer in question.answers: answer = get_object_or_404(Answer, key_answer) if answer == question.question_answer: answers.append(answer) item['answers'] = answers quiz.append(item) return object_detail(request, Quiz.all(), key, extra_context={ 'quiz': quiz, 'result': True, 'note': note, 'nbquestion': i })
def show_page(request, path): slug = path.split('/')[-1] #TODO: need to use full path to identify the page page = get_object_or_404(Page, "slug =", slug) if request.method == "POST": if request.user.is_staff: setattr(page.storage, request.POST['id'], db.Text(request.POST['value'])) page.storage.put() return HttpResponse(request.POST['value']) else: raise Http404 return render_to_response(request, page.template.name, {'page' : page })
def event_show(request, key_id): key_id = int(key_id, 10) if request.user.is_authenticated(): event = get_object_or_404(Event, id=key_id) fav = Favourite.all().filter('event =', event).filter('user ='******'invitation'): invitation = request.GET['invitation'] else: invitation = 0 extra_context = { 'is_fav' : fav, 'in_iframe' : True, 'invitation' : invitation, 'invitation_link' : get_facebook_app_url(request.path), } return object_detail(request, Event.all(), object_id=key_id, extra_context = extra_context)
def list(request, cat=None, blog=None, label=None): entry_obj = Entry.all().order('-created_at') if cat: cat_obj = CategoryCount.all().filter('category =', cat).get() if not cat_obj: raise Http404 entry_obj.filter('cat_ref =', cat_obj) label = cat_obj.category elif blog: feed_obj = get_object_or_404(Feed, blog) entry_obj.filter('feed_ref =', feed_obj) label = feed_obj.name template_ext = 'xml' if request.GET.has_key('output') and request.GET.get('output') == 'rss' else 'html' return object_list(request, entry_obj, paginate_by=25, extra_context={'label' : label, 'cat' : cat, 'blog' : blog}, template_name='archive/entry_list.%s' % template_ext)
def users_photo(request, username, photo_key): viewed_user = User.get_user_by_username_or_404(username) photo = get_object_or_404(Photo, photo_key) if photo.user != viewed_user: raise Http404('Object does not exist!') extra_context = { 'viewed_user': viewed_user, 'photo': photo, 'viewed_username': username } return object_list(request, queryset=Thumbnail.all().filter('photo_user', viewed_user).order('-photo_date_added'), template_name='photo/show.html', extra_context=extra_context )
def stations_put(request, providerId): if request.method == "PUT": provider = get_object_or_404(Provider, id=int(providerId)) data = request.raw_post_data try: xmltree = ET.XML(data) except: raise HttpResponseBadRequest() try: save_station_status(xmltree, provider) provider.locationsUpdated = datetime.datetime.now() provider.put() return HttpResponse("OK") except InvalidXML, e: return HttpResponseBadRequest(e.message) except InvalidXMLNode, e: return HttpResponseBadRequest(e.message)
def detail(request, key_name): """ Show details for a public suggestion, and a button to create a reminder from it. """ suggestion = get_object_or_404(Reminder, key_name=key_name) logging.debug(request.method) email_form = EmailForm(request.POST) if request.method == "POST": user = request.user if user.is_anonymous() and email_form.is_valid(): email = email_form.cleaned_data['email'] existing = User.all().filter('email', email).fetch(1) if len(existing): return HttpResponseRedirect( '/accounts/login/?email=%s&next=%s' % (email, request.path)) user = create_user(request, email) return create_reminder(request, user, suggestion) return render_to_response( request, 'suggestions/detail.html', locals())
def flatpage(request, url): """ Flat page view. Models: `flatpages.flatpages` Templates: Uses the template defined by the ``template_name`` field, or `flatpages/default.html` if template_name is not defined. Context: flatpage `flatpages.flatpages` object """ if not url.endswith('/') and settings.APPEND_SLASH: return HttpResponseRedirect("%s/" % request.path) if not url.startswith('/'): url = "/" + url f = get_object_or_404(FlatPage, 'url =', url, 'sites = ', db.Key(settings.SITE_ID)) # If registration is required for accessing this page, and the user isn't # logged in, redirect to the login page. if f.registration_required and not request.user.is_authenticated(): from django.contrib.auth.views import redirect_to_login return redirect_to_login(request.path) if f.template_name: t = loader.select_template((f.template_name, DEFAULT_TEMPLATE)) else: t = loader.get_template(DEFAULT_TEMPLATE) # To avoid having to always use the "|safe" filter in flatpage templates, # mark the title and content as already safe (since they are raw HTML # content in the first place). f.title = mark_safe(f.title) f.content = mark_safe(f.content) c = RequestContext(request, { 'flatpage': f, }) response = HttpResponse(t.render(c)) populate_xheaders(request, response, FlatPage, f.id) return response
def facebook_show_animal_by_name(request, category=None, year=None, month=None, day=None, name=None): date_ = datetime.date(int(year), int(month), int(day)) name = urllib.unquote_plus(name) animal = get_object_or_404(Animal, 'brought_to_shelter =', date_, 'category =', category, 'name = ', name) # todo: also check date return render_to_response(request, "fb/animal_detail.html", data={ 'object': animal, 'page_title': _animal_page_title(animal), 'template_wrapper': 'base.html', 'FB_APPLICATION_ID': settings.FACEBOOK_APPLICATION_ID })
def entry_show(request, key): entry = get_object_or_404(Entry, key) #clustering wordcounts = [] wordlist = [] entries = Entry.all().filter('cat_ref =', entry.cat_ref).order('-created_at').fetch(20) for e in entries: wc = clusters.get_words(e) wordcounts.append(wc) for w in wc.keys(): if w not in wordlist: wordlist.append(w) words = [[] for i in range(len(wordcounts))] for i, wc in enumerate(wordcounts): for word in wordlist: if word in wc: c = float(wc[word]) else: c = 0.0 words[i].append(c) kcluster = clusters.kcluster(words) #logging.debug(kcluster) similalities = [] for cluster in kcluster: for i, c in enumerate(cluster): if entries[c] == entry: #similalities = cluster similalities = [entries[cl] for cl in cluster] break #logging.debug(similalities) return render_to_response(request, 'feed/entry_detail.html', {'entry' : entry, 'similalities' : similalities})
def download_albumentry(request,key): userfile = get_object_or_404(UserFile,key) filebin=userfile.filebin_set.get() if not userfile or not filebin: return HttpResponseNotFound() response=HttpResponse(filebin.bin,content_type=guess_type(userfile.name)[0] or 'application/octet-stream') #dealing with unicode :( Can't convert unicode to ascii when decode. #If any solutions, please mail to me: [email protected] if isinstance(userfile.name, unicode): response['Content-Type'] = 'application/octet-stream' encoding=sys.getdefaultencoding() try : name=force_unicode(urllib.unquote(smart_str(userfile.name))) str=name.decode(encoding) filename=str.encode(encoding, 'replace') response['Content-Disposition'] = 'attachment; filename="%s"'%filename except UnicodeEncodeError: filename=userfile.name response['Content-Type']=userfile.mimetype else: filename=userfile.name response['Content-Type']=userfile.mimetype return response
def detail(request, key_name): domain = get_object_or_404(Domain, key_name=key_name) return render_to_response(request, 'domains/detail.html', locals())
def show_icon(request,key): userfile = get_object_or_404(UserFile,key) if userfile.icon: return HttpResponse(userfile.icon,'image/JPEG') return HttpResponseNotFound()