Funções de atalho do DjangoLink para este cabeçalho
O pacote django.shortcuts agrega funções e classes auxiliares que “abrangem” múltiplos níveis do MVC. Em outras palavras, essas funções/classes introduzem uma composição controlada por uma questão de conveniência.
render()Link para este cabeçalho
- render(request, template_name, context=None, content_type=None, status=None, using=None)Link para esta definição
Combina uma dado template com um dado dicionário de dados e retorna um objeto
HttpResponsecom aquele texto renderizado.Django does not provide a shortcut function which returns a
TemplateResponsebecause the constructor ofTemplateResponseoffers the same level of convenience asrender().
Argumentos requeridosLink para este cabeçalho
requestO objeto de requisição usado para gerar esta resposta.
template_nameO nome completo do template a ser usado ou uma sequência de nomes de templates. Se uma sequência é dada, o primeiro template que existir será usado. Veja a documentação de carga de templates para maiores informações de como os templates são encontrados.
Argumentos opcionaisLink para este cabeçalho
contextUm dicionário de valores que são adicionados ao contexto do template. Por padrao, é um dicionário vazio. Se um valor neste dicionário é um executável, a “view” irá executá-lo logo antes de renderizar o template.
content_typeThe MIME type to use for the resulting document. Defaults to
'text/html'.statusO código de status da resposta. Padrão é
200.usingO
NAMEdo mecanismo de template a ser usado para a carga do template.
ExemploLink para este cabeçalho
O exemplo seguinte renderiza o template myapp/index.html com o tipo MIME application/xhtml+xml:
from django.shortcuts import render
def my_view(request):
# View code here...
return render(
request,
"myapp/index.html",
{
"foo": "bar",
},
content_type="application/xhtml+xml",
)
Este exemplo é equivalente a:
from django.http import HttpResponse
from django.template import loader
def my_view(request):
# View code here...
t = loader.get_template("myapp/index.html")
c = {"foo": "bar"}
return HttpResponse(t.render(c, request), content_type="application/xhtml+xml")
redirect()Link para este cabeçalho
- redirect(to, *args, permanent=False, preserve_request=False, **kwargs)Link para esta definição
Retorna uma
HttpResponseRedirectpara a URL apropriada de acordo com os argumentos passados.Os argumentos podem ser:
A model: the model’s
get_absolute_url()function will be called.Um nome de uma “view”, possivelmente com argumentos: a
reverse()será usada para resolver inversamente o nomeUma URL absoluta ou relativa, a qual será usada como tal para o local do redirecionamento.
By default, a temporary redirect is issued with a 302 status code. If
permanent=True, a permanent redirect is issued with a 301 status code.If
preserve_request=True, the response instructs the user agent to preserve the method and body of the original request when issuing the redirect. In this case, temporary redirects use a 307 status code, and permanent redirects use a 308 status code. This is better illustrated in the following table:permanent
preserve_request
HTTP status code
TrueFalse301
FalseFalse302
FalseTrue307
TrueTrue308
ExemplosLink para este cabeçalho
Você pode usar a função redirect() de várias maneiras.
Passando algum objeto; o método
get_absolute_url()daquele objeto será chamado para descobrir a URL de redirecionamento:from django.shortcuts import redirect def my_view(request): ... obj = MyModel.objects.get(...) return redirect(obj)Passando o nome de uma “view” e opcionalmente algum argumento posicional ou nomeado; a URL será inversamente resolvida usando o método
reverse()def my_view(request): ... return redirect("some-view-name", foo="bar")By passing a hardcoded URL to redirect to:
def my_view(request): ... return redirect("/some/url/")This also works with full URLs:
def my_view(request): ... return redirect("https://example.com/")
Por padrão, a redirect() retorna um redirecionamento temporário. Todas as formas acima aceitam um argumento chamado permanent; se definido como True um redirecionamento permanente será retornado:
def my_view(request):
...
obj = MyModel.objects.get(...)
return redirect(obj, permanent=True)
Additionally, the preserve_request argument can be used to preserve the
original HTTP method:
def my_view(request):
# ...
obj = MyModel.objects.get(...)
if request.method in ("POST", "PUT"):
# Redirection preserves the original request method.
return redirect(obj, preserve_request=True)
# ...
resolve_url()Link para este cabeçalho
- resolve_url(to, *args, **kwargs)Link para esta definição
Returns a URL string by resolving and normalizing the given
toargument into a concrete URL. The parametertomay be:An object implementing
get_absolute_url(), in which case the method will be called and its result returned.A view name, view function, or view class, possibly with arguments passed as
*argsand**kwargs, in which casereverse()will be used to reverse-resolve the view.A URL string, which will be returned unchanged.
This function is used internally by the
redirect()shortcut to determine the target URL for the redirect location.
ExemplosLink para este cabeçalho
Resolving a URL for a model that defines
get_absolute_url():models.pyfrom django.db import models from django.urls import reverse class Article(models.Model): title = models.CharField(max_length=100) def get_absolute_url(self): return reverse("article-detail", args=[self.pk])views.pyfrom django.http import JsonResponse from django.shortcuts import get_object_or_404, resolve_url from .models import Article def article_api_view(request, pk): """Return metadata about an article, including its canonical URL.""" article = get_object_or_404(Article, pk=pk) return JsonResponse( { "id": article.pk, "title": article.title, "url": resolve_url(article), } )Resolving a target URL for use outside of a redirect, such as in an HTTP response header:
from django.conf import settings from django.http import HttpResponse from django.shortcuts import resolve_url def login_success(request): response = HttpResponse("Login successful") response["X-Next-URL"] = resolve_url(settings.LOGIN_REDIRECT_URL) return response
get_object_or_404()Link para este cabeçalho
- get_object_or_404(klass, *args, **kwargs)Link para esta definição
- aget_object_or_404(klass, *args, **kwargs)Link para esta definição
Asynchronous version:
aget_object_or_404()Calls
get()on a given model manager, but it raisesHttp404instead of the model’sDoesNotExistexception.
ArgumentosLink para este cabeçalho
ExemploLink para este cabeçalho
O exemplo seguinte pega o objeto do modelo MyModel e com chave-primária igual a 1:
from django.shortcuts import get_object_or_404
def my_view(request):
obj = get_object_or_404(MyModel, pk=1)
Este exemplo é equivalente a:
from django.http import Http404
def my_view(request):
try:
obj = MyModel.objects.get(pk=1)
except MyModel.DoesNotExist:
raise Http404("No MyModel matches the given query.")
O caso de uso mais comum é passar uma Model, como mostrado acima. Porém, você pode também passar uma instância de QuerySet:
queryset = Book.objects.filter(title__startswith="M")
get_object_or_404(queryset, pk=1)
O exemplo acima é um pouco exagerado já que é equivalente a fazer:
get_object_or_404(Book, title__startswith="M", pk=1)
mas pode ser útil se você estiver passando uma varável queryset vinda de algum outro lugar.
E fInalmente, você pode usar uma Manager. Isso é útil por exemplo quando você tem uma custom manager:
get_object_or_404(Book.dahl_objects, title="Matilda")
Você pode usar também uma "Manager"/s relacionados:
author = Author.objects.get(name="Roald Dahl")
get_object_or_404(author.book_set, title="Matilda")
Nota: Assimcomo o get(), uma exceção do tipo MultipleObjectsReturned será emitida se mais de um objeto for encontrado..
get_list_or_404()Link para este cabeçalho
- get_list_or_404(klass, *args, **kwargs)Link para esta definição
- aget_list_or_404(klass, *args, **kwargs)Link para esta definição
Asynchronous version:
aget_list_or_404()Returns the result of
filter()on a given model manager cast to a list, raisingHttp404if the resulting list is empty.
ArgumentosLink para este cabeçalho
ExemploLink para este cabeçalho
O exemplo seguinte pega todos os objetos publicados do MyModel:
from django.shortcuts import get_list_or_404
def my_view(request):
my_objects = get_list_or_404(MyModel, published=True)
Este exemplo é equivalente a:
from django.http import Http404
def my_view(request):
my_objects = list(MyModel.objects.filter(published=True))
if not my_objects:
raise Http404("No MyModel matches the given query.")