Django custom manager request object/current user - django

I have made a custom manager by creating a class inheriting from models.Manager.The manager just changed the default model.objects query to add some filters. Now, I want to add a filter according to the user logged in. I dont want to have to search through code changing what params are added, is there any way I can get the request object/current user without passing it through to the method?
Im hoping this is not a stupid question, but I may just be getting confused...
This is the basic setup of the Manager
class pubManager(models.Manager):
def get_queryset(self):
return pubEnt.objects.filter(state='new')
def on_site(self):
return pubEnt.objects.filter(state='old', val=0)

There is no way in django to access the current request without passing it. If can't live without it you should probably rethink your design! Having access to the request shouldn't be a requirement of a manager's method, since it could also be accessible from somewhere where you do not have a request object (think for example of calling the method from the python shell). If you need access to the currently logged-in user, pass the user object to the method (from request.user), but not the whole request!

Global Django requests
http://nedbatchelder.com/blog/201008/global_django_requests.html

Related

Whats the different between override the update method inside view and inside serializers?

I am new in django i know this is a naive question but im so confused about when exactly do we have to override update method located in view and when do we have to override update method located in serializer?
From the documentation:
1) Creating, Updating in views:
perform_create(self, serializer)
perform_update(self, serializer)
perform_destroy(self, serializer)
These hooks are particularly useful for setting attributes that are implicit in the request, but are not part of the request data. For instance, you might set an attribute on the object based on the request user, or based on a URL keyword argument.
These override points are also particularly useful for adding behavior that occurs before or after saving an object, such as emailing a confirmation, or logging the update.
You can also use these hooks to provide additional validation, by raising a ValidationError(). This can be useful if you need some validation logic to apply at the point of database save.
2) Creating, Updating in serializers:
If we want to be able to return complete object instances based on the validated data we need to implement one or both of the .create() and .update() methods.
If your object instances correspond to Django models you'll also want to ensure that these methods save the object to the database.
Also you can override create, update methods for nested operations.

django access request data (without POST or GET )

Is there any way to access the request data without specifying the request method - GET or POST ?
I have a class based view which uses POST with some parameters.
Sometimes for some tests/debugging I want to use this view with a GET method, but then I need to change all the parameters to request.GET instead of request.POST.
Since my view is class based, I've already specify the method in the class by choosing post/get method. So I would prefer to access both GET and POST data together.
No, Django does not provide a way to do this. It once had a request.REQUEST attribute, but it was deprecated in Django 1.7 and removed in Django 1.9.
It was removed because there was consensus that treating request.GET and request.POST the same was not a good idea. See the mailing list discussion for more info.

How does viewset aligns with rest methods

I am relatively new to DRF, but found viewsets an amazing abstraction technique for writing RESTful API. I am having a hard time correlating Viewsets with REST methods though. Let's say I have a viewset for Userprofiles and somebody new creates a profile on client.
Should this send a PUT or a POST ?
Which url should this request go to, http://user or http://user/new_id ?
If I want this profile only accessible to the user or admin(all CRUD operations), then where should I handle the code for making it inaccessible to others ?
Should I create a new permission ? If yes, should I handle rest methods in has_permission/has_object_permission ?
I have gone through the tutorial, and know how permissions/mixins works, but I am not able to connect these dots here.
1/ In general, POST is for creating new, PUT is for updating. See the docs on the SimpleRouter to show how the various types of Http methods align with various actions in your Django backend.
2/ You'll find that different situations call for different routing methods. If yours is standard, you may want to use a SimpleRouter like the example above. In that case, creating a new user would be a POST request to /user/ and updating a user would be a PUT request to /user/{{user_id}}/.
3/ To limit access to various API methods, you want to use Permissions. It's possible that you could use one of DRF's Custom Permissions. I've found that in general, if you want only the user to access his/her own profile, it's easier to either use conditional logic within a view (i.e., return a DRF PermissionDenied exception in the view logic if the request.user.pk is not the pk of that REST url. More often than not, I've used the UserPassesTestMixin from Django Braces, that works pretty well to filter user permissions.
4/ I guess the Django Braces mixin above answers this question. You should include a test_func method if you're using Django Braces that returns True if you want to grant the user access, and False otherwise.
Hope this helps! I agree that these are difficult parts of DRF and perhaps some of these could more effectively get incorporated into the source. Good luck!

Managing UserContext in Django

Im using the following statement to set Language Option in my projects which works as expected.
request.session['django_language'] = "de"
This is fine with in View, but when the control goes to other files to connect to DB or external services how can I access it. I dont want to pass the request object through out all the application.
If something like UserContext/RequestContext where every request has to go-through it (Middleware) so that I can set it there and access it without help if request object.
I understand from the headline that you want to store the language per user.
It might be best to extend the user model and add a model field for preferred_language.

How do I set session variables at login using django-registration and auth?

I'm using django-registration to log users into my application. That part works fine. The part that I cannot figure out is how to set custom session variables when the user logs in. For instance, I'd like to populate variables containing UserProfile data as well as the output of a few other functions. Then I'd be able to use that information in subsequent views/templates.
If anybody can point me to a tutorial online or post some sample code, that would be great.
I'm using django 1.1 and Python 2.6
If you don't want persistent storage of user data (just additional session data) have a look at:
http://docs.djangoproject.com/en/dev/topics/http/sessions/
The sessions framework will most probably be already enabled if you use django.contrib.auth.
If you want persistent storage of additional user data (not only in a session, but in the database), you will store them in another "profile" model:
http://docs.djangoproject.com/en/dev/topics/auth/#storing-additional-information-about-users
I realize #stefanw provided you an alternative solution, but to answer the original question:
Setting session data at login is difficult because the easiest place to set that data is in your view function, and the particular view function you'd want to modify is a part of the contrib.django.auth app.
So your options would be the following:
Create a small middleware class to set your session data.
Create a template tag or other bit of code than can be integrated into the login template or subsequent page that will set the data you want.
Write your own custom login view function (it's really quite easy, actually).
Happy django-ing!