django set cookie
时间: 2023-08-24 07:05:00 浏览: 99
To set a cookie in Django, you can use the `set_cookie()` method on the `HttpResponse` object. Here is an example:
```python
from django.http import HttpResponse
def set_cookie_view(request):
response = HttpResponse('Cookie set!')
response.set_cookie('my_cookie', 'cookie_value')
return response
```
In this example, we create a view function that sets a cookie with the name `my_cookie` and the value `cookie_value`. We do this by calling the `set_cookie()` method on the `HttpResponse` object and passing in the name and value of the cookie.
You can also set additional parameters for the cookie, such as the expiration time, domain, and path. Here is an example:
```python
from datetime import datetime, timedelta
from django.http import HttpResponse
def set_cookie_view(request):
response = HttpResponse('Cookie set!')
expires = datetime.now() + timedelta(days=30)
response.set_cookie('my_cookie', 'cookie_value', expires=expires, domain='example.com', path='/')
return response
```
In this example, we set the cookie to expire in 30 days, and we set the domain to `example.com` and the path to `/`. These parameters are optional and can be omitted if not needed.
阅读全文