Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Send PDF file path to client to download after covnersion in WeasyPrint
In my Django app, I'm using WeasyPrint to convert html report to pdf. I need to send the converted file back to client so they can download it. But I don't see any code on WeasyPrint site where we can get the path of saved file or know in any way where the file was saved. If I hard code the path, like, D:/Python/Workspace/report.pdf and try to open it via javascript, it simply says that the address was not understood. What is a better way to apporach this issue? -
I am trying to upgrading pip from 8.1.1 to 8.1.2 . but it showing following 'PermissionError: [WinError 5] Access is denied:.how to upgrade pip?
C:>python -m pip install --upgrade pip Collecting pip Using cached pip-8.1.2-py2.py3-none-any.whl Installing collected packages: pip Found existing installation: pip 8.1.1 Uninstalling pip-8.1.1: Exception: Traceback (most recent call last): File "C:\Program Files\Python35\lib\shutil.py", line 538, in move os.rename(src, real_dst) PermissionError: [WinError 5] Access is denied: 'c:\program files\python35\lib\site-packages\pip-8.1.1.dist-info\description.rst' -> 'C:\Users\user\AppD ata\Local\Temp\pip-nen4ldwg-uninstall\program files\python35\lib\site-packages\pip-8.1.1.dist-info\description.rst' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Program Files\Python35\lib\site-packages\pip\basecommand.py", line 209, in main status = self.run(options, args) File "C:\Program Files\Python35\lib\site-packages\pip\commands\install.py", line 317, in run prefix=options.prefix_path, File "C:\Program Files\Python35\lib\site-packages\pip\req\req_set.py", line 726, in install requirement.uninstall(auto_confirm=True) File "C:\Program Files\Python35\lib\site-packages\pip\req\req_install.py", line 746, in uninstall paths_to_remove.remove(auto_confirm) File "C:\Program Files\Python35\lib\site-packages\pip\req\req_uninstall.py", line 115, in remove renames(path, new_path) File "C:\Program Files\Python35\lib\site-packages\pip\utils__init__.py", line 267, in renames shutil.move(old, new) File "C:\Program Files\Python35\lib\shutil.py", line 553, in move os.unlink(src) PermissionError: [WinError 5] Access is denied: 'c:\program files\python35\lib\site-packages\pip-8.1.1.dist-info\description.rst' You are using pip version 8.1.1, however version 8.1.2 is available. You should consider upgrading via the 'python -m pip install --upgrade pip' command. and C:>python -m pip -qqq install -U pip Exception: Traceback (most recent call last): File "C:\Program Files\Python35\lib\shutil.py", line 538, in move os.rename(src, real_dst) PermissionError: [WinError 5] Access is denied: 'c:\program files\python35\lib\site-packages\pip-8.1.1.dist-info\description.rst' -> 'C:\Users\user\AppD ata\Local\Temp\pip-3i5xeu8u-uninstall\program files\python35\lib\site-packages\pip-8.1.1.dist-info\description.rst' During handling of the above exception, another exception occurred: … -
How to export and import data and auth information in Django?
I'm working on a project which is already public so there are some Order objects and User objects in the database (couple of people has registrated and created some orders). Now I'm changing some things in this project including Order model (added some fields like created_time etc.) So my new database (sqlite3) has very similar schemas compared to old but it's not the same. How can I add old users and Order objects into the new db? Is there some plugin or best practise? There should be no problem with Users because their schema hasn't changed but I suppose that app_users table is not enough to copy. class Order(models.Model): customer = models.ForeignKey(User, related_name='orders', blank=True, null=True) first_name = models.CharField(max_length=40,verbose_name=u'Vorname') last_name = models.CharField(max_length=40,verbose_name=u'Nachnahme') dry_wood = models.PositiveIntegerField(blank=True, null=True, default=0,verbose_name=u'Trockenes Holz') wet_wood = models.PositiveIntegerField(blank=True, null=True, default=0,verbose_name=u'Halb trockenes Holz') briquette = models.PositiveIntegerField(blank=True, null=True, default=0,verbose_name=u'Brikettes') stelinka = models.PositiveIntegerField(blank=True, null=True, default=0,verbose_name=u'Klein Holz') street = models.CharField(max_length=200, verbose_name=u'Straße', null=True, blank=True) number = models.CharField(max_length=40, null=True, blank=True, verbose_name=u'Hausnummer') city = models.CharField(max_length=100, verbose_name=u'Stadt', null=True, blank=True) psc = models.CharField(max_length=40, null=True, blank=True, verbose_name=u'PLZ') telephone = models.CharField(max_length=50, null=True, blank=True, verbose_name=u"Telefon Nummer") telephone2 = models.CharField(max_length=50, null=True, blank=True, verbose_name=u'Telefon 2') email = models.EmailField(null=True, blank=True,verbose_name=u'Mail') time = models.TextField(null=True, blank=True, verbose_name=u'Kommentar') price = models.DecimalField(max_digits=20, decimal_places=2, blank=True, null=True) text_order = … -
Email confirm error rest-auth
I use a standard form for the confirmation email: from allauth.account.views import confirm_email as allauthemailconfirmation urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^rest-auth/', include('rest_auth.urls')), url(r'^accounts/', include('allauth.urls')), url(r'^rest-auth/registration/account-confirm-email/(?P<key>\w+)/$', allauthemailconfirmation, name="account_confirm_email"), url(r'^rest-auth/registration/', include('rest_auth.registration.urls')), ] Settings: LOGIN_REDIRECT_URL='/' ACCOUNT_EMAIL_VERIFICATION='mandatory' ACCOUNT_CONFIRM_EMAIL_ON_GET=False ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_USERNAME_REQUIRED = True ACCOUNT_LOGIN_ON_EMAIL_CONFIRMATION = False I correctly get an e-mail, but when you try to link: ImproperlyConfigured at /rest-auth/registration/account-confirm-email/MTU:1bn1OD:dQ_mCYi6Zpr8h2aKS9J9BvNdDjA/ TemplateResponseMixin requires either a definition of 'template_name' or an implementation of 'get_template_names()' -
Save iteration values from list to single object
I'm trying to store in one object many values from list using for loop. All are of FloatField type. My function gives me many objects with one result. I need just one object with all values in one row. views.py form = f_Form() newF = form.save(commit=False) for i in namesOfModelFields: if any(str(i) in s for s in resultsOfNames): j = resultsOfValue[resultsOfNames.index(i)] form = f_Form({str(i) : float(j)}) newF = form.save(commit=False) newF.save() if form.is_valid(): form.save_m2m() -
Fetching model instance from a multiple direct relationship
Can anyone help me fetch data from this model structure? because i have a hard time doin this for hours now. First I would like to get all distinct SubSpecialization from all Doctor which has a given Specialization.title Secondly I would like to get all Doctor which has no SubSpecialization in a given Specialization.title Here is the Doctor model class Doctor(models.Model): name = models.CharField(max_length=50) room_no = models.IntegerField() floor_no = models.IntegerField() contact_no = models.CharField(max_length=50, blank=True, null=True) notes = models.CharField(max_length=70, blank=True, null=True) This is the model Doctor relationship is connected to Specializationand SubSpecialization. class DoctorSpecialization(models.Model): doc = models.ForeignKey(Doctor, models.DO_NOTHING) spec = models.ForeignKey('Specialization', models.DO_NOTHING) class DoctorSubSpecialization(models.Model): doc = models.ForeignKey(Doctor, models.DO_NOTHING) sub_spec = models.ForeignKey('SubSpecialization', models.DO_NOTHING) This is where i would make a criteria. class Specialization(models.Model): title = models.CharField(unique=True, max_length=45) point = models.IntegerField() class SubSpecialization(models.Model): title = models.CharField(max_length=100) There is no direct relationship between the Specialization and SubSpecialization please help. -
Django project to domain, vps
I have VPS-server (CentOS 6.8) I installed Python 3.5.2 and Django 1.10.1 on virtual enviroment I connected my domain to VPS-server Now: django-project: (venv) /home/django_user/djtest/venv/django_project/django_project domain: /var/www/www-root/data/www/mydomain.com I tried set BASE_DIR in settings.py to '/var/www/www-root/data/www/mydomain.com' but not working How I can to connect django-project to domain? Project is still empty, just created -
Finding out the file name in a FileUploadHandler
I am rolling my own fileupload handler in django and would like to know the file name. I am supporting more than one file format and want to do different processing in the receive_data_chunk method depending on which file format the uploaded file has. I thought I would be pragmatic and just judge file format based on file ending but I can't figure out how to get hold of the file name. If I try to extract the file name with something like the following code: if request.method == 'POST': p = re.compile('^.*\.sdf$', re.IGNORECASE) if ( p.search(request.FILES['filecontent'].name) ) : self.sdf = True else: self.sdf = False It seems I never reach the receive_data_chunk method. I presume the call to request.FILES trigger the loading somehow and then it's already done? How can I do different processing based on file ending in my receive_data_chunk method? -
Auto-fill Django OneToOneField
This maybe a simple question, but i do not have any idee how to do this. I have two models in Django. class ModelA(models.Model): some_member = models.Charfield(...) class ModelB(models.Model): model = OneToOneField(ModelA) other_member = models.Charfield(...) ModelA is filled in by a ModelForm and then redirect to the form for ModelB. How can I Autofill the OneToOneField based on the previous form. Thank you for helping -
how to add href value in django view
I am working on a project using django, in this i have a module which shows the listing of users in a table format, the data of users returns from django view to django template using ajax, so the action values with buttons also have to be returned from view to template in json response, as we usually do in bootstrap ajax datatables. Now the problem is that i have to set href value in django view. Code in view is :- for user in users: actionValues='<a title="Edit" class="btn btn-sm green margin-top-10" href="'"><i class="fa fa-edit"></i></a> <a title="View" class="btn btn-sm blue margin-top-10" href="'"><i class="fa fa-view"></i></a>'; inner_data_list = [ i, user['first_name'], user['last_name'], user['email'], user_type, '<div id=%s class="bootstrap-switch bootstrap-switch-%s bootstrap-switch-wrapper bootstrap-switch-animate toogle_switch"><div class="bootstrap-switch-container" ><span class="bootstrap-switch-handle-on bootstrap-switch-primary">&nbsp;Active&nbsp;&nbsp;</span><label class="bootstrap-switch-label">&nbsp;</label><span class="bootstrap-switch-handle-off bootstrap-switch-default">&nbsp;Inactive&nbsp;</span></div></div>'%(user['id'],checked), user['date_joined'], actionValues ] datalist.append(inner_data_list) As you can see in code there is a variable actionValues it contains two buttons, related to each listing , Now what i have to do is i have to link these two buttons to function edit_details and view_details respectively. So how can i link these two buttons to their respective function in view. -
how to test uwsgi app
I a question about monitoring uwsgi on multiple nodes So i have 2 instances: "a" instance => nginx (as a balancer ) + uwsgi app (django) "b" instances => uwsgi app (django) I had few times situation when uwsgi raced to 100% CPU and respond 499 http code to each http request. Everything I needed to make app works - just to restart uwsgi (supevizorcrl restart uwsgi). So now I want to setup some monitoring. I consider using monit. It can monitor how much cpu process uses. But I don't know how to check the 2-nd case - http code, especially I don't have nginx on the 2-nd instance. Is it possible to make request to uwsgi directly ? or how to check uwsgi is working properly ? Can someone advice how to setup monitoring in such case ? -
Mongo:the data consistency
I have some problem in my project. I deploy mongodb service in 4 servers.TO be understandable,I make a simple code demo ,just as follows(run with django): from mongoengine improt * class Date(Document): name=StringField() queryset=Date.object.filter(name="xxx") num=queryset.count() // num=1777 for item in quertset: item.delete() after several time , I run "num=Date.object.filter(name="xxx").count()" the num is also 1777 but when I try to print every item in the queryset,it return NONE is this data consistency problem in mongo? -
Can't save and instantiate a child class in my django model
in my django app in models.py I have the following code: class User(models.Model): password = models.CharField(max_length = 16) class Company(User): name = models.CharField(max_length = 20) class Employee(User): name = models.CharField(max_length = 20) last_name = models.CharField(max_length = 20) email = models.EmailField() When I try to create and save an Employee object through the interactive shell (the one given by the command: python manage.py shell) I get the following error Traceback (most recent call last): File "C:\Users\rdessi\Desktop\code\venv\lib\site-packages\django\db\backends\utils.py", line 64, in execute return self.cursor.execute(sql, params) File "C:\Users\rdessi\Desktop\code\venv\lib\site-packages\django \db\backends\sqlite3\base.py", line 337, in execute return Database.Cursor.execute(self, query, params) sqlite3.OperationalError: table home_user has no column named password The above exception was the direct cause of the following exception: Traceback (most recent call last): File "<console>", line 1, in <module> File "C:\Users\rdessi\Desktop\code\venv\lib\site-packages\django\db\models\base.py", line 796, in save force_update=force_update, update_fields=update_fields) File "C:\Users\rdessi\Desktop\code\venv\lib\site-packages\django\db\models\base.py", line 824, in save_base updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields) File "C:\Users\rdessi\Desktop\code\venv\lib\site-packages\django\db\models\base.py", line 908, in _save_table result = self._do_insert(cls._base_manager, using, fields, update_pk, raw) File "C:\Users\rdessi\Desktop\code\venv\lib\site-packages\django\db\models\base.py", line 947, in _do_insert using=using, raw=raw) File "C:\Users\rdessi\Desktop\code\venv\lib\site-packages\django\db\models\manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:\Users\rdessi\Desktop\code\venv\lib\site-packages\django\db\models\query.py", line 1045, in _insert return query.get_compiler(using=using).execute_sql(return_id) File "C:\Users\rdessi\Desktop\code\venv\lib\site-packages\django\db\models\sql\compiler.py", line 1054, in execute_sql cursor.execute(sql, params) File "C:\Users\rdessi\Desktop\code\venv\lib\site-packages\django\db\backends\utils.py", line 79, in execute return super(CursorDebugWrapper, … -
'SESSION_EXPIRE_AT_BROWSER_CLOSE = False' doesn't work only in Django testing
I use Django 1.9.7. And I set SESSION_EXPIRE_AT_BROWSER_CLOSE = False in my settings.py. When I manually test whether session expire or not after closing browser, it works(session doesn't expire) Open browser(Firefox) Access to my site In django-extension shell, print Session.objects.all() It shows [<Session: pvv97660g45505db1vvywp18ctxy3kmb>] Close browser completely (cmd + q in Mac OS) Open browser(Firefox) Access to my site print Session.objects.all() again It shows [<Session: pvv97660g45505db1vvywp18ctxy3kmb>] But when I test this procedure with selenium it doesn't work. Here is the code: class CartSessionWithouLoginTest(ProductSetupTestCase, LiveServerTestCase): def setUp(self): self.browser = webdriver.Firefox() self.browser.implicitly_wait(2) def tearDown(self): self.browser.quit() def test_session(eslf): self.browser.get(self.live_server_url) print(Session.objects.all()) # [<Session: pvv97660g45505db1vvywp18ctxy3kmb>] self.browser.quit() time.sleep(2) self.browser = webdriver.Firefox() self.browser.implicitly_wait(2) self.browser.get(self.live_server_url) print(Session.objects.all()) # [<Session: pvv97660g45505db1vvywp18ctxy3kmb>, <Session: jw7dpg0mrtcarrlqkfoaofd6f6p7ppw0>] Why does it happen in selenium test? -
Postgres converting uploaded user email to lowercase partially
I am uploading user details(username,email,password) from a .csv file to postgres DB using pandas in python. It is all fine till the dataframe gets generated but once I run the code for uploading the user details the substring-"@gmail.com" from their emai-id gets converted to/stored as lowercase in postgres DB. This is the code that I have written in python shell of a django application - >>>import sys >>>from django.contrib.auth import authenticate >>>from django.contrib.auth import get_user_model >>>import pandas as pd >>>User = get_user_model() >>>df=pd.read_excel('set_A_results_748_web.xlsx',sheetname='Sheet1',parse_cols=(0,3,4)) df.head() Dataframe First 10 rows Output Screenshot >>>users = [tuple(x) for x in df.values] >>>for name, email, password in users: try: print ('Creating user {0}.'.format(name)) user = User.objects.create_user(name=name, email=email) user.set_password(password) user.save() assert authenticate(name=name, password=password) print ('User {0} successfully created.'.format(name)) except: print ('There was a problem creating the user: {0}. Error: {1}.' \ .format(name, sys.exc_info()[1])) Postgres User Table Data Screenshot After Uploading As shown in the output (first 10 rows of dataframe df) the email ids of every user is acc to the data in excel file but when I upload them to auth_user table in my postgres DB the latter part of email gets converted to lowercase. for Example: E-mail id of row 6 Dipak Shah would … -
Accessing users groups through attributes / foreign keys in Django
I'm trying to access my users groups in Django, but keep getting auth.Group.None as the result. When in the django shell I'll first create a group, then a user and add the user to the group. After this, I try to print the users groups, like so: from django.contrib.auth.models import User, Group Artists = Group.objects.create(name="Artists") Artists.save() Rihanna = User.objects.create_user(username="Rihanna", password="newpassword") Rihanna.save() Artists.user_set.add(Rihanna) # Save both of them again just to double check Rihanna.save() Artists.save() # Now try to access Rihanna's groups through her attributes: print Rihanna.groups, Rihanna.groups.name and the results are >>> auth.Group.None None What I'd like to happen is for it to print the groups name. I know I can query the members of a group by the filter and get commands, but I'd like to access the groups straight through a users attributes/foreign keys. Any idea what I'm doing wrong? -
Accordion on admin change list
I have a model like this class ModelName(models.Model): title = models.CharField(max_length=300, blank=False) description = models.TextField(max_length=500, default="DEFAULT VALUE") And I have registered this model in admin change_list page. when I click title I am redirected to change page. Is there any way for showing that page in drop (down-up) accordion-styled box on the bottom of each row when I click the title link? (How can I handle it?) If any ajax or jquery stuff are needed, where I should add them? -
Django server is hanging in request handler
I do a poll once a second, and after some idle time (10min - 1h) the server stops responding. If I press Ctrl-C handler is terminated and the server is back alive. Error after pressing Ctrl-C (while trying to connect with a new client): ...same messages repeat... [22/Sep/2016 21:54:27] "GET /ajax/?id=STATUS_POLL&_=1474566714286 HTTP/1.1" 200 0 [2016-09-22 21:54:28,217: DEBUG/MainProcess] NONE [22/Sep/2016 21:54:28] "GET /ajax/?id=STATUS_POLL&_=1474566714287 HTTP/1.1" 200 0 [2016-09-23 09:33:14,657: INFO/MainProcess] Starting view [23/Sep/2016 09:36:34] "GET / HTTP/1.1" 200 18970 Traceback (most recent call last): File "c:\python27\lib\wsgiref\handlers.py", line 86, in run self.finish_response() File "c:\python27\lib\wsgiref\handlers.py", line 128, in finish_response self.write(data) File "c:\python27\lib\wsgiref\handlers.py", line 212, in write self.send_headers() File "c:\python27\lib\wsgiref\handlers.py", line 270, in send_headers self.send_preamble() File "c:\python27\lib\wsgiref\handlers.py", line 194, in send_preamble 'Date: %s\r\n' % format_date_time(time.time()) File "c:\python27\lib\socket.py", line 328, in write self.flush() File "c:\python27\lib\socket.py", line 307, in flush self._sock.sendall(view[write_offset:write_offset+buffer_size]) error: [Errno 10053] An established connection was aborted by the software in your host machine [23/Sep/2016 09:36:34] "GET / HTTP/1.1" 500 59 Request handler: class CTrackerView(TemplateView): __process = ProcessWrapper() @staticmethod def ajax_handler(request): if request.GET.get('id', "") == "STATUS_POLL": if CTrackerView.__process.is_alive(no_log=False): return HttpResponse("UPDATING") else: return HttpResponse("") process_wrapper.py: class ProcessWrapper: def is_alive(self, no_log=False): if (not hasattr(self, "_process")) or not self._process: if not no_log: log("NONE", DEBUG) return False As you … -
string parameter passing not working in django1.9
I am passing a string parameter in view but its not working. url(r'^users/(?P<user_type>\w+)/$', views.users, name='users'), url(r'^users/$', views.users, name='users') view is:- def users(request, user_type=None): Link is:- <a href="{% url 'users' %}">All Users</a> <a href="{% url 'users' customers %}">Customers</a> <a href="{% url 'users' promoters %}">Promoters</a> But its giving error when i access view without parameter Reverse for 'users' with arguments '('',)' and keyword arguments '{}' not found. 2 pattern(s) tried: ['administrator/users/$', 'administrator/users/(?P<user_type>\\w+)/$'] Exception Value: Reverse for 'users' with arguments '('',)' and keyword arguments '{}' not found. 2 pattern(s) tried: ['administrator/users/$', 'administrator/users/(?P<user_type>\\w+)/$'] -
I am getting this error django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be empty on import of class
I am working on Cartridge (django) project. I want to add one new field 'tag' in my shop.models.Product class. I added that field and now I want to add that tag manually from cartridge admin panel. So, to do that I am importing one admin class in my settings.py, from cartridge.shop.admin import ProductAdmin When I am importing above class, I am getting error on terminal, django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be empty. I wants to add that "tag" field in ProductAdmin class like below,but before I write below code in my project I am getting that "SECRET_KEY" error on import, ProductAdmin.list_display = ProductAdmin.list_display.append("tag") -
django localtime template filter doesn't work
I am use django 1.10 to display datetime. The datetime is stored in mongodb and it is always UTC without timezone info, so I need to display the date time according to machine's time zone which run django. First, add those in settings.py TIME_ZONE = 'Asia/Chongqing' USE_I18N = True USE_L10N = True USE_TZ = True Then in views.py adds: import pytz from tzlocal import get_localzone from django.utils import timezone local_tz = get_localzone() timezone.activate(local_tz) # make datetime object and pass it to html to render in template.html: {% load tz %} <table border="1"> {% for i in online %} <tr> <td align='center'>{{ i.time|localtime}}</td> </tr> {% endfor %} </table> But the datetime still UTC, even I add tzinfo to the datetime which pass into html. Did I miss something? -
return mongodb search results in a list to angular js Django
here is my code to fetch results from mongodb after recieving a keyword for search sent by a POST Method via Angular JS: retrieved_data = save_data.retrieve_handler(attr={'NAME':{'$regex':keyword},'date_published':{'$gte':startDate,'$lt':lastDate}}) return HttpResponse(json.dumps(retrieved_data), content_type="application/json") retrieved data is a list of dictionaries fetched from MongoDb. But when I tried to send it through response to the angular js, it failed and got nothing angular js code is here : $scope.search_info=function(){ var search_req = { url:'/portfolio/home', method:'POST', data:$scope.search } $http(search_req).success(function (response) { window.alert(response); }) $http(search_req).error(function(){ window.alert('No') }) } Also I want to convert the json/dictionaries data to an html table when it recieved, please help me to resolve this issue. -
How to deploy react.js webpack with django to heroku?
I have a django backend and react.js frontend along with webpack. I've set everything up locally as per this page: http://owaislone.org/blog/webpack-plus-reactjs-and-django/ and have my dev server running and all is peachy. For my production webpack file I've copied the same exact one as on the site. However I would like to deploy to heroku and this is where I get stuck. Do I need to replace my webpack-dev-server with some kind of express server on production? Can I just run django and serve up static javascript files instead? To generate these files I've tried running: "webpack webpack-config.prod.js --progress -p" however I get a bunch of "Cannot resolve module 'fs'" errors but I do notice it generated a 900kb js file in assets/bundles. Also if I try running "webpack webpack-config.prod.js --progress -p" on my local machine (without the dev server) and go to a django route I get this in my console: GET http://localhost:3000/assets/bundles/main-62ddfced1c44b3270fa7.js net::ERR_CONNECTION_REFUSED I have spent quite a few hours getting this to work, setting up the dev environment was a lot faster. What am I doing wrong here? -
How to create key value data type in django 1.7 models
I want to store key-value pair in one column. Above >Django-1.7 provides hstore to do that. But I want to same functionality in Django-1.7. How can I create custom datatype to store key-value pair in one column. I am using postgres-9.5 database. I want to store below json in key value pair in one column. Example: { "prepared_date":"2016-08-08T02:04:34Z", "date_0":"2016-08-08T02:04:34Z", "status_0":true, "date_1":"2016-08-08T02:04:34Z", "status_1":true, "date_2":"2016-08-08T02:04:34Z", "status_2":true, } -
Django How PermissionRequireMixin class works in code level?(I am even looking into mixins.py in auth folder)
I would like to know how PermissionRequireMixin works in Django. (I couldn't find any question explaining how PermissionRequireMixin works in very detail. I am looking into code 'mixins.py' in path of 'django.contrib.auth'.) For example, if write codes like below, it will check if login-user has permission named 'test_permission'. if the login-user has this permission, it moves to a template which is written in template_name attribute. if not, it moves to login page(or another page depend on what you set up). so PermissionRequiredMixin check permission to move on in a class type view. from django.contrib.auth.mixins import PermissionRequiredMixin from django.views.generic import ListView class ViewTest(PermissionRequiredMixin, ListView): permission_required = ('pertest.test_permission',) model = Test template_name = 'pertest/pertest_check_list.html' what I want to know is... I looked into 'django.contrib.auth.mixin.py code to understand how PermissionRequiredMixin class works. I can see it is subclass of AccessMixin and understand what kind of methods it has. but I can't understand how it proceed to check login's permission. I would like to understand flow in code base. where should i check to understand process for checking permission fully? I even want to know this. Let's say a login-user 'A' has permission named 'test_permission' and the 'A' user is in a group which …