django-unicorn
django-unicorn copied to clipboard
How would decorators work with UnicornView ?
I recently started implementing Django-Uniorn on a personal project and I'M LOVING IT so far. However I'm having a litle problem where I try to implement a simple decorator (similar to login_required) and I can't get it working with my UnicornView component. The view seems to ignore (when implementing it with @method_decorator(login_required, name='dispatch')) and I've tried implementing it in other ways but I just can't get it to work.
Any help is welcome !
I'm also very excited with unicorn and looking forward to start contributing and trying to improve it once I have a better understanding of how everything workds !!!
Are you trying to decorate a particular method in a UnicornView class? If you can give me some sample code I can dig into what might be going on!
I'm trying to decorate the whole component, so that when it's called, if the user is not authenticated, unicorn triggers a javascript function I have that shows a modal that then the user can use to then login / sign up (as I've read in the documentation that unicorn can call js functions via the self.call("", "") method.
I haven't figured out how to create that custom decorator, but I've tried this:
from django.utils.decorators import method_decorator
from django.contrib.auth.decorators import login_required
from django_unicorn.components import UnicornView
@method_decorator(login_required, name='dispatch')
class LikeView(UnicornView):
product = None # Product is assigned when calling the component {% unicorn 'like' <myproduct> %}
template_name = "app/components/product/like.html"
def like(self):
self.request.user.favorites.add(self.product)
What currently happens when I try to like a product without being authenticated is that I recive an error message "AttributeError: 'AnonymousUser' object has no attribute 'favorites'" which indicates me that login_required is not being called, as far as I understand it...
I've also tried decorating my like method with "@login_required" right above it, but nothing seems to change.
Thanks a lot for the response !
This issue seems similar to what you are looking to do. For my own code, I tend to override mount and do an auth check there (a decorator should work as well) since that will get called before any action gets called.
Thanks !!! I'll try to implement it that way.
I'm going to close this issue because I think there is a way forward. However, let me know if I could add something to make this work better. Or if I should update the docs with an example, maybe?