I a have a certain amounts of products. I want to make function that save a certain products in cookies not database. But i dont know how to create a list of product in cookies. Products mast be saved in such way from that i can show them by some function. What method i must use to create a list of products in cookies.
def add_instance_note(request,instance_id):
instance = Instance.objects.get(pk=instance_id)
request.session['list'].append(instance_id)
return render_to_response('show_instance.html', locals(),
context_instance=RequestContext(request))
def show_instance_note(request):
instances=[]
for instance_id in request.session['list']:
instances.append(Instance.objects.get(pk=instance_id))
return render_to_response('show_instance_note.html', locals(),
context_instance=RequestContext(request))
To use sessions with Django you must first enable and configure a session service, with a certain backend (in your case cookies). This is covered in depth here:
https://docs.djangoproject.com/en/1.6/topics/http/sessions/#using-cookie-based-sessions
For basic cookie support, this is available on the request/respond objects:
https://docs.djangoproject.com/en/dev/ref/request-response/
You can set a cookie with set_cookie:
def GetHandler(request):
response = HttpResponse('Testing cookies')
response.set_cookie('key', 'value')
To get cookies, you retrieve them from request.COOKIES. You can use standard dict operations like has_key and get to retrieve them (by the key you set previously).
Related
request.session.set_test_cookie() <---- this will create a session with cookie id
but how can I store this cookie key in a variable in Django.
I've tried this, but it gives error.
id = request.session.set_test_cookie()
Django provides an easy way to test whether the user’s browser accepts cookies. Just call the set_test_cookie() method of request.session in a view, and call test_cookie_worked() in a subsequent view – not in the same view call reference.
so set_test_cookie() method is only for testing a is browser support cookie or not. if you want to check is browser support call session.test_cookie_worked() method
Create cookie in django as follow:
def view(request):
response = HttpResponse('response data')
response.set_cookie('cookie_name', 'cookie_value')
Retrieve cookie data:
def view(request):
if 'cookie_name' in request.COOKIES:
value = request.COOKIES['cookie_name']
I have an application where a device sends data to my application and the application stores the data.
My Question is What is the best way to send data from the device to the server ?
The Device can be a Smart Phone.
right now I am sending a URL request along with some data like this:
www.example.com:8888/Data/?id=12345&name=john&DOB=25-09-1974
I fetch data with GET Request in Django and then save the data. Is this Right to do ? or should I follow some other process ?
P.S The data is not Sensitive. I mean Security is not a concern.
You shouldn't upload Data to the server via "GET". That is what the "POST" method is for.
According to the HTTP/1.1 Spec:
The POST method is used to request that the origin server accept the
entity enclosed in the request as a new subordinate of the resource
identified by the Request-URI in the Request-Line
In other words, POST is used to create.
It doesn't matter if you think your data is sensitive or not. By implementing a way to alter data on the server, you are automatically offering a way that can be misused by anyone. Hence, all such interfaces have to be treated with the same thoroughness in terms of security.
Your question doesn't provide anything about what you want to to with the transferred data. Do you want to store it persistently in a database or is the data only relevant for the user during his current visit?
Basically you are offered three ways:
1. persistent storage.
You will store the data in your database.
In this case you should use a form with the aforementioned "post" method.
#your_template.html
<form method="post" action="<your action">
<!-- do something -->
{{ form }}
</form>
#your_view.py
def your_view(request):
if request.method == 'POST':
form = YourForm(request.POST)
if form.is_valid(): # All validation rules pass
# Process the data in form.cleaned_data
# ...
return HttpResponseRedirect('/thanks/') # Redirect after POST
else:
form = YourForm() # An unbound form
return render(request, 'your_template.html', {
'form': form,
})
See https://docs.djangoproject.com/en/dev/topics/forms/ for more information about django forms
2. temporary storage.
you are not required to store any of these results persistently, so you can use the session mechanism of django, which will allow you to pass around data which will be just valid while a specific user is visiting your page. You can adjust the time to live of session objects
See https://docs.djangoproject.com/en/dev/topics/http/sessions/ for more information about django sessions
3. client based storage.
Go all the way to the client and use cookies which will be stored on the clients machine and are just read by the server. But you have to be extra thorough while evaluating cookie values.
See Django Cookies, how can I set them? for a little cookie helper for django and take it from there
I have a view that looks like this:
def CineByCiudad(request):
city = request.session["ciudad"]
cines = Cine.objects.filter(ciudad=city)
context = {'cines': cines}
return render_to_response('cine-ciudad.html', context, context_instance=RequestContext(request))
Now, I am using the session variable "ciudad" to filter my query.
On the homepage of my site I let the user set their "ciudad" and once its set I redirect them to another page and they can start viewing the content based on their city("ciudad").
My homepage checks if the session has items:
def index(request):
#Checks to see if the session has items, in particular if a city has been set
if not request.session.items():
return render_to_response('index.html', context_instance=RequestContext(request))
else:
return redirect(Cartelera)
Now lets suppose for some reason the user deletes his cookies and on the site he visits a url different than the homepage(something like www.site.com/cartelera) he would then get an error because the session variable "ciudad" is not set.
Is there a way to create a default value for this session variable in case that it has not been set?
Or what is a good practice to deal with this issue?
Use the dict.get method on the session to retrieve a default if the value isn't set, like this:
city = request.session.get('ciudad', 'default value')
For my website pretty much every page has a header bar displaying "Welcome, ABC" where "ABC" is the username. That means request.user will be called for every single request resulting in database hits over and over again.
But once a user is logged in, I should be able to store his user instance in his cookie and encrypt it. That way I can avoid hitting the database repeatedly and just retrieve request.user from the cookie instead.
How would you modify Django to do this? Is there any Django plugins that does what I need?
Thanks
You want to use the session middleware, and you'll want to read the documentation. The session middleware supports multiple session engines. Ideally you'd use memcached or redis, but you could write your own session engine to store all the data in the user's cookie. Once you enable the middleware, it's available as part of the request object. You interact with request.session, which acts like a dict, making it easy to use. Here are a couple of examples from the docs:
This simplistic view sets a has_commented variable to True after a user posts a comment. It doesn’t let a user post a comment more than once:
def post_comment(request, new_comment):
if request.session.get('has_commented', False):
return HttpResponse("You've already commented.")
c = comments.Comment(comment=new_comment)
c.save()
request.session['has_commented'] = True
return HttpResponse('Thanks for your comment!')
This simplistic view logs in a "member" of the site:
def login(request):
m = Member.objects.get(username=request.POST['username'])
if m.password == request.POST['password']:
request.session['member_id'] = m.id
return HttpResponse("You're logged in.")
else:
return HttpResponse("Your username and password didn't match.")
This smells of over-optimisation. Getting a user from the db is a single hit per request, or possibly two if you use a Profile model as well. If your site is such that an extra two queries makes a big difference to performance, you may have bigger problems.
The user is attached to the request object using the Authentication Middleware provided by django (django.contrib.auth.middleware). It users a function the get_user function in django.contrib.auth.init to get the user from the backend you are using. You can easily change this function to look for the user in another location (e.g. cookie).
When a user is logged in, django puts the userid in the session (request.session[SESSION_KEY]=user.id). When a user logs off, it erases the user's id from the session. You can override these login and logoff functions to also store a user object in the browsers cookie / erase user object from cookie in the browser. Both of these functions are also in django.contrib.auth.init
See here for settting cookies: Django Cookies, how can I set them?
Once you have proper caching the number of database hits should be reduced significantly - then again I'm not really and expert on caching. I think it would be a bad idea to modify request.user to solve your problem. I think a better solution would be to create some utility, method or custom template tag that attempts to load your require user data from the cookie, and return the result. If the user data is not found in the cookie, then a call to request.user should be made, save the data to the cookie, and then return the result. You could possibly use a post_save signal to check for changes to the user data, so that you can make update to the cookie as required.
I redirect the user to the home page after logout. In between I would like to delete all/or specific client cookies (I have previously set).
def logoutuser(request):
logout(request)
return redirect('app.home.views.home')
To call response.delete_cookie('user_location'), there is no response object. How do I do this?
Like jobscry said, logout() cleans session data, but it looks like you have set your own cookies too.
You could wrap auth logout view, which will return a HttpResponse:
def logout_user(request):
response = logout(request, next_page=reverse('app.home.views.home'))
response.delete_cookie('user_location')
return response
Or if you're just using the logout method as opposed to the view, you can use the return value for the redirect() method you have (which I assume returns a HttpResponse too).
def logout_user(request):
logout(request)
response = redirect('app.home.views.home')
response.delete_cookie('user_location')
return response
according to http://docs.djangoproject.com/en/dev/topics/auth/#django.contrib.auth.logout
Changed in Django 1.0: Calling logout() now cleans session data.
Hope this helps:
delete cookie when caling "/clear-cookies"
location.href = '/clear-cookies';
Define a method in views.py:
def clear_cookies(request):
response = HttpResponseRedirect('/')
response.delete_cookie('_gat', domain='example.com')
response.delete_cookie('_ga', domain='example.com')
response.delete_cookie('_gid', domain='example.com')
return response
Add the path and method to your urls.py:
url(r'^clear-cookies', clear_cookies),
This is slightly tangential, but maybe helpful to others in a similar situation.
If you are setting cookies that need to be deleted when the user logs out, maybe you shouldn't be using cookies in the first place. For that use case, it's much better to use session data instead. Like:
request.session['myKey'] = myValue
retrievedValue = request.session.get('myKey')
From the docs: "The session framework lets you store and retrieve arbitrary data on a per-site-visitor basis. It stores data on the server side and abstracts the sending and receiving of cookies".
Using session data is more secure and more performant than setting cookies, because the data stays on the server side.
The only use case where I would recommend setting your own cookies is if you need to store information that persists beyond a session (say you want to store preferences across sessions for a visitor who does not sign in).