Posts

Showing posts with the label django-views

How can I write my own decorator in Django?

How can I write my own decorator in Django? My models.py file is as follow: models.py from django.contrib.auth.models import User class Shopkeeper(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) # ... class Customer(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) # ... And I have some views which only Customers can access after login, but Shopkeepers cannot. And vice versa. How can I write decorator for such task? 1 Answer 1 There is nothing magical about a decorator, it is a function that takes as input the function (or class) to decorate, and makes some changes to it. If we look at the login_required decorator [GitHub], we see: login_required def login_required(function=None, redirect_field_name=REDIRECT_FIELD_NAME, login_url=None): """ Decorator for views that checks tha...

Django url namespaces giving errors

Django url namespaces giving errors I am new to the django framework. I currently started learning from an online video tutorial and I came across some errors. I have an app called groups which has two separate view files namely company and family. Due to that I have my groups/url file as this: from django.urls import path, include, re_path from . views import company from . views import family app_name = 'groups' company_patterns = [ path('create/', company.Create.as_view(), name='create'), re_path(r'^edit/(?P<slug>w+)/$', company.Update.as_view(), name='update'), path('<str:slug>/', company.Details.as_view(), name='detail'), ] family_patterns = [ path('create/', family.Create.as_view(), name='create'), path('edit/<str:slug>/', family.Update.as_view(), name='update'), path('<str:slug>/', fami...

Calling user follow/follower list in Django

Calling user follow/follower list in Django Hi Djangonauts, I am trying to get the user follows list(example like Instagram 'A' follows 'B') in the templates. I have tried almost everything I am not able to call it in the templates. What am I doing wrong My models (It's a monkey patch to the Django User model) class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) #other profile fields class Contact(models.Model): user_from = models.ForeignKey(User, related_name='supporter') user_to = models.ForeignKey(User, related_name='leader') def __str__(self): return '{} follows {}'.format(self.user_from, self.user_to) User.add_to_class( 'following', models.ManyToManyField( 'self', through=Contact, related_name='followers', symmetrical=False)) My views (not sure if this is correct) def get_context_data(self, *...