I want the post method in the class-based view to be atomic. I have defined the class so:
class AcceptWith(View):
#method_decorator(login_required)
#method_decorator(user_passes_test(my_test))
#method_decorator(transaction.atomic)
def dispatch(self, *args, **kwargs):
return super(AcceptWith, self).dispatch(*args, **kwargs)
Is this correct?
Can I make only the post method atomic?
Assuming that you're defining your own method to handle the POST, just apply the transaction.atomic decorator directly to that method.
class AcceptWith(View):
#transaction.atomic
def post(self, request, *args, **kwargs):
# your code here will be executed atomically
I think you should not wrap whole method, also you may want custom handler execute after rollback
def post(self, request, *args, **kwargs)
try:
with transaction.atomic():
pass # CRUD operations
except IntegrityError:
handle_exception() # this will run after rollback
https://docs.djangoproject.com/en/dev/topics/db/transactions/
Related
I have RetrieveUpdateDestroyAPIView view like this.
class TaskRetrieveUpdateDestroyAPIView(RetrieveUpdateDestroyAPIView):
lookup_field = 'id'
serializer_class = TasksSerializer
def get_queryset(self):
query_set=Task.objects.get(id=self.kwargs['id'])
def get(self, request, *args, **kwargs):
return self.retrieve(request, *args, **kwargs)
def put(self, request, *args, **kwargs):
return self.update(request, *args, **kwargs)
def patch(self, request, *args, **kwargs):
return self.partial_update(request, *args, **kwargs)
def delete(self, request, *args, **kwargs):
return self.destroy(request, *args, **kwargs)
and my urls like this
path('task_detail/<int:id>', TaskRetrieveUpdateDestroyAPIView.as_view(), name="get_task"),
I am trying to PUT , PATCH , GET but getting same error
{
"detail": "Not found.",
"status_code": 404
}
The issue is in the function get_queryset, It expects a queryset but yours returns a single object, that's what the get function does as described here. So, you need to either set the queryset class field or use the get_queryset function.
You don't need to look up the task object yourself, that's what the generic view does for you. also you don't have to specify the method handlers(get, post, i.e.) yourself, they are already generated because you use RetrieveUpdateDestroyAPIView class. Also, since the lookup field defaults to the primary key(id), so, you could omit that, too
Try this code
class TaskRetrieveUpdateDestroyAPIView(RetrieveUpdateDestroyAPIView):
queryset = Task.objects.all()
serializer_class = TasksSerializer
and use pk instead of id
path('task_detail/<int:pk>', TaskRetrieveUpdateDestroyAPIView.as_view(), name="get_task")
or you could leave the lookup field as id and use it in the path function. It's pretty much the same thing, just saving some code
I noticed that I am setting site-wide context variables and request variables for many views on my site. Naturally, this situation calls for inheritance. If all of my view class-based views are inheriting from SiteView instead of the generic View, I can factor out all the commonalities into the SiteView child class. I can then inherit from SiteView on all my views. But, I cannot get this to work. Here is my code:
from django.contrib.auth.decorators import login_required
from django.views.generic import View
from django.utils.decorators import method_decorator
class SiteView(View):
''' Extends the generic django-supplied View class '''
#method_decorator(login_required)
def dispatch(self, request, *args, **kwargs):
return super(SiteView, self).dispatch(*args, **kwargs)
def get(self, *args, **kwargs):
''' Adds the variables required in the get request '''
context = super(SiteView, self).get(*args, **kwargs)
context['common_var'] = 'some common value'
context['user'] = request.user
return self.render_to_response(context)
This throws the following TypeError:
dispatch() missing 1 required positional argument: 'request'
Any help would be appreciated
Edit: Even though the correct answer is marked, there were other issues with the code. In particular, the get method of the SiteView should not have the following line:
context = super(SiteView, self).get(*args, **kwargs)
This is because the View class does NOT have any get method.
You forgot to pass the request to the super().dispatch(..) call:
class SiteView(View):
#method_decorator(login_required)
def dispatch(self, request, *args, **kwargs):
return super(SiteView, self).dispatch(request, *args, **kwargs)
or you can just omit the request in the dispatch parameters, and thus pass it through *args and **kwargs:
class SiteView(View):
#method_decorator(login_required)
def dispatch(self, *args, **kwargs):
return super(SiteView, self).dispatch(*args, **kwargs)
It is however probably more elegant, to pass the name of the function, like:
#method_decorator(login_required, name='dispatch')
class SiteView(View):
# ...
EDIT: Note that a View has no get(..), post(..), etc. method. The dispatch(..) method will look if such method exists, and if so redirect to it. If such method does not exists, it will return a "405 Method Not Allowed" response.
Your get(..) function thus be implemented like:
#method_decorator(login_required, name='dispatch')
class SiteView(View):
''' Extends the generic django-supplied View class '''
def render_to_response(self, context):
# ...
def get(self, request, *args, **kwargs):
context = {
'common_var': 'some common value',
'user': request.user
}
return self.render_to_response(context)
It perhaps makes more sense to implement a "mixin" (perhaps with a subclass of the LoginRequiredMixin mixin [Django-doc].
For example like:
class SiteViewMixin(LoginRequiredMixin):
def get_context_data(self, *args, **kwargs):
context = super().get_context_data(*args, **kwargs)
context.update(common_var='some common value', user=self.request.user)
return context
and then use the mixin in another view, like:
class SomeView(SiteViewMixin, TemplateView):
# ...
I have this CBV:
class GetStuff(View):
def get(self, request, company_id):
...
I want to decorate the get function with a custom function which takes the request and company_id arguments and check some permissions.
Any idea on how to achieve this? Most information I've found about decorators focus on FBV.
This is what I have so far:
def custom_decorator(func_view):
def wrapper(request, company_id):
if not request.user.is_staff:
# do_something()
return func_view(request, company_id)
return wrapper
You have to decorate the dispatch method
To decorate every instance of a class-based view, you need to decorate the class definition itself. To do this you apply the decorator to the dispatch() method of the class. django doc
from django.utils.decorators import method_decorator
class GetStuff(View):
#method_decorator(custom_decorator)
def dispatch(self, *args, **kwargs):
return super(GetStuff, self).dispatch(*args, **kwargs)
or
#method_decorator(custom_decorator, name='dispatch')
class GetStuff(View):
def dispatch(self, *args, **kwargs):
return super(GetStuff, self).dispatch(*args, **kwargs)
you can find other decorating techniques in the docs
I am trying to implement staff_member_required mixins:
Here are the two ways I found on how to do so:
First:
class StaffRequiredMixin(object):
#method_decorator(login_required)
def dispatch(self, request, *args, **kwargs):
if not request.user.is_staff:
messages.error(
request,
'You do not have the permission required to perform the '
'requested operation.')
return redirect(settings.LOGIN_URL)
return super(StaffRequiredMixin, self).dispatch(request,
*args, **kwargs)
Second:
class StaffRequiredMixin(object):
#classmethod
def as_view(self, *args, **kwargs):
view = super(StaffRequiredMixin, self).as_view(*args, **kwargs)
return staff_member_required(view)
#method_decorator(login_required)
def dispatch(self, request, *args, **kwargs):
if not request.user.is_staff:
messages.error(
request,
'You do not have the permission required to perform the '
'requested operation.')
return redirect(settings.LOGIN_URL)
return super(StaffRequiredMixin, self).dispatch(request,
*args, **kwargs)
What I want to know is:
Why the second way is overriding the as_view() method and wrapping it with staff_member_required ?
Do we get any 'additional' advantages by doing so ?
I am new to these mixins. Please help.
TL; DR: they're close to the same, the difference is in checking is_active as well as is_staff and the error messages. You probably don't need both because the as_view override negates the need for the dispatch override anyway.
These are really just two ways of doing close to the same thing.
This code:
class StaffRequiredMixin(object):
#classmethod
def as_view(self, *args, **kwargs):
view = super(StaffRequiredMixin, self).as_view(*args, **kwargs)
return staff_member_required(view)
...could actually be used alone to implement the staff_member_required decorator. In this case the staff_member_required functionality gets called in the view's as_view() function (i.e., from as_view() in your URLConf).
This code:
class StaffRequiredMixin(object):
#method_decorator(login_required)
def dispatch(self, request, *args, **kwargs):
if not request.user.is_staff:
messages.error(
request,
'You do not have the permission required to perform the '
'requested operation.')
return redirect(settings.LOGIN_URL)
return super(StaffRequiredMixin, self).dispatch(request,
*args, **kwargs)
...filters users in the dispatch method. You can see in the Django codebase that as_view actually calls dispatch. This means that if you use both together you won't actually ever trigger the if not request.user.is_staff code in the dispatch method because any user who doesn't pass would have been filtered out in the as_view method.
The second difference is that staff_member_required is slightly different from what the first code does. If you check out the code, you'll notice that staff_member_required also checks whether the user's is_active flag passes (not just is_staff like in your dispatch decorator). It also doesn't pass the messages.error like in your code.
What it says on the tin. Is there a way to make a Django model read-only?
By this I mean a Django model in which once records have been created, they can't be edited.
This would be useful for a model that records transaction history.
You can override the model's save method and check whether it's an existing entity, in which case you won't save any changes:
def save(self, *args, **kwargs):
if self.id is None:
super(ModelName, self).save(*args, **kwargs)
So in this example you only save the changes when the entity has not got an id yet, which is only the case when it's a new entity that hasn't been inserted yet.
You can override the save method and not call super if you wanted to. That'd be a fairly easy way of accomplishing this.
# blatantly ripped the save from another answer, since I forgot to save original model
def save(self, *args, **kwargs):
if self.id is None:
super(ModelName, self).save(*args, **kwargs)
def delete(self, *args, **kwargs):
return
You should probably also raise an exception if a delete or update is attempting to occur instead of simply returning. You want to signal the user what is happening - that the behaviour isn't valid.
In addition to other solutions: If your main goal is to avoid write access from the admin, you can modify the used admin class so that nobody has an add/change permission:
class HistoryAdmin(admin.ModelAdmin):
def has_add_permission(self, request):
return False
def has_change_permission(self, request, obj=None):
return False
def has_delete_permission(self, request, obj=None):
return False
If you don't want an attempt to modify a record to fail silently:
def save(self, *args, **kwargs):
if self.pk:
(raise an exception)
super(YourModel, self).save(*args, **kwargs)
def delete(self, *args, **kwargs):
(raise an exception)