Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: how can I pass a variable from one view to another?
As the title, how can I pass a variable from a Django view to another? def my_view_one(request): from .views import my_view_two if my_view_two.editting == True: print("You're now editting an existing object. ") #The stuff I need to do here my_view_two.editting = False else: print("You're now creating a new object. ") #The stuff I need to do here return HttpResponse("My http response.") def my_view_two(request): editting = True print("You entered here and now editting is set to True. ") Using a global variable is a good solution for me too. I tried it but it returned always a False value. Any idea? -
Populating form field based on another models foreign key <user> - Django
I have 2 models one for a Club & one for a Team. The Club model contains a foreign key for the user. The Team model contains a foreign key to the Club. I am currently looking to auto populate and hide the "club_id" field in the Team form based on the logged in user. So each "User" is associated to a "Club" and each "Club" has multiple "Teams". Can this be accomplished in forms.py or must I do something in the view? Models.py class ClubInfo(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) club_name = models.CharField(max_length=50, default='', unique=True) club_logo = models.ImageField(upload_to='profile_pics', blank=True) club_address1 = models.CharField(max_length=30) club_address2 = models.CharField(max_length=30, default='') club_address3 = models.CharField(max_length=30, default='') club_town = models.CharField(max_length=30) club_county = models.CharField(max_length=30) club_country = models.CharField(max_length=30) created_date = models.DateTimeField(default=timezone.now) def __str__(self): return self.club_name class Team(models.Model): club_id = models.ForeignKey(ClubInfo, on_delete=models.CASCADE) team_name = models.CharField(max_length=30) manager_name = models.CharField(max_length=20) def __str__(self): return self.team_name Forms.py class ClubInfoForm(forms.ModelForm): class Meta(): model = ClubInfo fields = ('club_name', 'club_logo', 'club_address1', 'club_address2', 'club_address3', 'club_town', 'club_county', 'club_country',) class TeamForm(forms.ModelForm): class Meta(): model = Team fields = ('club_id', 'team_name', 'manager_name') def __init__(self, *args, **kwargs): super(TeamForm, self).__init__(*args, **kwargs) self.fields['club_id'].widget = forms.HiddenInput() -
I have setup crontab for run task in 5 mins intervel
I have setup crontab in Django application for a run task in 5 mins interval. after run 1st time getting an error in syslog of the server. below is the log. Feb 5 13:23:42 backend-dev bash[26913]: [2019-02-05 18:53:42,378: WARNING/MainProcess] Traceback (most recent call last): Feb 5 13:23:42 backend-dev bash[26913]: [2019-02-05 18:53:42,378: WARNING/MainProcess] File "/usr/local/bin/celery", line 11, in Feb 5 13:23:42 backend-dev bash[26913]: [2019-02-05 18:53:42,379: WARNING/MainProcess] sys.exit(main()) Feb 5 13:23:42 backend-dev bash[26913]: [2019-02-05 18:53:42,379: WARNING/MainProcess] File "/usr/local/lib/python3.6/dist-packages/celery/__main__.py", line 16, in main Feb 5 13:23:42 backend-dev bash[26913]: [2019-02-05 18:53:42,379: WARNING/MainProcess] _main() Feb 5 13:23:42 backend-dev bash[26913]: [2019-02-05 18:53:42,379: WARNING/MainProcess] File "/usr/local/lib/python3.6/dist-packages/celery/bin/celery.py", line 322, in main Feb 5 13:23:42 backend-dev bash[26913]: [2019-02-05 18:53:42,380: WARNING/MainProcess] cmd.execute_from_commandline(argv) Feb 5 13:23:42 backend-dev bash[26913]: [2019-02-05 18:53:42,380: WARNING/MainProcess] File "/usr/local/lib/python3.6/dist-packages/celery/bin/celery.py", line 496, in execute_from_commandline Feb 5 13:23:42 backend-dev bash[26913]: [2019-02-05 18:53:42,380: WARNING/MainProcess] super(CeleryCommand, self).execute_from_commandline(argv))) Feb 5 13:23:42 backend-dev bash[26913]: [2019-02-05 18:53:42,381: WARNING/MainProcess] File "/usr/local/lib/python3.6/dist-packages/celery/bin/base.py", line 275, in execute_from_commandline Feb 5 13:23:42 backend-dev bash[26913]: [2019-02-05 18:53:42,381: WARNING/MainProcess] return self.handle_argv(self.prog_name, argv[1:]) Feb 5 13:23:42 backend-dev bash[26913]: [2019-02-05 18:53:42,381: WARNING/MainProcess] File "/usr/local/lib/python3.6/dist-packages/celery/bin/celery.py", line 488, in handle_argv Feb 5 13:23:42 backend-dev bash[26913]: [2019-02-05 18:53:42,382: WARNING/MainProcess] return self.execute(command, argv) Feb 5 13:23:42 backend-dev bash[26913]: [2019-02-05 18:53:42,382: WARNING/MainProcess] File "/usr/local/lib/python3.6/dist-packages/celery/bin/celery.py", line 420, in execute … -
What happens during AWS Elastic Beanstalk 504 Gateway Timeout
I have a Django server running in Elastic Beanstalk and I am not sure if the process continues to run in the server or the process gets killed. Does anyone have any insight on this? There is no application logic to stop the request in case of a disconnection. Would Elastic Beanstalk kill off the process along with the client connection or will the process continue to run regardless of the timeout? -
How does frontend-backend communication work with React & Django (OAuth2)?
Following the Python Social Auth guide, I have set Google OAuth2 with Django: https://github.com/python-social-auth/social-app-django A user can log-in via Google, signup via an access token (which is stored in a Social Auth table linked to User). I wanted some pointers around how would I add an authentication wrapper around every method in my views? Do I need to run an authentication check in every method? Or explore middlewares? I know the flow, I am just trying to find out what’s the Django way of doing it. Please note that with every method called by the frontend, the passed access token should be verified with Google, and only then should a user be allowed through. I can share code if needed. -
UnboundLocalError and TypeError in Django
I am getting error. UnboundLocalError at /timesheet/report/ local variable 'qs' referenced before assignment class ReportView(LoginRequiredMixin, generic.ListView): template_name = 'report/report.html' paginate_by = constants.PAGINATED_NUMBER context_object_name = 'reports' def get_queryset(self, *args, **kwargs): try: timesheet_latest_ids = TimesheetEntry.objects.raw('SELECT MAX(id) as id FROM timesheet_entry WHERE timesheet_is_running = 0 GROUP BY timesheet_users_id ORDER BY timesheet_clock_out_on DESC') list1 = [] for timesheet_latest_id in timesheet_latest_ids: list1.append(timesheet_latest_id.id) result = TimesheetEntry.objects.filter(id__in=list1) if self.request.user.userprofile.user_role.id == 2 : # 2 for admin qs = TimesheetEntry.objects.filter( id__in=list1 ).filter( timesheet_users__userprofile__user_company=self.request.user.userprofile.user_company ) if self.request.user.userprofile.user_role.id == 3 : # 3 for manager qs = TimesheetEntry.objects.filter( id__in=list1 ).filter( timesheet_users__userprofile__user_company=self.request.user.userprofile.user_company ).exclude(timesheet_users__userprofile__user_role_id=3) | TimesheetEntry.objects.filter(timesheet_users__pk=self.request.user.pk) if self.request.user.userprofile.user_role.id == 4 : # 4 for employee qs = TimesheetEntry.objects.filter(timesheet_users=self.request.user.id).latest('id') except TimesheetEntry.DoesNotExist: qs=None return qs If i put qs=None in except something like this except TimesheetEntry.DoesNotExist: qs = None Then i am getting error like this TypeError at /timesheet/report/ object of type 'NoneType' has no len() How can i return None -
Cached computed fields - effective batch updating
I'm looking for an effective way to update a cached computed field on a related model when batch-deleting Django objects - an example: class Parent: child_count = IntegerField() class Child: parent = ForeignKey(Parent, related_name='children') Here, child_count is a cached version of the .annotate(Count('children')) lookup. The problem arises when batch-deleting lots of children based on fields other than parent. My current options are: Update child_count in Child's post_save and pre_delete signals. Pros: easy and no code duplication, works with both normal and batch deletion Cons: very slow at batch deletion as Django has to call the handler for each object separately. Handle the cascading myself and use _raw_delete() Pros: fast Cons: boilerplate code for each additional FK, care must be taken to use this custom implementation everywhere Children are being deleted. I suppose the perfect solution would have been a "Queryset-level" signal handling, but I couldn't find a nice way to implement that. -
NoReverseMatch at /fileupload/ :Reverse for 'view' not found. 'view' is not a valid view function or pattern name
I'm trying to create a file upload page. I get this error just after successfully logging in. I don't what I'm missing looked over StackOverflow. There are many posts just like this but I'm not getting what to do in my code. Any help will be appreciated Error during template rendering In template /Users/mac/mrpash/csimplifypd/pd/templates/base.html, error at line 16 Exception Type: NoReverseMatch at /fileupload/ Exception Value: Reverse for 'view' not found. 'view' is not a valid view function or pattern name. Here is my Urls.py from django.urls import path from django.conf import settings from pd.views import FileUpload, Index, GetText urlpatterns = [ path('', Index.index, name='login'), path('fileupload/', FileUpload.fileup, name='fileupload'), path('detected/', GetText.fileget, name='detected'), ] also i divided my views into three different files. they are FileUpload.py from pd.forms.FileUploadForm import DocumentForm from django.shortcuts import render, redirect from django.conf import settings from django.core.files.storage import FileSystemStorage def fileup(request): if request.method == 'POST': form = DocumentForm(request.POST, request.FILES) if form.is_valid(): form.save() return redirect("fileupload") else: form = DocumentForm() return render(request, 'pd/FileUpload.html', {'form': form}) GetText.py from django.shortcuts import render from pd.models.ImageUpload import Img # Create your views here. def fileget(request): if request.method == 'GET': imgs = Img.objects.all() return render(request, "pd/DetectedText.html", {'imgs': imgs}) Index.py from django.shortcuts import render from pd.models.UserForm import … -
Event Sourcing With an Event Store and an ORM
I am building an Authentication Service with Django for a micro-services architecture. its more of an experiment than a real world implementation to understand more about event sourcing. I do understand that Django has an ORM which is very coupled with the framework and using Flask would be an easier approach but i am trying to figure out a way around it. The use case is very simple. A user registers he would get an email to activate his account. a user gets activated again i shoot an email to inform him about his account being active. From my understanding is that in an event sourced system. events are triggered and stored and we can get the latest state and store it in a database for example. in my case it would be Postgres using Django ORM. I publish the event to kafka using the signals in django. pre_save() signals. and then the model will save the object. In case of an update which is not yet implemented bellow. I would publish only the updated fields. and update the object in Django. Does anyone see any caveats with this approach or would it be better to implement this in the … -
django-otp implementation using custom Views
I have been trying to implement the django-otp with qrcode using custom Forms and Views. The problem is I am a little caught up on whether my implementation is correct or not. As the documentation states that a request.user.is_verified() attribute is added to users who have been OTP verified, I am actually not able to get it right. Have created confirmed TOTP device for user with the QR code setup using Microsoft Authenticator app. I was able to successfully implement the default Admin Site OTP verification without any issues. Below is the files for the custom implementation. urls.py from django.conf.urls import url from account.views import AccountLoginView, AccountHomeView, AccountLogoutView urlpatterns = [ url(r'^login/$', AccountLoginView.as_view(), name='account-login',), url(r'^home/$', AccountHomeView.as_view(), name='account-home',), url(r'^logout/$', AccountLogoutView.as_view(), name='account-logout',) ] views.py from django.contrib.auth import authenticate, login as auth_login from django.views.generic.base import TemplateView from django.views.generic.edit import FormView from django_otp.forms import OTPAuthenticationForm class AccountLoginView(FormView): template_name = 'login.html' form_class = OTPAuthenticationForm success_url = '/account/home/' def form_invalid(self, form): return super().form_invalid(form) def form_valid(self, form): # self.request.user returns AnonymousUser # self.request.user.is_authenticated returns False # self.request.user.is_verified() returns False username = form.cleaned_data.get('username') password = form.cleaned_data.get('password') otp_token = form.cleaned_data.get('otp_token') otp_device = form.cleaned_data.get('otp_device') user = authenticate(request=self.request, username=username, password=password) if user is not None: device_match = match_token(user=user, token=otp_token) # device_match … -
Django: How to edit value and store back in database
I'm working on an attendance register. So I've got an HTMl checkbox form where user can tick if person is here. If they are then the views will pull out the number of lessons person has in database and subtract 1 from the value. How can I achieve this? This is done using Django. views.py: def present(request): students = Student.objects.filter(squad='LearnToSwim1') completed = request.GET.get('pre') for stu in students: if request.POST.get('completed', '') == 'on': print("Present!") #I don't know what to do here to extract the lessons_left and subtract 1 from it. else: print("Not present") models.py: class Student(models.Model): student_name = models.CharField(max_length=200) squad = models.CharField(max_length=30, choices=SQUAD, default='INSERT_SQUAD') lessons_left=models.IntegerField(default=0) def __str__(self): return self.student_name presentform.html: <form action="/present/" method="POST"> {% csrf_token %} <p> <input type="checkbox" id="completed" name="completed" /> <label for="completed">Present</label> </p> <input class="waves-effect waves-light btn" type='submit'/> </form> -
Django, Redis: Where to put connection-code
I have to query redis on every request in my Django-app. Where can I put the setup/ connection routine (r = redis.Redis(host='localhost', port=6379)) so that I can access and reuse the connection without having to instantiate a new connection in my views? -
How to allow Django Rest API to only work for a particular cors request and not through browser or command line curl
I have a Django REST API and I want it to be only accessible from a cross origin request from my react frontend, and not from the browser or command line. How can I achieve this? I installed django-cors-headers and put my frontend url in the CORS_ORIGIN_WHITELIST and put it in MIDDLEWARE and INSTALLED_APPS. The call works from my frontend, but it still also works from the browser, how can I remove that? -
How to update django model field every month using cron?
I have a model in django in which one Integer field is there. I want to update that field every month using cron job. Lets say 1st of every month the field would update . Example: class Demo(models.Model): data = models.IntegerField(default = 1) def __str__(self): return str(self.data) Now I want to increment data field by 1 every month. -
Set values for form field by query using filter
I want to set the item in dropdown using the query in the form. I want to add employee and the select company which using filter Is_Del= 0. I do not know how to set values for the drop down and where to write this query. I tried to put in Forms.py, but it is not working. This is form.py class EmployeeCreateForm(forms.ModelForm): class Meta: model = Employee fields = ('Emp_Name','Emp_company','Emp_Dept','Emp_Join_Date', 'Emp_End_Date') def clean(self): cleaned_data = super(EmployeeCreateForm, self).clean() Emp_Name = cleaned_data.get('Emp_Name') Emp_company = cleaned_data.get('Emp_company') Emp_Dept = cleaned_data.get('Emp_Dept') Emp_Join_Date = cleaned_data.get('Emp_Join_Date') Emp_End_Date = cleaned_data.get('Emp_End_Date') return cleaned_data def __init__(self, *args, **kwargs): super(EmployeeCreateForm,self).__init__(*args, **kwargs) self.fields['Emp_company'].queryset = Company.objects.values('id').filter(Is_Del=0) and below is my view.py class EmployeeCraeteView(LoginRequiredMixin,SuccessMessageMixin,CreateView): model=Employee form = EmployeeCreateForm success_message = " Employee Craeted successfully!" success_url="../../company/all-companies" template_name = 'employee_form.html' fields =[ 'Emp_Name','Emp_company','Emp_Dept','Emp_Join_Date', 'Emp_End_Date' ] companies= Company.objects.filter(Is_Del=0) def form_valid(self,form): form.instance.Emp_Crt_By = self.request.user if form.cleaned_data['Emp_Join_Date'] >= form.cleaned_data['Emp_End_Date']: form.add_error('Emp_End_Date', 'Joining date should be less than Ending date') return self.form_invalid(form) return super(EmployeeCraeteView, self).form_valid(form) I want to show only this companies in the form which are filtered by Is_Del =0 -
Implementation of loading gif in django templates
I want to implement ajax loading gif from http://ajaxload.info/ in my django template but I do not know how. I do not have any experience with ajax or javasrcipt. I want to implement loading gif, while my program loadading some data from the web. My views.py looks like this: def get_file(request): get_web_file() return render(request, 'data/getwebdata.html') get_web_data.py looks like this: def get_web_file(): r = requests.get('https://nvd.nist.gov/vuln/data-feeds#JSON_FEED') for filename in re.findall("nvdcve-1.0-2018\.json\.zip|nvdcve-1.0-2018\.meta", r.text): r_file = requests.get("https://static.nvd.nist.gov/feeds/json/cve/1.0/" + str(filename).strip(), stream=True) if filename.endswith('.zip'): with open(r"data/web_files/zip/" + filename, 'wb') as f: for chunk in r_file: f.write(chunk) zip_ref = zipfile.ZipFile('data/web_files/zip/' + str(filename), 'r') zip_ref.extractall('data/web_files/unzip') zip_ref.close() I have not find any useful information on web. -
How to add a value to a field in the same model when the model is saved - django admin
I have a django model that looks like this... class Account(models.Model): account_name = models.CharField(max_length=100) deposited_amount = models.PositiveIntegerField(default=0) opening_balance = models.IntegerField(default=0) current_balance = models.CharField(max_length=9) Inside my admin.py file, I have the current_balance field set to readonly. I would like the current balance to be the sum of deposited_amount and opening_balance hence I have implemented a signal to try and handle that... @receiver(pre_save, sender=Account, dispatch_uid="update_current_balance") def update_current_balance(sender, **kwargs): created = kwargs['created'] instance = kwargs['instance'] if created: instance.current_balance = F('deposited_amount') + F('opening_balance') else: instance.save() However, I get the Exception Type: KeyError with Exception Value: 'created'. What am I doing wrong here? Also, I'm thinking that in the event that either the deposited amount or opening_balance is updated, I will need the current balance updated so should I maybe remove the if created check, or do I create another signal? -
Django 2.0 : How to fix it ? : TypeError: view must be a callable or a list/tuple in the case of include()
I used Python 3.7 Django 2.0 MySql My Question is when i write right code in urls.py file than occurred this below error TypeError: view must be a callable or a list/tuple in the case of include() NOTE : I used multiple separate views file and same for model file My CODE urls.py from django.conf.urls import url from django.contrib import admin from django.urls import path,include from django_adminlte import views urlpatterns = [ path('admin/', admin.site.urls), path('',views.login,name='login'), path('home/',views.home,name='home'), path('signup/',views.signup,name='signup'), path('employee/',views.emp,name='emp'), path('show/',views.show,name='show'), path('edit/<int:id>',views.edit), path('update/<int:id>',views.update), path('delete/<int:id>',views.delete), path('laptop/',views.laptop,name='laptop'), path('laptop_show/',views.laptop_show,name='laptop_show'), path('laptop_edit/<int:pk>',views.laptop_edit,name='laptop_edit'), path('laptop_update/<int:pk>',views.laptop_update,name='laptop_update'), path('desktop/',views.desktop,name='desktop'), path('desktop_show/',views.desktop_show,name='desktop_show'), path('mobile/',views.mobile,name='mobile'), path('mobile_show/',views.mobile_show,name='mobile_show'), path('accounts/',include('django.contrib.auth.urls')), ] -
DjangoRestFramework ChoiceField fails float value validation
I have a question regarding validation logic of serializers.ChoiceField. As I've seen in the code, here is to_internal_value() of ChoiceField that is used to validate client inputs: def to_internal_value(self, data): if data == '' and self.allow_blank: return '' try: return self.choice_strings_to_values[six.text_type(data)] except KeyError: self.fail('invalid_choice', input=data) Here is my declaration of Django model: class MyModel(BaseModel, ScopedModelMixin): my_field = models.FloatField(choices=MY_FLOAT_CHOICES, default=MY_FLOAT_CHOICES.default_value) And here is my declaration of choices object from django-model-utils==2.6.1: from model_utils import Choices MY_FLOAT_CHOICES = Choices( (1.0, 'choice1', 'Choice1'), (1.5, 'default_value', 'Choice2'), (2.0, 'choice3', 'Choice3') ) So, the generated field in a model serializer is a serializers.ChoiceField with choices provided at the previously declared model level. When it comes to validation user input from the client, DRF fails to validate float values correctly. For example, when I send: { "myField": 1 } it throws "\"1\" is not a valid choice.". So when I come with debugger to the line return self.choice_strings_to_values[six.text_type(data)] from previously shown to_internal() of ChoiceField, I see that it literally tries to find '1' in choices list. When I update my choices with: MY_FLOAT_CHOICES = Choices( (1, 'choice1', 'Choice1'), (1.5, 'default_value', 'Choice2'), (2, 'choice3', 'Choice3') ) it doesn't fail, but then I have the same problem with sending … -
Convert timestamp to datetimefield and save it in the database
Suppose i have a time stamp as following: ts=1549366296466 and i have a model which has DateTimeField as follows: class MyTime(models.Model): date_and_time = models.DateTimeField() Now suppose that there is an object 'o' of class 'MyTime' ? How can i use this time stamp and save it into object 'o'? o.date_and_time = #I need your help here. o.save() I know how to convert this into 'Date Time' format.I can do this using the below method. import datetime #First i will convert timestamp into seconds format by dividing by 1000.0 ts = ts/1000.0 #Then i will use this 'ts' in the following line of code. datetime.utcfromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S') -
inline models fields not editable django
Good evening. I work in django and created model A and model B associated with it. Model B is displayed as inline along with model A in the admin panel. My problem is that on the server I can create a model, display it in a template, delete it, but I cannot edit it - when I try, the object shows empty fields. On the local server, everything is in order. Thank. -
NoReverseMatch at /rubies/: Reverse for 'user' with arguments '(None,)' not found
when I go to the main page of my website, it throws this error NoReverseMatch at /rubies/ Reverse for 'user' with arguments '(None,)' not found. 1 pattern(s) tried: ['rubies/users/(?P[0-9]+)/$'] I have dealt with this in the past, but nothing that I used to do to solve it works in this case. The error occurs in my base.html template, in line 59: <a class="nav-link" href="{% url 'rubies:user' user.id %}">Profile</a> base.html (the part I have a problem with) <div class="collapse navbar-collapse" id="navbarResponsive"> <ul class="navbar-nav ml-auto"> <li class="nav-item"> <a class="nav-link" href="{% url 'rubies:index' %}">Home</a> </li> <li class="nav-item"> <a class="nav-link" href="{% url 'rubies:user' user.id %}">Profile</a> </li> </ul> </div> This is my views file. Of course, there are other views in it as well, but I only used the user_view one. views.py def user_view(request, user_id): if user_id is not None: user = get_object_or_404(UserTwo, pk=user_id) else: user = UserTwo() context = { 'user_id': user_id, 'username': user.username, 'password': user.password } return render(request, 'rubies/user.html', context) Thank you ! -
Filter DateTimeField By Month Without USE_TZ as False
I want to filter a datetimefield pub_date by year and month. But due to USE_TZ =True in settings, Django can't get to filter by month. If I should remove the month from the query and put only year, it will work. And if I should set USE_TZ to False, the below query will work. Now, how do I filter by month without setting USE_TZ to False? zc = TxHistory.objects.filter(pub_date__year=datetime.today().year, pub_date__month=2) I'm on Django 2.1 and Python 3.6. -
Foreign key data in admin
Is there any way I can display the total number attending a course in the list_display of CourseAdmin? admin.py class Attendee_Inline(admin.TabularInline): model = Attendee extra = 5 class CourseAdmin(admin.ModelAdmin): inlines = [Attendee_Inline] list_display = ('date','course_name','course','venue','maximum_attendees','get_count') //Trying something like this? def get_count(self,request): this = self.id q = Attendee.objects.get(pk=this).count() return q -
Issue with Django rules
I'm working with rules library from Django and I don't overcome to define rules for specific menu. I'm logged as edqm_admin in my web application. I have a menus.py file like this : # -*- coding: utf-8 -*- from __future__ import print_function, unicode_literals from django.core.urlresolvers import reverse from edqm.core.menu import Menu, MenuItem from edqm.forum.views import check_forum class AdminMenuItem(MenuItem): def check(self, request): return request.user.is_superuser or request.user.has_perm('omcl.admin_menu') settings_children = ( ... AdminMenuItem("Statistics", reverse("statistics"), weight=140) ) Then I defined in my rules.py file : # -*- coding: utf-8 -*- import rules @rules.predicate def is_edqm_admin(user): if user.is_anonymous: return False return True if user.profile.type == 'ED' and user.profile.role == 'AD' else False # Rules for menu item. rules.add_perm('omcl.view_menu_item_admin', is_edqm_admin) # Rules for statistics. rules.add_perm('omcl.statistics', is_edqm_admin) But when I try to access to the statistics part, I have an error 403 Access forbidden. I forgot something in my code ? Thank you