django redirect request with parameters

django redirect() with parameters

There have been several similar questions asked already but I couldn’t find answer to my problem after spending loong hours.

In the code below when I redirect to «anotherView» from «myView» with parameter «username», it works fine as expected. But I need to include «range» parameter in this redirect too as this «range» is required for the template used after redirection. Whenever I try to do, I get several errors like:

— «Don’t mix *args and **kwargs in call to reverse()»

Is there a way to manage this the way I want?

django redirect request with parameters

5 Answers 5

redirect is merely a wrapper around HttpResponseRedirect that automatically calls reverse for you to create the URL to redirect to. As a result, the parameters you pass to it, aren’t arbitrary, they must be same you would pass to reverse and, specifically, only those required to create the URL.

Many people seem to have troubles understanding that data can’t just be arbitrarily passed to a view. HTTP is a stateless protocol: each request exists on it’s own, as if user had never been to any other page of the site. The concept of a session was created to provide a sense of «state» to a cohesive unit such as a site. With sessions, data is stored in some form of persistent storage and a «key» to look up that data is given to the client (typically the user’s browser). On the next page load, the client sends the key back to the server, and the server uses it to look up the data to give the appearance of state.

As a result, if you need data from one view available in another, you need to add it to the session, do your redirect, and look up the data in the session from the next view.

Источник

How to redirect to previous page in Django after POST request

I face a problem which I can’t find a solution for. I have a button in navbar which is available on all pages and it is a button responsible for creating some content.

View that links with button:

If you can see now I always redirect to main page ‘/’ after creating content but I want to go back to the page with which I launched the creation of content.

django redirect request with parameters

5 Answers 5

This is roughly what django.contrib.auth does for the login form if I remember well.

If you pass through an intermediate page, you can pass the ‘next’ value via the querystring:

django redirect request with parameters

You can use the HTTP_REFERER value:

django redirect request with parameters

Make sure to import this

django redirect request with parameters

My favorite way to do that is giving the request.path as GET parameter to the form. It will pass it when posting until you redirect. In Class-Based-Views (FormView, UpdateView, DeleteView or CreateView) you can directly use it as success_url. Somewhere i read that it’s bad practise to mix GET and POST but the simplicity of this makes it to an exception for me.

Link to the form inside of the template:

In your function based view you can use it as follows:

django redirect request with parameters

In case this helps someone I got this to work in class based UpdateView

The view now redirects you back to the page where you had clicked the «Update/Edit» button. Any URL query parameters are also preserved.

Источник

Documentation

Request and response objects¶

Quick overview¶

Django uses request and response objects to pass state through the system.

When a page is requested, Django creates an HttpRequest object that contains metadata about the request. Then Django loads the appropriate view, passing the HttpRequest as the first argument to the view function. Each view is responsible for returning an HttpResponse object.

This document explains the APIs for HttpRequest and HttpResponse objects, which are defined in the django.http module.

HttpRequest objects¶

Attributes¶

All attributes should be considered read-only, unless stated otherwise.

A string representing the scheme of the request ( http or https usually).

A string representing the full path to the requested page, not including the scheme, domain, or query string.

Under some Web server configurations, the portion of the URL after the host name is split up into a script prefix portion and a path info portion. The path_info attribute always contains the path info portion of the path, no matter what Web server is being used. Using this instead of path can make your code easier to move between test and deployment servers.

A string representing the HTTP method used in the request. This is guaranteed to be uppercase. For example:

A string representing the MIME type of the request, parsed from the CONTENT_TYPE header.

A dictionary of key/value parameters included in the CONTENT_TYPE header.

A dictionary-like object containing all given HTTP GET parameters. See the QueryDict documentation below.

A dictionary-like object containing all given HTTP POST parameters, providing that the request contains form data. See the QueryDict documentation below. If you need to access raw or non-form data posted in the request, access this through the HttpRequest.body attribute instead.

It’s possible that a request can come in via POST with an empty POST dictionary – if, say, a form is requested via the POST HTTP method but does not include form data. Therefore, you shouldn’t use if request.POST to check for use of the POST method; instead, use if request.method == «POST» (see HttpRequest.method ).

A dictionary containing all cookies. Keys and values are strings.

See Managing files for more information.

A dictionary containing all available HTTP headers. Available headers depend on the client and server, but here are some examples:

A case insensitive, dict-like object that provides access to all HTTP-prefixed headers (plus Content-Length and Content-Type ) from the request.

The name of each header is stylized with title-casing (e.g. User-Agent ) when it’s displayed. You can access headers case-insensitively:

For use in, for example, Django templates, headers can also be looked up using underscores in place of hyphens:

