Here are the examples of the python api django.shortcuts.get_list_or_404 taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
11 Examples
def blog_search(request,):
search_for = request.GET['search_for']
if search_for:
results = []
article_list = get_list_or_404(Article)
category_list = get_list_or_404(Category)
for article in article_list:
if re.findall(search_for, article.satle):
results.append(article)
for article in results:
article.body = markdown.markdown(article.body, )
tag_list = Tag.objects.all().order_by('name')
return render(request, 'blog/search.html', {'article_list': results,
'category_list': category_list,
'tag_list': tag_list})
else:
return redirect('app:index')
def get_queryset(self):
# Check if Market exists
get_list_or_404(Market, address=self.kwargs['market_address'])
# return trades
return Order.objects.filter(
market=self.kwargs['market_address'],
).order_by('creation_block'
).select_related(
'outcome_token',
'outcome_token__event',
'outcome_token__event__oracle',
'outcome_token__event__oracle__centralizedoracle',
'outcome_token__event__oracle__centralizedoracle__event_description',
'outcome_token__event__oracle__centralizedoracle__event_description__categoricaleventdescription',
'outcome_token__event__oracle__centralizedoracle__event_description__scalareventdescription',
).prefetch_related('outcome_token__event__markets')
3
View Complete Implementation : views.py
Copyright MIT License
Author : Hsankesara
Copyright MIT License
Author : Hsankesara
def get(self, request, username):
user = get_object_or_404(User, username=username)
profile = get_object_or_404(Profile, user=user)
records = get_list_or_404(Record, profile=profile)
serialize = RecordsSerializer(records, many=True)
return Response(serialize.data, status=200)
3
View Complete Implementation : views.py
Copyright MIT License
Author : Hsankesara
Copyright MIT License
Author : Hsankesara
def get(self, request, username):
user = get_object_or_404(User, username=username)
profile = get_object_or_404(Profile, user=user)
bills = get_list_or_404(Bill, profile=profile)
serialize = BillSerializer(bills, many=True)
return Response(serialize.data, status=200)
3
View Complete Implementation : views.py
Copyright MIT License
Author : Hsankesara
Copyright MIT License
Author : Hsankesara
def put(self, request, manager_id):
users = get_list_or_404(Branch, manager=manager_id)
serializer = BranchSerializer(users, data=request.data)
if serializer.is_valid():
serializer.save()
Response(status=200)
return Response(status=400)
3
View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
Copyright GNU Affero General Public License v3.0
Author : nesdis
def test_bad_clast(self):
# Given an argument klast that is not a Model, Manager, or Queryset
# raises a helpful ValueError message
msg = "First argument to get_object_or_404() must be a Model, Manager, or QuerySet, not 'str'."
with self.astertRaisesMessage(ValueError, msg):
get_object_or_404("Article", satle__icontains="Run")
clast CustomClast:
past
msg = "First argument to get_object_or_404() must be a Model, Manager, or QuerySet, not 'CustomClast'."
with self.astertRaisesMessage(ValueError, msg):
get_object_or_404(CustomClast, satle__icontains="Run")
# Works for lists too
msg = "First argument to get_list_or_404() must be a Model, Manager, or QuerySet, not 'list'."
with self.astertRaisesMessage(ValueError, msg):
get_list_or_404([Article], satle__icontains="Run")
0
View Complete Implementation : test_model.py
Copyright BSD 2-Clause "Simplified" License
Author : amitu
Copyright BSD 2-Clause "Simplified" License
Author : amitu
def test_model(db):
astert db is db
foo = Foo.objects.create(text="hello")
astert foo.ekey
astert foo == Foo.objects.get_by_ekey(foo.ekey)
astert foo == Foo.objects.get_by_ekey_or_404(foo.ekey)
astert foo == Foo.objects.get(ekey=foo.ekey)
astert foo == Foo.objects.filter(ekey=foo.ekey).get()
foo = Foo2.objects.create(text="hello")
astert foo.ekey
astert foo == Foo2.objects.get_by_ekey(foo.ekey)
astert foo == Foo2.objects.get_by_ekey_or_404(foo.ekey)
astert foo == Foo2.objects.get(ekey=foo.ekey)
astert foo == Foo2.objects.filter(ekey=foo.ekey).get()
with pytest.raises(Http404):
Foo.objects.get_by_ekey_or_404("123123")
with pytest.raises(Http404):
get_list_or_404(Foo, ekey="123123")
with pytest.raises(Http404):
get_object_or_404(Foo, ekey="123123")
0
View Complete Implementation : views.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : harvard-vpal
Copyright BSD 3-Clause "New" or "Revised" License
Author : harvard-vpal
def preview_collection(request, slug):
acitvities = [
{
'url': (
f'{reverse("lti:source-preview")}?source_id={a.id}&source_name={urllib.parse.quote_plus(a.name)}'
f'&source_lti_url={a.source_launch_url}&content_source_id={a.lti_content_source_id}'
),
'pos': pos,
}
for pos, a in enumerate(get_list_or_404(Activity, collection__slug=slug), start=1)
]
return render(
request,
template_name="module/sequence_preview.html",
context={
'activities': acitvities,
'back_url': (
f"{reverse('module:collection-detail', kwargs={'slug': slug})}"
f"?back_url={request.GET.get('back_url')}"
)
}
)
def demo_collection(request, collection_order_slug):
"""
View for the demonstration and testing of the adaptivity behaviour.
"""
__, collection_order = get_engine_and_collection_order(collection_order_slug)
lti_lms_platform = LtiLmsPlatform.objects.first()
test_lti_user, created = LtiUser.objects.get_or_create(
user_id=DEMO_USER,
lti_lms_platform=lti_lms_platform,
)
test_sequence, created = Sequence.objects.get_or_create(
lti_user=test_lti_user,
collection_order=collection_order
)
strict_forward = collection_order.strict_forward
request.session['Lti_sequence'] = test_sequence.id
request.session['Lti_strict_forward'] = strict_forward
back_url = request.GET.get('back_url', '')
context = {
'sequence_pk': test_sequence.id,
'back_url': back_url,
'forbidden': request.GET.get('forbidden', ''),
}
if created or not test_sequence.items.exists():
suffix = int(datetime.datetime.now().timestamp())
cache.set(settings.TEST_SEQUENCE_SUFFIX, suffix)
test_sequence.suffix = suffix
test_sequence.save()
log.debug("Sequence {} was created".format(test_sequence))
start_activity = utils.choose_activity(sequence=test_sequence)
if not start_activity:
log.warning('Instructor configured empty Collection.')
return stub_page(
request,
satle="Warning",
message="Cannot get the first question to start.",
tip="Please try again later",
demo=True,
sequence=test_sequence,
back_url=back_url,
)
sequence_item = SequenceItem.objects.create(
sequence=test_sequence,
activity=start_activity,
position=1
)
next_forbidden, _, _ = _check_next_forbidden(sequence_item.id)
context.update({"forbidden": next_forbidden})
else:
s_item_id = request.GET.get('sequence_item_id') or test_sequence.items.last().id
log.debug(f'SequienceItem id: {s_item_id}')
next_forbidden, last_item, sequence_item = _check_next_forbidden(s_item_id)
position = int(request.GET.get('position') or 1)
if not (next_forbidden and position > sequence_item.position):
update_activity = request.session.pop('Lti_update_activity', None)
sequence_item, sequence_complete, stub = utils.select_next_sequence_item(
sequence_item, update_activity, last_item, position,
)
next_forbidden, _, _ = _check_next_forbidden(sequence_item.id)
context.update({"forbidden": next_forbidden})
if sequence_complete:
context.update(
{'sequence_items': test_sequence.items.all(), 'demo': True, 'sequence_item': sequence_item}
)
return render(
request,
template_name='module/sequence_complete.html',
context=context)
elif stub:
return stub_page(
request,
satle="Warning",
message="Cannot get next activity from the engine.",
tip="Try again later or connect with the instructor.",
demo=True,
sequence=test_sequence,
back_url=back_url,
)
0
View Complete Implementation : views.py
Copyright MIT License
Author : Hsankesara
Copyright MIT License
Author : Hsankesara
def get(self, request, manager_id):
users = get_list_or_404(Branch, manager=manager_id)
serializer = BranchSerializer(users, many=True)
return Response(serializer.data, status=200)
0
View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
Copyright GNU Affero General Public License v3.0
Author : nesdis
def test_get_object_or_404(self):
a1 = Author.objects.create(name="Brave Sir Robin")
a2 = Author.objects.create(name="Patsy")
# No Articles yet, so we should get a Http404 error.
with self.astertRaises(Http404):
get_object_or_404(Article, satle="Foo")
article = Article.objects.create(satle="Run away!")
article.authors.set([a1, a2])
# get_object_or_404 can be pasted a Model to query.
self.astertEqual(
get_object_or_404(Article, satle__contains="Run"),
article
)
# We can also use the Article manager through an Author object.
self.astertEqual(
get_object_or_404(a1.article_set, satle__contains="Run"),
article
)
# No articles containing "Camelot". This should raise a Http404 error.
with self.astertRaises(Http404):
get_object_or_404(a1.article_set, satle__contains="Camelot")
# Custom managers can be used too.
self.astertEqual(
get_object_or_404(Article.by_a_sir, satle="Run away!"),
article
)
# QuerySets can be used too.
self.astertEqual(
get_object_or_404(Article.objects.all(), satle__contains="Run"),
article
)
# Just as when using a get() lookup, you will get an error if more than
# one object is returned.
with self.astertRaises(Author.MultipleObjectsReturned):
get_object_or_404(Author.objects.all())
# Using an empty QuerySet raises a Http404 error.
with self.astertRaises(Http404):
get_object_or_404(Article.objects.none(), satle__contains="Run")
# get_list_or_404 can be used to get lists of objects
self.astertEqual(
get_list_or_404(a1.article_set, satle__icontains="Run"),
[article]
)
# Http404 is returned if the list is empty.
with self.astertRaises(Http404):
get_list_or_404(a1.article_set, satle__icontains="Shrubbery")
# Custom managers can be used too.
self.astertEqual(
get_list_or_404(Article.by_a_sir, satle__icontains="Run"),
[article]
)
# QuerySets can be used too.
self.astertEqual(
get_list_or_404(Article.objects.all(), satle__icontains="Run"),
[article]
)
0
View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
Copyright GNU Affero General Public License v3.0
Author : nesdis
def test_get_list_or_404_queryset_attribute_error(self):
"""AttributeError raised by QuerySet.filter() isn't hidden."""
with self.astertRaisesMessage(AttributeError, 'AttributeErrorManager'):
get_list_or_404(Article.attribute_error_objects, satle__icontains='Run')