Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Using a Django FileField in an inline formset
having issues getting the file to upload in my app. A User submits a report and can add attachments (through a foreign key relationship). I've got the inline form showing up and will work if I leave it blank, but when I try to upload a file then submit the form I get a 500 error. The base report is made, but the attachment that's getting inlined doesn't get saved. forms.py class ReportForm(forms.ModelForm): accidentDate = forms.DateField(widget=SelectDateWidget( empty_label=("Choose Year", "Choose Month", "Choose Day"), ), label=(u'Accident Date'), initial=timezone.now()) claimNumber = forms.CharField(max_length=50, label=(u'Claim Number'), required=True) damageEstimate = forms.DecimalField(max_digits=6, decimal_places=2, label=(u'Damage Estimate')) description = forms.CharField(widget=forms.Textarea(attrs={'rows': 5, 'cols': 80} ), label=(u'Description'), required=True) drivable = forms.BooleanField(label=(u'Drivable'), required=False) receivedCheck = forms.CharField(max_length=30, label=(u'Who Received Check')) reported = forms.BooleanField(label=(u'Reported to Insurance Company'), required=False) reportedDate = forms.DateField(widget=SelectDateWidget( empty_label=("Choose Year", "Choose Month", "Choose Day"), ), initial=timezone.now(), label=(u'Date Reported to Insurance')) repairsScheduled = forms.DateField(widget=SelectDateWidget( empty_label=("Choose Year", "Choose Month", "Choose Day"), ), initial=timezone.now(), label=(u'Scheduled Repair Date')) repairsCompleted = forms.DateField(widget=SelectDateWidget( empty_label=("Choose Year", "Choose Month", "Choose Day"), ), initial=timezone.now(), label=(u'Repair Completion Date')) repairsPaid = forms.BooleanField(label=(u'Repairs Paid'), required=False) subrogationReceived = forms.BooleanField(label=(u'Subrogation Received'), required=False) subrogationDate = forms.DateField(widget=SelectDateWidget( empty_label=("Choose Year", "Choose Month", "Choose Day"), ), initial=timezone.now(), label=('Subrogation Date')) class Meta: model = Report exclude = ('driver',) ReportAttachmentFormSet = … -
Django multiple "daisy-chained" models
I have five "connected" models: Book, Chapter, Page, Paragraph, Line. They are all connected by a chain of foreign keys in the sense that Line has a foreign key linking it to Paragraph Paragraph has a foreign key linking it to Page Page has a foreign key linking it to Chapter Chapter has a foreign key linking it to Book Basically, 5 tables, 4 one-to-many relationships. I would like to display a tree of nested lists. I know how to do it for just Book and Chapter (using regroup) but when I need to "dig deeper" I'm stuck. -
Form not Rendered in Django
I am trying to display a form in Django HTML Template, but it is not being Rendered views.py from django.shortcuts import render from django.http import HttpResponse from .models import Description, Bill from django.http import Http404 from .forms import DForm from .forms import BForm import pprint # Create your views here. def index(request): context = {} return render(request, 'front/index.html', context) def commitbill(request): if request.method == "POST": form = BForm(request.POST,request.FILES) if form.is_valid(): print form.errors Bill = form.save() return HttpResponse(str(Bill.bill_id())) print form.errors return HttpResponse("fail") forms.py from django import forms from .models import Description, Bill class BForm(forms.ModelForm): class Meta: db_table = 'inventory_bill' model = Bill fields = ('party', 'inovice', 'amount','image','image_caption') the template, portion of which is not being Rendered! {% load staticfiles %} <html> <head> <title></title> <link href="{%static "./styles/bootstrap.min.css" %}" rel="stylesheet" /> </head> <body> <h1 style="text-align: center;">Rahul's Shop</h1> <h2 style="text-align: center;">Inventory</h2> <form id="bill" action ="{% url 'front:commitbill' %}" method = "post" class="form-horizontal" enctype="multipart/form-data"> {% csrf token %} {{ form.as_p }} <div class="container"> <div class="row"> <input type="button" id="add_items" class="col-md-offset-5 col-md-2 btn btn-success" value="Add items" \> </div> </div> </form> The portion {{ form.as_p }} is not being Rendered, That's my main Issue! -
In setting up a Django host, migrate.py often fails to create a .sock file
I am learning to use Django on Nginx. To set up a new host at sitename.com I do: ~$ mkvirtualenv sitename ~$ pip install Django ~$ django-admin.py startproject sitename ~$ cd sitename ~$ ./manage.py migrate ~$ ls -rw-r--r-- 1 andrew 36864 Jan 11 09:11 db.sqlite3 -rwxrwxr-x 1 andrew 803 Jan 11 09:10 manage.py drwxrwxr-x 2 andrew 4096 Jan 11 09:11 sitename/ srw-rw-rw- 1 root 0 Jan 11 09:11 sitename.sock The problem is that the .sock file is only created about 1/5 of the time. I have tried the exact same steps with different domain names, after restarting the server etc., and most of the time the .sock file is missing. It's such a simple process that I can't figure out why the result seems so random. Ubunto 16.04 LTS, Nginx 1.10.0, Python 2.7.12, Django 1.10.5 -
Why does MySQL treat Japanese alphabets hiragana and katakana the same, and how can you make it compatible with Django?
This question was partially addressed here, but I wanted to ask more specifically: MySQL difficulties - Hiragana and Katakana are treated as the same Japanese has 2 separate phonetic alphabets describing the same set of sounds, and MySQL appears to treat these two alphabets the same way they treat upper and lower case (so I suppose, rather than case insensitive, it's alphabet insensitive). However, these two alphabets are not analogous to English case, so it doesn't make much sense to do that. Does anybody know why they chose to do it this way, and an easy work around? More specifically, when connected to django, you get this problem: >>> ichi = 'イチ' # This word is in katakana >>> Dictionary.objects.get(word=ichi).word # The record that is returned is in hiragana 'いち' >>> Dictionary.objects.get(word=ichi).word == ichi # The words are not the same False Does anyone know how I can make the behavior consistent? -
Get Token after Registration with Djoser, django-rest-framework-jwt and django-rest-framework
I'm trying to get the Token after the user registration, but I can't. I read this post and this doc, but I'm not getting it. I also tried to do something like this UserRegistrationSerializer, but it still without working. And I found this issue, but I think I'm not understanding what I've to do. Here is my models.py: from django.db import models class User(models.Model): created = models.DateTimeField(auto_now_add=True) email = models.CharField(max_length=100, blank=False) name = models.CharField(max_length=100, blank=False) last_name = models.CharField(max_length=100, blank=False) birthday = models.CharField(max_length=15, blank=False) password = models.CharField(max_length=100, blank=False) class Meta: ordering = ('created',) my serializers.py from rest_framework import serializers from users.models import User class UserSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = User fields = ('url', 'id', 'email', 'name', 'last_name', 'birthday', 'password') my app urls: from django.conf.urls import url, include from rest_framework.routers import DefaultRouter from .views import UserViewSet router = DefaultRouter() router.register(r'users', UserViewSet) urlpatterns = [ url(r'^', include(router.urls)), ] and my views.py from rest_framework import viewsets from rest_framework_jwt.settings import api_settings from users.models import User from users.serializers import UserSerializer class UserViewSet(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer def create(self, request, *args, **kwargs): # if settings.get('SEND_ACTIVATION_EMAIL'): # with transaction.atomic(): # user = User.objects.create_user(**validated_data) # user.is_active = False # user.save(update_fields=['is_active']) # else: user = User.objects.create_user() token = … -
What is the new version of csrf in Django 1.10
I'm following a tutorial and getting a TypeError with this line: c.update(csrf(request)) This is the full view from django.shortcuts import render from django.views.decorators import csrf def index(request): c = {} #dictionary called c c.update(csrf(request)) return render(request, 'login/index.html', c) Am I doing an old version of something that has changed? Did I import csrf incorrectly? I'm running the newest version of Django. -
Django get all related object from model with 'through' tables
In our app we have several relationships and several models, I'm trying to achieve a generic way to get all related objects of an object, even reverse ones. If I print get_fields() from my model Pessoa, i get these relationship fields(I omitted the other ones): <ManyToManyRel: cadastroimoveis.ccir> <ManyToOneRel: cadastroimoveis.ccir_pessoa> <ManyToManyRel: cadastroimoveis.pessoa> <ManyToOneRel: cadastroimoveis.pessoa_pessoa> <ManyToOneRel: cadastroimoveis.pessoa_pessoa> <ManyToOneRel: cadastroimoveis.pessoa_imovel> <ManyToOneRel: cadastroimoveis.pessoa_itr> <ManyToManyRel: cadastroimoveis.doc> <ManyToOneRel: cadastroimoveis.doc_pessoa> This specific model only has M2M relationships, and all of them contain a 'through' model as specified Here. As you can see, it repeats them, one for the M2M fields, and one for the ManyToOne with the through table. And in the case of the recursive relationship it repeats twice. My question is, is there a way to get these non repeated? I'm not sure if the repeated ones point to the same object. And according to the Model _meta API documentation, you would use this to get all related objects : [ f for f in MyModel._meta.get_fields() if (f.one_to_many or f.one_to_one) and f.auto_created and not f.concrete ] But the 'through' tables are not considered auto_created so it would just get the same result as the one above it. -
django-oauth-toolkit setup without Django Rest Framework
I have a web project made with Django 1.9 which will have its RESTful API as an application. I don't want to use Django Rest Framework since, from my understanding, it works as a wrapper of Django itself, which I already have. I'm using django-oauth-toolkit for OAuth2 authentication, but the problem is that Django requires the csrf token in POST requests and I wan't to disable the SessionAuthenticationMiddleware in all the application. I tried to redirect to an extended method for the TokenView class, but Django still asks for the csrf token in the request. Here is what I have so far: Project Structure: myproject: |_app1 |_app2 |_api |_views.py |_urls.py api/urls.py: from django.conf.urls import include, url from django.conf import settings from . import views urlpatterns = [ url(r'^o/token/$', views.TokenView.as_view(), name="token"), url( r'^o/', include( 'oauth2_provider.urls', namespace='oauth2_provider' ) ), # OAuth2 Provider ] api/views.py: class TokenView(InitialTokenView): def __init__(self, **kwargs): super(TokenView, self).__init__(**kwargs) @method_decorator(csrf_exempt) def dispatch(self, *args, **kwargs): return super(TokenView, self).dispatch(*args, **kwargs) The TokenView class comes from the original code of django-oauth-toolkit https://github.com/evonove/django-oauth-toolkit/blob/master/oauth2_provider/views/base.py What is what I'm missing? Thanks in advance. -
avoid duplicate model instance in django without any django unique constraint error
I write a news aggregator service and I run a periodic task for every 5 minutes to fetch top stories based on votes and save data to the database. everything working fine but I run into a problem. in every 5mint there may or may not a new entry and my service save the duplicate entry to DB. if I use unique=True then my celery worker show error regarding django unique constraint violation and crashes. is there any way to avoid duplicate data without error. i know maybe its not a best practise but i have this use case. please suggest how to do this in django. -
Fetch gets failed
I have a login page in react project. I have been trying to work out with fetch api to call my django rest-api but nothing is working. THis is my code of component. import fetch from 'isomorphic-fetch' export default class LogInComponent extends Component { handleLoginButtonClick() { var payload = { passwor:1, username: 2 }; var data = new FormData(); data.append( "json", JSON.stringify( payload ) ); console.log(data); console.log("test"); fetch('https://myname-backend.appspot.com/auth/login/', { method: "POST", headers: { 'Content-Type': 'application/json' }, body: data } ) .then(function(res){ return res.json(); }) .then(function(data){ alert( JSON.stringify( data ) ) }) .catch(function(error) { console.log('There has been a problem with your fetch operation: ' + error.message); }); } render(){ return ( <div className="LoginPage"> <div className="login-page"> <div className="form"> <form className="login-form"> <input id="username" type="username" placeholder="username"/> <input id="password" type="password" placeholder="password"/> <button onClick={this.handleLoginButtonClick}>login</button> <p className="message">Not registered? <a href="#">Request Username and Password</a></p> </form> </div> </div> </div> ); } } I don't know what am I doing wrong? When I include headers in fetch api doesn't get the payload (api just gets options then) and when I don't include headers then it throws 415 error. I am attaching screenshots of my api endpoints also error error -
Using django json fixture with model having Meta db_table set manually
I have a django project with json fixtures generated with a model attribute like: "model": "app_name.dog" but I've set the model like this: class Meta: managed = True db_table = 'dog' and edited the json so that the model is like this: "model": "dog" and I get this when I try to loaddata: django.core.serializers.base.DeserializationError: Problem installing fixture 'dog.json': not enough values to unpack (expected 2, got 1) Since I removed the app name from the model to accomodate the db_table having no app_name prefix. Is there a way to get django to ignore the need for an app name in the fixture? -
Django display filefield in Template
I want to display and audio stored in filefield but the links comes up dead #template {% for audios in Audios %} <audio controls> <source src="{{ audios.Audio_File.url }}" type="audio/mpeg"> </audio> {% endfor %} #settings.py MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' #urls.py if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) -
Is it pythonic to create a class with all the global variables?
I am using strings like 'email' and 'password' in my application very often. So thought I will create a class and instance variables and use them by creating instance of class in every method. I have many strings which are used very often in my application. Is this a correct approach or should I only use strings directly when required. -
How to override Site.get_current()/request.get_host() in tests
In my app I have line if request.get_host() == Site.objects.get_current().domain. The problem is in my tests this condition is never True. request.get_host() returns testserver and Site.objects.get_current returns example.com. I know that I can add SERVER_NAME to request but I want change globally not in every single request. -
Docker - Running bash scripts on a Windows host
I setup a django project with Docker, its got two containers, one for the django server, one for the postgres server. I want to be able to also do different things like run bash scripts and perl scripts for this project, for example I need to use a bash script to download and restore database dumps from the live site automatically. Do I setup a new Docker image for each bash script? Or would I need to setup a Ubuntu container and run the bash scripts through that? Heres the Dockerfile: FROM python:3.5 ENV PYTHONBUFFERED 1 ENV APPLICATION_ROOT /app/ ENV APP_ENVIRONMENT L COMPOSE_CONVERT_WINDOWS_PATHS=1 RUN mkdir -p $APPLICATION_ROOT WORKDIR $APPLICATION_ROOT ADD requirements.txt $APPLICATION_ROOT RUN pip install --upgrade pip RUN pip install -r requirements.txt ADD . $APPLICATION_ROOT And the docker-compose file: web: build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/app ports: - "8998:8998" links: - db db: image: postgres:9.4 environment: APP_ENVIRONMENT: L POSTGRES_USER: postgres POSTGRES_PASSWORD: root POSTGRES_DB: mydb I'm new to Docker so don't yet know the best approach to doing things. Where would I put the bash script and new docker file, and how would I link it to this project so that I can execute the scripts whenever … -
why does simple startup script error out when ran via docker-compose?
I have a pretty simple .sh script that does some django startup tasks. startup.sh #!/bin/bash python manage.py makemigrations accounts python manage.py migrate python manage.py check_permissions python manage.py cities --import=country --force echo "removing extra countries" python manage.py removecountries echo "importing cities" python manage.py cities --import=city python manage.py cities --import=postal_code echo "starting dev server" python manage.py runserver 0.0.0.0:8000 When I build and run docker-compose, and then open a shell into the resulting container, I can manually run this startup.sh script and it completes each task without issue. However, when I let Docker-Compose run this script via Command, it seems to run into issues. When I check Docker logs, I can see that the script is in fact being ran, but only the first few lines about migration and check_permissions are successful. The rest seem to error out. Changed permissions for user: AnonymousUser Importing countries: 100%|##########| 250/250 [00:01<00:00, 195.79it/s] Importing country neighbours: 46%|####6 | 115/250 [00:00<00:00, 223.78it/s] Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/usr/lib/python2.7/dist-packages/psycopg2/__init__.py", line 164, in connect conn = _connect(dsn, connection_factory=connection_factory, async=async) django.db.utils.OperationalError: could not connect to server: Connection refused Is the server running on host "postgres" (172.17.0.2) and accepting TCP/IP connections on port 5432? … -
Sanitise string slug in URL to avoid
I have a Django / django-rest-framework website with the following in a model: nickname = models.CharField(max_length=255, unique=True) Then in urls.py: url(r'^subjects/$', subjects_views.SubjectList.as_view(), name="subject-list"), url(r'^subjects/(?P<nickname>[^/].+)/$', subjects_views.SubjectDetail.as_view(), name="subject-detail"), This all works great, until I create a nickname with a special character in it (like $). Then trying to view the main page (subject-list) returns the following: django.urls.exceptions.NoReverseMatch: Reverse for 'subject-detail' with arguments '()' and keyword arguments '{'nickname': '$'}' not found. 1 pattern(s) tried: ['subjects/(?P[^/].+)/$'] What is the best way of fixing this? I can try and sanitize all database inputs so they only contain alphanumeric characters, but it might be nicer to deal with this properly (to support Unicode properly etc...) -
Streaming audio file conversion process
I am integrating IBM speech to text API to my Django project. The problem that I have right now is that we allow users to upload audio files and majority of them are in the format of mp3 or mp4. However the API only take flac or wav format. I am currently using ffmpeg for file conversion. But this audio conversion library loads the entire audio file in memory as opposed to doing it in chunks. I wonder what would be a good solution to this problem or other packages that I should use? -
requests.post fail inside of django shell but not python shell
When I execute : requests.post("https://slack.com/api/chat.postMessage", data= {"channel": "maison"}) it fails in the django shell (python manage.py shell) with the error : InvalidCodepoint: Codepoint U+002A at position 1 of u'*' not allowed but it doesnt fail in the python shell. So this tells me it is probable something Django related. It was working before, and the only thing I changed is that I updated the SSL certificate of my server Thanks complete trace of the error is : Traceback (most recent call last): File "<console>", line 1, in <module> File "/usr/lib/python2.7/dist-packages/requests/api.py", line 107, in post return request('post', url, data=data, json=json, **kwargs) File "/usr/lib/python2.7/dist-packages/requests/api.py", line 53, in request return session.request(method=method, url=url, **kwargs) File "/usr/lib/python2.7/dist-packages/requests/sessions.py", line 468, in request resp = self.send(prep, **send_kwargs) File "/usr/lib/python2.7/dist-packages/requests/sessions.py", line 576, in send r = adapter.send(request, **kwargs) File "/usr/lib/python2.7/dist-packages/requests/adapters.py", line 376, in send timeout=timeout File "/usr/local/lib/python2.7/dist-packages/urllib3/connectionpool.py", line 594, in urlopen chunked=chunked) File "/usr/local/lib/python2.7/dist-packages/urllib3/connectionpool.py", line 350, in _make_request self._validate_conn(conn) File "/usr/local/lib/python2.7/dist-packages/urllib3/connectionpool.py", line 833, in _validate_conn conn.connect() File "/usr/local/lib/python2.7/dist-packages/urllib3/connection.py", line 324, in connect cert = self.sock.getpeercert() File "/usr/local/lib/python2.7/dist-packages/urllib3/contrib/pyopenssl.py", line 312, in getpeercert 'subjectAltName': get_subj_alt_name(x509) File "/usr/local/lib/python2.7/dist-packages/urllib3/contrib/pyopenssl.py", line 185, in get_subj_alt_name for name in ext.get_values_for_type(x509.DNSName) File "/usr/local/lib/python2.7/dist-packages/urllib3/contrib/pyopenssl.py", line 141, in _dnsname_to_stdlib name = idna.encode(name) File "/usr/lib/python2.7/dist-packages/idna/core.py", line 354, in encode … -
Django 1.10 run script standalone - django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet
I am trying to run script alone with Django 1.10, Python 3.5 and the code will use the Django model. the script located in the root of Django project. import os import sys import django from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "proj.settings") application = get_wsgi_application() from pipeline.models import * c = ModelName.objects.all() I got the error of django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. for the following line of code. application = get_wsgi_application() Previously, I was using Django-extension - runscript to run these scripts to perform data processing task, but it relies on the manage.py, which is not compatible with celery(provide periodic task management.) Do you have any idea to solve the problem or how to combine runscript with celery? -
Django Rest Framework limit the amount of items pulled from many to many serializer
This is my model: class Campaign(models.Model): ... associated_entities = models.ManyToManyField(db_index=True, to='Entity', through='EntityToCampaignMap') ... A campaign can contain many many entities, but I want to limit the amount of entities I'm pulling with my serializer here: class CampaignSerializer(serializers.ModelSerializer): ... associated_entities = EntityToCampaignMapSerializer(source='entitytocampaignmap_set', many=True) class Meta: model = Campaign fields = ( 'id', ... 'associated_entities', ...) This pulls in as many entities as it can. Is there a way to limit it to say, 50 elements at most? -
Using X-Editable with Django - not returning JSON
I've read through every answer I could find and nothing seems click with me so I can get my project working. I have a Django site that I would like to use X-editable ( similar to Jquery I believe ) but can't figure out how to send my data in JSON. I am sure it's something simple, but I can't find my error. My code is below. <!DOCTYPE HTML> <html lang="en"> </html> <head> <meta charset="utf-8"> </head> <link href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet"> <script src="http://code.jquery.com/jquery-2.0.3.min.js"></script> <script src="//netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js"></script> <link href="//cdnjs.cloudflare.com/ajax/libs/x-editable/1.5.0/bootstrap3-editable/css/bootstrap-editable.css" rel="stylesheet"/> <script src="//cdnjs.cloudflare.com/ajax/libs/x-editable/1.5.0/bootstrap3-editable/js/bootstrap-editable.min.js"></script> <body> <p></p> <div class="container"> <table class="table table-hover table-responsive"{% if table.attrs %} {{ table.attrs.as_html }}{% endif %}> <tr> <th>Project</th> <th>Employee</th> <th>Percent on Project</th> <th>Total Utilization</th> <th>Start</th> <th>End</th> </tr> {% for detail in utilization %} <tr> <td class="col-md-1">{{ detail.proj }}</td> <td class="col-md-2"> {{ detail.employee.last_name }} </td> <td class="col-md-2"><a href="#" name="{{ detail.percent_allocated }}" data-name="percent_allocated" data-params="{csrfmiddlewaretoken:'{{csrf_token}}'}" class="editable" data-url="/employee_post" data-type="text" data-pk="{{ detail.id }}" title="Project Name">{{ detail.percent_allocated }}</a></td> <td class="col-md-1"> {{ detail.total_utilization }} </td> <td class="col-md-1"> {{ detail.week_start }}</td> <td class="col-md-1"> {{ detail.target_complete }}</td> </tr> {% endfor %} </table> <button type="button" class="btn save-btn btn-primary">Save</button> </div> <script> function getCookie(name) { var cookieValue = null; if (document.cookie && document.cookie !== '') { var cookies = document.cookie.split(';'); for (var i = … -
Showing Deprecation Warnings Only for a Specific Version When Testing Django
I am about to upgrade from Django 1.9 to 1.10 and would like to test if I have some deprecated functionality. However using python -Wall manage.py test will show tons and tons of warnings for Django 2.0. Is there a way to suppress warnings only for 2.0 or show only warnings for 1.10? -
Sphinx Autodoc is not getting docstrings from decorated functions
While I know there are people who have asked questions about this in the past and the answer is to use functools.wraps and make sure that the __doc__ value is available, I am having an issue because that is not working. I have a django project that I am documenting with Sphinx and have some code that will successfully document and other code that does not. I am attempting to have autodoc pull the docstrings from the views file, however it is not showing any of the functions that have decorators, specifically the decorator used to check permissions, whose skeleton is outlined below. The decorator that does not require any variables passed in does not prevent the docstrings for those functions from being consumed and displayed: def permission_check(*permissions): def _decorate(view_function): def _check(request, arg1, arg2=None, *args, **kwargs): ... The check stuff happens here ... _check.__name__ = view_function.__name__ _check.__dict__ = view_function.__dict__ _check.__doc__ = view_function.__doc__ setattr(_check, 'permissions', [permissions]) return _check return _decorate This is then used on the views like so: @permission_check('index.view') def index(request, arg1): """ Docstring is here :param request: The request :type request: :mod:`django.http.HttpRequest` :returns: The index page :rtype: :mod:`django.http.HttpResponse` """ ... Do function stuff here and return... If I comment …