An instance of ResolverMatch representing the resolved URL. This attribute is only set after URL resolving took place, which means it’s available in all views but not in middleware which are executed before URL resolving takes place (you can use it in process_view() though).

Attributes set by application code¶

Django doesn’t set these attributes itself but makes use of them if set by your application.

This will be used as the root URLconf for the current request, overriding the ROOT_URLCONF setting. See How Django processes a request for details.

This will be used instead of DEFAULT_EXCEPTION_REPORTER_FILTER for the current request. See Custom error reports for details.

This will be used instead of DEFAULT_EXCEPTION_REPORTER for the current request. See Custom error reports for details.

Attributes set by middleware¶

From the SessionMiddleware : A readable and writable, dictionary-like object that represents the current session.

From the CurrentSiteMiddleware : An instance of Site or RequestSite as returned by get_current_site() representing the current site.

Methods¶

Returns the originating host of the request using information from the HTTP_X_FORWARDED_HOST (if USE_X_FORWARDED_HOST is enabled) and HTTP_HOST headers, in that order. If they don’t provide a value, the method uses a combination of SERVER_NAME and SERVER_PORT as detailed in PEP 3333.

Raises django.core.exceptions.DisallowedHost if the host is not in ALLOWED_HOSTS or the domain name is invalid according to RFC 1034/ 1035.

The get_host() method fails when the host is behind multiple proxies. One solution is to use middleware to rewrite the proxy headers, as in the following example:

Returns the originating port of the request using information from the HTTP_X_FORWARDED_PORT (if USE_X_FORWARDED_PORT is enabled) and SERVER_PORT META variables, in that order.

