def watch(request, poll_url):
current_poll = get_object_or_404(Poll, url=poll_url)
if not current_poll.can_watch(request.user, request):
messages.error(
request, _("You are not allowed to watch this poll.")
)
return redirect('poll', poll_url)
if current_poll.user_watches(request.user):
poll_watch = PollWatch.objects.get(poll=current_poll, user=request.user)
poll_watch.delete()
else:
poll_watch = PollWatch(poll=current_poll, user=request.user)
poll_watch.save()
return redirect('poll', poll_url)
python类get_object_or_404()的实例源码
def checkin(request, primary_key):
"""Checkin the :model:`library.Lendable`.
Cleanup and delete Lendable.
Redirect:
:view:`library.index`
"""
item = get_object_or_404(Lendable.all_types,
pk=primary_key,
user=request.user)
try:
item.checkin()
except Exception as e:
messages.error(request, e)
else:
messages.success(request, "'%s' returned." % (item.name))
return redirect(reverse('library:index'))
def like(request):
"""
kullan?c? be?endi?inde vya be?enmedi?inde ekrandaki skoru otomatik
update eder
"""
id = request.GET.get("id", default=None)
like = request.GET.get("like")
obj = get_object_or_404(Post, id=int(id))
if like == "true":
# f objesi veri tabanindaki ilgili sutunun degerini cekerek
# atama yapmak yerine arttirma veya azaltma yapmamizi saglar.
obj.score = F("score") + 1
obj.save(update_fields=["score"])
elif like == "false":
obj.score = F("score") - 1
obj.save(update_fields=["score"])
else:
return HttpResponse(status=400)
obj.refresh_from_db()
return JsonResponse({"like": obj.score, "id": id})
def vote(request, question_id):
question = get_object_or_404(Question, pk=question_id)
try:
selected_choice = question.choice_set.get(pk=request.POST['choice'])
except (KeyError, Choice.DoesNotExist):
# Redisplay the question voting form.
return render(request, 'polls/detail.html', {
'question': question,
'error_message': "You didn't select a choice."
})
else:
# See Avoiding race conditions using F()
# https://docs.djangoproject.com/en/1.9/ref/models/expressions/#avoiding-race-conditions-using-f
selected_choice.votes += 1
selected_choice.save()
# Always return an HttpResponseRedirect after successfully dealing
# with POST data. This prevents data from being posted twice if a
# user hits the Back button.
return HttpResponseRedirect(reverse('polls:results', args=(
question.id,
)))
def plan_run_repo(request, plan_id, repo_owner, repo_name):
plan = get_object_or_404(Plan, id=plan_id)
repo = get_object_or_404(Repository, owner=repo_owner, name=repo_name)
if request.method == 'POST':
form = RunPlanForm(plan, repo, request.user, request.POST)
if form.is_valid():
build = form.create_build()
return HttpResponseRedirect(build.get_absolute_url())
else:
form = RunPlanForm(plan, repo, request.user)
context = {
'form': form,
'plan': plan,
'repo': repo,
}
return render(request, 'plan/run.html', context=context)
def build_rebuild(request, build_id):
build = get_object_or_404(Build, id=build_id)
if not request.user.is_staff:
return HttpResponseForbidden(
'You are not authorized to rebuild builds')
rebuild = Rebuild(
build=build,
user=request.user,
status='queued',
)
rebuild.save()
if not build.log:
build.log = ''
build.log += '\n=== Build restarted at {} by {} ===\n'.format(
timezone.now(), request.user.username)
build.current_rebuild = rebuild
build.save()
return HttpResponseRedirect('/builds/{}'.format(build.id))
def test_method_peek(request, method_id):
method = get_object_or_404(TestMethod, id=method_id)
latest_fails = method.test_results.filter(
outcome='Fail'
).order_by(
'-build_flow__time_end'
).select_related(
'build_flow',
'build_flow__build',
'build_flow__build__repo',
'build_flow__build__plan',
'build_flow__build__branch',
'build_flow__build__branch__repo'
)
latest_fails = paginate(latest_fails, request)
data = {
'method': method,
'latest_fails': latest_fails
}
return render(request, 'testresults/test_method_peek.html', data)
def repo_detail(request, owner, name):
query = {
'owner': owner,
'name': name,
}
if not request.user.is_staff:
query['public'] = True
repo = get_object_or_404(Repository, **query)
query = {'repo': repo}
builds = view_queryset(request, query)
context = {
'repo': repo,
'builds': builds,
}
return render(request, 'repository/repo_detail.html', context=context)
def commit_detail(request, owner, name, sha):
query = {
'owner': owner,
'name': name,
}
if not request.user.is_staff:
query['public'] = True
repo = get_object_or_404(Repository, **query)
query = {'commit': sha, 'repo': repo}
builds = view_queryset(request, query)
context = {
'repo': repo,
'builds': builds,
'commit': sha,
}
return render(request, 'repository/commit_detail.html', context=context)
def form_valid(self, form, *args, **kwargs):
product = get_object_or_404(Product, pk=self.kwargs['product_id'])
quantity = form.cleaned_data['quantity']
cart = get_cart(self.request, create=True)
cart_item, cart_item_created = CartItem.objects.update_or_create(cart=cart, product=product)
# If Cart item object has not been created , amend quantity.
if cart_item_created is False:
cart_item.quantity += quantity
else:
cart_item.quantity = quantity
cart_item.save()
return super(AddToCartView, self).form_valid(form)
def edit(request, individual_id):
individual = get_object_or_404(Individual, pk=individual_id)
if request.method == 'POST':
form = IndividualForm(request.POST, instance=individual)
if form.is_valid():
form.save()
return redirect('dashboard')
# form = IndividualForm(request.POST, request.FILES)
# if form.is_valid():
# individual = form.save(commit=False)
# individual.user = request.user
# individual.save()
# return redirect('dashboard')
else:
form = IndividualForm(instance=individual)
return render(request, 'individuals/individual_form.html', {'form':form})
def view(request, disease_id):
disease = get_object_or_404(Disease, pk=disease_id)
gene = disease.gene_set.all()[0]
# print 'gene', gene.official_name
# individuals = Individual.objects.all()
individuals_variants = Variant.objects.filter(gene=gene.official_name)
# individuals_variants = []
# for individual in individuals:
# individual_variants = Variant.objects.filter(individual=individual, gene=gene.official_name)
# individuals_variants.append(individual_variants)
# individual_variants.query.group_by = ['individual_id']
# results = query.execute_sql()
# individuals = Individual.objects.all()
# for individual in individuals:
# individual_variants = Variant.objects.find(filter(date__range=["2011-01-01", "2011-01-31"]))
return render(request, 'diseases/view.html', {'disease': disease, 'variants': individuals_variants})
def edit(request, case_id):
case = get_object_or_404(Case, pk=case_id)
if request.method == 'POST':
form = CaseForm(request.POST, request.FILES, instance=case)
if form.is_valid():
form.save()
# variants = form.cleaned_data['variants']
# strs = form.cleaned_data['strs']
# cnvs = form.cleaned_data['cnvs']
# #use id for unique names
# individual = Individual.objects.create(user=request.user, status='new')
#
# individual.variants=variants
# individual.strs=cnvs
# individual.cnvs=cnvs
#
# individual.name=request.POST['name']
# individual.save()
# AnnotateVariants.delay(individual.id)
return redirect('cases_list')
else:
form = CaseForm(instance=case)
return render(request, 'cases/edit.html', {'form': form})
def import_files(request, project_id):
project = get_object_or_404(Project, pk=project_id)
form = ImportFilesForm(request.POST or None)
if request.method == 'POST':
if form.is_valid():
for file in form.cleaned_data['file_list'].splitlines():
# print(file)
file_objs = File.objects.filter(name__contains=file)
# print(file_obj)
for file_obj in file_objs:
project.files.add(file_obj)
# form.save()
return redirect('projects-view', project.id)
context = {'form': form, 'project': project}
return render(request, 'projects/import_files.html', context)
def wishlist_oglas(request, oglas_id):
oglas = get_object_or_404(Oglas, pk=oglas_id)
try:
if oglas.na_wishlist:
oglas.na_wishlist = False
else:
oglas.na_wishlist = True
oglas.save()
except (KeyError, Oglas.DoesNotExist):
return JsonResponse({'success': False})
else:
return JsonResponse({'success': True})
def get_context_data(self, **kwargs):
context = super(GameView, self).get_context_data(**kwargs)
group = get_object_or_404(Group, id=self.kwargs.get('group_pk', None))
game = get_object_or_404(Game, id=self.kwargs.get('game_pk', None))
players = game.players.order_by('-ranking')
for player in players:
try:
rank_change = str(player.rankchange_set.get(game=game))
except RankChange.DoesNotExist:
rank_change = 'not available'
setattr(player, 'rank_change', rank_change)
context.update({
'group': group,
'game': game,
'players': players,
})
return context
def form_valid(self, form):
# Make sure only two players are selected.
players = form.cleaned_data['players']
if players.count() != 2:
form.add_error(
'players',
'A game requires two players, please try again.',
)
return self.form_invalid(form)
# Otherwise, connect the game to the group.
self.object = form.save()
group = get_object_or_404(Group, id=self.kwargs.get('pk', None))
group.games.add(self.object)
group.save()
return HttpResponseRedirect(self.get_success_url())
def content_xml_view(request, guid):
"""Diaspora single post view XML representation.
Fetched by remote servers in certain situations.
"""
content = get_object_or_404(Content, guid=guid, visibility=Visibility.PUBLIC, local=True)
entity = make_federable_content(content)
xml = get_full_xml_representation(entity, content.author.private_key)
return HttpResponse(xml, content_type="application/xml")
def content_fetch_view(request, objtype, guid):
"""Diaspora content fetch view.
Returns the signed payload for the public content. Non-public content will return 404.
If the content is not local, redirect to content author server.
Args:
objtype (str) - Diaspora content type. Currently if it is `status_message`, `post` or `reshare`,
we try to find `Content`.
guid (str) - The object guid to look for.
"""
if objtype not in ["status_message", "post", "reshare", "comment"]:
raise Http404()
content = get_object_or_404(Content, guid=guid, visibility=Visibility.PUBLIC)
if not content.local:
url = "https://%s/fetch/%s/%s" % (
content.author.handle.split("@")[1], objtype, guid
)
return HttpResponseRedirect(url)
entity = make_federable_content(content)
message = get_full_xml_representation(entity, content.author.private_key)
document = MagicEnvelope(
message=message, private_key=content.author.private_key, author_handle=content.author.handle
)
return HttpResponse(document.render(), content_type="application/magic-envelope+xml")
def get(self, request, *args, **kwargs):
"""Render ProfileDetailView for this user."""
profile = get_object_or_404(Profile, user__username=kwargs.get("username"))
return ProfileDetailView.as_view()(request, guid=profile.guid)