HttpRequest. build_absolute_uri (location=None

If the location is already an absolute URI, it will not be altered. Otherwise the absolute URI is built using the server variables available in this request. For example:

Mixing HTTP and HTTPS on the same site is discouraged, therefore build_absolute_uri() will always generate an absolute URI with the same scheme the current request has. If you need to redirect users to HTTPS, it’s best to let your Web server redirect all HTTP traffic to HTTPS.

Returns a cookie value for a signed cookie, or raises a django.core.signing.BadSignature exception if the signature is no longer valid. If you provide the default argument the exception will be suppressed and that default value will be returned instead.

The optional salt argument can be used to provide extra protection against brute force attacks on your secret key. If supplied, the max_age argument will be checked against the signed timestamp attached to the cookie value to ensure the cookie is not older than max_age seconds.

See cryptographic signing for more information.

Returns True if the request is secure; that is, if it was made with HTTPS.

HttpRequest. accepts (mime_type

Returns True if the request Accept header matches the mime_type argument:

Most browsers send Accept: */* by default, so this would return True for all content types. Setting an explicit Accept header in API requests can be useful for returning a different content type for those consumers only. See Content negotiation example of using accepts() to return different content to API consumers.

Deprecated since version 3.1.

HttpRequest. read (size=None)¶ HttpRequest. readline ()¶ HttpRequest. readlines ()¶ HttpRequest. __iter__ ()¶

Methods implementing a file-like interface for reading from an HttpRequest instance. This makes it possible to consume an incoming request in a streaming fashion. A common use-case would be to process a big XML payload with an iterative parser without constructing a whole XML tree in memory.

Given this standard interface, an HttpRequest instance can be passed directly to an XML parser such as ElementTree :

QueryDict objects¶

Methods¶

QueryDict implements all the standard dictionary methods because it’s a subclass of dictionary. Exceptions are outlined here:

QueryDict. __init__ (query_string=None, mutable=False, encoding=None

If query_string is not passed in, the resulting QueryDict will be empty (it will have no keys or values).

classmethod QueryDict. fromkeys (iterable, value=», mutable=False, encoding=None

QueryDict. __setitem__ (key, value

Sets the given key to [value] (a list whose single element is value ). Note that this, as other dictionary functions that have side effects, can only be called on a mutable QueryDict (such as one that was created via QueryDict.copy() ).

QueryDict. __contains__ (key

QueryDict. get (key, default=None

QueryDict. setdefault (key, default=None

QueryDict. update (other_dict

In addition, QueryDict has the following methods:

QueryDict. getlist (key, default=None

QueryDict. setlist (key, list_

Sets the given key to list_ (unlike __setitem__() ).

QueryDict. appendlist (key, item

Appends an item to the internal list associated with key.

QueryDict. setlistdefault (key, default_list=None

Returns a list of values for the given key and removes them from the dictionary. Raises KeyError if the key does not exist. For example:

Removes an arbitrary member of the dictionary (since there’s no concept of ordering), and returns a two value tuple containing the key and a list of all values for the key. Raises KeyError when called on an empty dictionary. For example:

Returns a string of the data in query string format. For example:

Use the safe parameter to pass characters which don’t require encoding. For example:

HttpResponse objects¶

The HttpResponse class lives in the django.http module.

Usage¶

Passing strings¶

But if you want to add content incrementally, you can use response as a file-like object:

Passing iterators¶

Finally, you can pass HttpResponse an iterator rather than strings. HttpResponse will consume the iterator immediately, store its content as a string, and discard it. Objects with a close() method such as files and generators are immediately closed.

If you need the response to be streamed from the iterator to the client, you must use the StreamingHttpResponse class instead.

Setting header fields¶

To set or remove a header field in your response, use HttpResponse.headers :

You can also manipulate headers by treating your response like a dictionary:

When using this interface, unlike a dictionary, del doesn’t raise KeyError if the header field doesn’t exist.

You can also set headers on instantiation:

HTTP header fields cannot contain newlines. An attempt to set a header field containing a newline character (CR or LF) will raise BadHeaderError

The HttpResponse.headers interface was added.

The ability to set headers on instantiation was added.

Telling the browser to treat the response as a file attachment¶

To tell the browser to treat the response as a file attachment, set the Content-Type and Content-Disposition headers. For example, this is how you might return a Microsoft Excel spreadsheet:

There’s nothing Django-specific about the Content-Disposition header, but it’s easy to forget the syntax, so we’ve included it here.

Attributes¶

A bytestring representing the content, encoded from a string if necessary.

A string denoting the charset in which the response will be encoded. If not given at HttpResponse instantiation time, it will be extracted from content_type and if that is unsuccessful, the DEFAULT_CHARSET setting will be used.

The HTTP reason phrase for the response. It uses the HTTP standard’s default reason phrases.

This attribute exists so middleware can treat streaming responses differently from regular responses.

True if the response has been closed.

Methods¶

Instantiates an HttpResponse object with the given page content, content type, and headers.

reason is the HTTP response phrase. If not provided, a default phrase will be used.

headers is a dict of HTTP headers for the response.

The headers parameter was added.

Sets the given header name to the given value. Both header and value should be strings.

HttpResponse. __delitem__ (header

Deletes the header with the given name. Fails silently if the header doesn’t exist. Case-insensitive.

HttpResponse. __getitem__ (header

Returns the value for the given header name. Case-insensitive.

HttpResponse. get (header, alternate=None

Returns the value for the given header, or an alternate if the header doesn’t exist.

HttpResponse. has_header (header

Returns True or False based on a case-insensitive check for a header with the given name.

Acts like dict.items() for HTTP headers on the response.

HttpResponse. setdefault (header, value

Sets a header unless it has already been set.

HttpResponse. set_cookie (key, value=», max_age=None, expires=None, path=’/’, domain=None, secure=False, httponly=False, samesite=None

Sets a cookie. The parameters are the same as in the Morsel cookie object in the Python standard library.

max_age should be an integer number of seconds, or None (default) if the cookie should last only as long as the client’s browser session. If expires is not specified, it will be calculated.

expires should either be a string in the format «Wdy, DD-Mon-YY HH:MM:SS GMT» or a datetime.datetime object in UTC. If expires is a datetime object, the max_age will be calculated.

Use domain if you want to set a cross-domain cookie. For example, domain=»example.com» will set a cookie that is readable by the domains www.example.com, blog.example.com, etc. Otherwise, a cookie will only be readable by the domain that set it.

Use secure=True if you want the cookie to be only sent to the server when a request is made with the https scheme.

Use httponly=True if you want to prevent client-side JavaScript from having access to the cookie.

HttpOnly is a flag included in a Set-Cookie HTTP response header. It’s part of the RFC 6265 standard for cookies and can be a useful way to mitigate the risk of a client-side script accessing the protected cookie data.

Use samesite=’Strict’ or samesite=’Lax’ to tell the browser not to send this cookie when performing a cross-origin request. SameSite isn’t supported by all browsers, so it’s not a replacement for Django’s CSRF protection, but rather a defense in depth measure.

Use samesite=’None’ (string) to explicitly state that this cookie is sent with all same-site and cross-site requests.

Using samesite=’None’ (string) was allowed.

RFC 6265 states that user agents should support cookies of at least 4096 bytes. For many browsers this is also the maximum size. Django will not raise an exception if there’s an attempt to store a cookie of more than 4096 bytes, but many browsers will not set the cookie correctly.

Using samesite=’None’ (string) was allowed.

Deletes the cookie with the given key. Fails silently if the key doesn’t exist.

Due to the way cookies work, path and domain should be the same values you used in set_cookie() – otherwise the cookie may not be deleted.

The samesite argument was added.

This method is called at the end of the request directly by the WSGI server.

HttpResponse. write (content

This method makes an HttpResponse instance a file-like object.

This method makes an HttpResponse instance a file-like object.

This method makes an HttpResponse instance a file-like object.

HttpResponse. writelines (lines

Writes a list of lines to the response. Line separators are not added. This method makes an HttpResponse instance a stream-like object.

HttpResponse subclasses¶

The first argument to the constructor is required – the path to redirect to. This can be a fully qualified URL (e.g. ‘https://www.yahoo.com/search/’ ), an absolute path with no domain (e.g. ‘/search/’ ), or even a relative path (e.g. ‘search/’ ). In that last case, the client browser will reconstruct the full URL itself according to the current path. See HttpResponse for other optional constructor arguments. Note that this returns an HTTP status code 302.

This read-only attribute represents the URL the response will redirect to (equivalent to the Location response header).

The constructor doesn’t take any arguments and no content should be added to this response. Use this to designate that a page hasn’t been modified since the user’s last request (status code 304).

Acts just like HttpResponse but uses a 400 status code.

Acts just like HttpResponse but uses a 404 status code.

Acts just like HttpResponse but uses a 403 status code.

Acts just like HttpResponse but uses a 410 status code.

Acts just like HttpResponse but uses a 500 status code.

Custom response classes¶

JsonResponse objects¶

An HttpResponse subclass that helps to create a JSON-encoded response. It inherits most behavior from its superclass with a couple differences:

Its default Content-Type header is set to application/json.

The json_dumps_params parameter is a dictionary of keyword arguments to pass to the json.dumps() call used to generate the response.

Usage¶

Typical usage could look like:

Serializing non-dictionary objects¶

In order to serialize objects other than dict you must set the safe parameter to False :

Before the 5th edition of ECMAScript it was possible to poison the JavaScript Array constructor. For this reason, Django does not allow passing non-dict objects to the JsonResponse constructor by default. However, most modern browsers implement EcmaScript 5 which removes this attack vector. Therefore it is possible to disable this security precaution.

Changing the default JSON encoder¶

If you need to use a different JSON encoder class you can pass the encoder parameter to the constructor method:

StreamingHttpResponse objects¶

Django is designed for short-lived requests. Streaming responses will tie a worker process for the entire duration of the response. This may result in poor performance.

Generally speaking, you should perform expensive tasks outside of the request-response cycle, rather than resorting to a streamed response.

StreamingHttpResponse should only be used in situations where it is absolutely required that the whole content isn’t iterated before transferring the data to the client. Because the content can’t be accessed, many middleware can’t function normally. For example the ETag and Content-Length headers can’t be generated for streaming responses.

Attributes¶

The HTTP reason phrase for the response. It uses the HTTP standard’s default reason phrases.

FileResponse objects¶

FileResponse is a subclass of StreamingHttpResponse optimized for binary files. It uses wsgi.file_wrapper if provided by the wsgi server, otherwise it streams the file out in small chunks.

FileResponse accepts any file-like object with binary content, for example a file open in binary mode like so:

The file will be closed automatically, so don’t open it with a context manager.

Methods¶

Источник

Перенаправление страниц Django

django redirect request with parameters

Перенаправление страниц необходимо по многим причинам в веб-приложениях. Возможно, вы захотите перенаправить пользователя на другую страницу, когда происходит определенное действие, или в основном в случае ошибки. Например, когда пользователь входит на ваш сайт, его часто перенаправляют либо на главную домашнюю страницу, либо на его личную панель инструментов. В Django перенаправление выполняется методом redirect.

Метод redirect принимает в качестве аргумента URL-адрес, на который вы хотите быть перенаправлены, представляющий собой строку.

Файл myapp/views.py пока выглядит следующим образом:

Давайте изменим представление hello для перенаправления на djangoproject.com, а viewArticle для перенаправления на наш внутренний адрес /myapp/article. Файл myapp/view.py изменится и станет выглядеть следующим образом:

В приведенном выше примере сначала мы импортировали функцию для перенаправления из django.shortcuts. Для перенаправления на официальный сайт Django мы просто передали полный URL-адрес методу redirect в виде строки, а для второго примера (представление viewArticle) метод перенаправления принимает имя представления и его параметры в качестве аргументов.

Получив доступ к /myapp/hello, вы увидите следующее:

django redirect request with parameters

А доступ к /myapp/article/42, даст вам следующий результат:

django redirect request with parameters

Также можно указать, является ли перенаправление временным или постоянным, добавив параметр constant = True. Пользователь не увидит никакой разницы, но это детали, которые поисковые системы учитывают при ранжировании вашего сайта.

Также помните, что мы определили параметр name в нашем urls.py при сопоставлении URL-адреса:

Это имя (в данном случае articles) может использоваться в качестве аргумента для метода redirect, тогда наше перенаправление viewArticle может быть изменено с:

Источник

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *