Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to use joins in Django?
I want the details of lender whose state,distrtict,religion,profession equals to borrowers details i.e;(state,distrtict,religion,profession) This is borrowers models.py class Borrower(models.Model): district = models.TextField(blank=True) state = models.TextField(blank=True) profession = models.TextField(blank=True) religion = models.TextField(blank=True) This is Lenders models.py class LenderStateDistrict(models.Model): lenderId = models.CharField(max_length=5) state = models.CharField(max_length=50,**optional) district = models.CharField(max_length=50,**optional) class LenderReligion(models.Model): lenderId = models.CharField(max_length=5) religion = models.CharField(max_length=50, **optional) class LenderMultipleProfessions(models.Model): lenderId = models.CharField(max_length=5) profession = models.CharField(max_length=50,**optional) views.py @api_view(['GET']) def xyz(request): borrower1= Borrower.objects.get(id =1) city = borrower1.district state = borrower1.state profession = borrower1.profession religion = borrower1.religion I got every requirement for borrower and then how to query based on the three tables i.e; LenderStateDistrict,LenderReligion,LenderMultipleProfessions,if the borrowers district,state,religion,profession equals to the lenders then it should give the details how to query it? -
Django prefetch_select and reverse join issue
I am working on multiple join with Django. questions = Question.objects.select_related( 'publishedquestionmapping__library_question' ).prefetch_related( 'publishedquestionmapping__library_question__contributor_set__user', ).filter( hide=False).order_by('-pub_date')[:count] for question in questions: contributers = question.publishedquestionmapping.library_question.contributor_set.all() for contributer in contributers: print contributer.user The Error is RelatedObjectDoesNotExist: Contributor has no user. The problem is that I can use prefetch_related ...contributor_set__user, but I can't use contributer.user? btw, print contributer.user_id is ok. I want to do like contributer.user.username. How should I do that?! Thanks! -
Django: Trying to make for zip work with Python Jinja
Hello guys I have this code and it works perfectly in python: var1 = ('puno', 'pdos', 'ptres') var2 = ('runo', 'rdos', 'rtres') for x, y in zip (var1, var2): hola = x, y for x in hola: print x The output of this it's exactly what I'm looking: uno runo pdos rdos ptres rtres [Finished in 0.1s] I'm trying to get the same using django with jinja but it does not work for me even If use "zip" in jinja, Is there any way to have this result in jinja? Let me show my code using django: def todo(request): lista_completa = Data_pregunta.objects.all()#.order_by('id')[:2] lista_completa2 = Data_respuesta.objects.all()#.order_by('id')[:2] return render(request, 'todo.html', {'lista_completa': lista_completa,'lista_completa2':lista_completa2}) Jinja: {% for x in lista_completa %} {{x.pregunta}}<br> {% endfor %} What I'm looking is to get the result of Data_pregunta then Data_respuesta, is it possible ? I think the problem is not python is that I'm nor using jinja properly, can you guys give me a hand ? Thank you! -
Django-recurrence Parsing
I have a recurrence in the database from Django-recurrence - http://django-recurrence.readthedocs.io/en/latest/index.html Note: This utility provide a Jscript UI interface to dateutil.rrule - It is used for working with recurring dates in Django. 'RRULE:FREQ=WEEKLY;INTERVAL=2;UNTIL=20170511T050000Z;BYDAY=MO,TU,WE,TH,FR,SA,SU\n' 'RDATE:20170224T060000Z\n' 'EXDATE:20170228T060000Z', How do I parse this? -
Django : Form in forms.py does not displayed in HTML
I've been trying to render HTML using form I made in forms.py, however this is not working, just fail to loaded without error message. Also, there is no message in console too, so I'm having hard time to fix this. Please take a look and tell me which part is wrong. This is urls.py url(r'^profile/(?P<username>[-\w.]+)/$', views.profile, name='profile'), url(r'^password_change/(?P<username>[-\w.]+)/$', views.password_change, name='password_change'), url(r'^password_change_done/$', views.password_change_done, name='password_change_done'), forms.py class PasswordChangeForm(forms.Form): oldpassword = forms.CharField(max_length = 20, widget=forms.TextInput(attrs={'type':'password', 'placeholder':'your old Password', 'class' : 'span'})) newpassword1 = forms.CharField(max_length = 20, widget=forms.TextInput(attrs={'type':'password', 'placeholder':'New Password', 'class' : 'span'})) newpassword2 = forms.CharField(max_length = 20, widget=forms.TextInput(attrs={'type':'password', 'placeholder':'Confirm New Password', 'class' : 'span'})) class Meta: model = User fields = ("username",) field_classes = {'username': UsernameField} def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) if self._meta.model.USERNAME_FIELD in self.fields: self.fields[self._meta.model.USERNAME_FIELD].widget.attrs.update({'autofocus': True}) def clean(self): if 'newpassword1' in self.cleaned_data and 'newpassword2' in self.cleaned_data: if self.cleaned_data['newpassword1'] != self.cleaned_data['newpassword2']: raise forms.ValidationError(_("The two password fields did not match.")) return self.cleaned_data def save(self, commit=True): user = super().save(commit=False) user.set_password(self.cleaned_data["password1"]) if commit: user.save() return user views.py @login_required def password_change(request, username): if request.method == 'POST': form = PasswordChangeForm(data=request.POST, user=request.user) print("username is "+username) if form.is_valid(): #form.save() update_session_auth_hash(request, form.user) form.save() print("A") return HttpResponseRedirect('/blog/password_change_done/') else: update_session_auth_hash(request, form.user) form.save() print("B") return redirect(reverse('blog:profile', args=[form.user.get_username()])) else: print("C") form = PasswordChangeForm(user=request.user)#unbound return … -
Create a wav file from blob audio django
On the client side, I am sending a blob audio (wav) file. On the server side, I am trying to convert the blob file to an audio wav file. I did the following: blob = request.FILES['file'] name = "TEST.wav" audio = wave.open(name, 'wb') audio.setnchannels(1) audio.writeframes(blob.read()) I thought that converting the blob would be similar to converting a blob image to a jpeg file, but was very incorrect in that assumption. That didn't work; I get an error - "Error: sample width not specified." I then used setsampwidth() and tossed in an arbitrary number between 1 and 4 (after looking at the wave.py source file...I don't know why the bytes have to be between 1 and 4). After that another error is thrown - "Error: sampling rate not specified." How do I specify the sampling rate? What does the setnchannels(), setsampwidth() methods do? Is there an "easy" way I generate the wav file from the blob? -
How To Structure Table In Django With Overlapping Items
I'm building a webapp using Django, that's going to be used to keep track of people and job/gig vacancies. Types of people who we're trying to help are distinct, but people may be in more than one category. To give a more concrete example, let's that I have actors, singers, dancers. I could set up three tables: class Actor(models.Model): name = models.TextField(max_length=100) dob = models.DateField() email = models.EmailField() number = models.TextField(max_length=15) sex = models.TextField(max_length=1) dramatic = models.BooleanField() comedic = models.BooleanField() height = models.DecimalField(max_digits=3, decimal_places=2) weight = models.DecimalField(max_digits=5, decimals_places=2) class Singer(models.Model): name = models.TextField(max_length=100) dob = models.DateField() email = models.EmailField() number = models.TextField(max_length=15) sex = models.TextField(max_length=1) style = models.TextField(max_length=20) range = models.TextField(max_length=50) class Dancer(models.Model): name = models.TextField(max_length=100) dob = models.DateField() email = models.EmailField() number = models.TextField(max_length=15) sex = models.TextField(max_length=1) style = models.TextField(max_length=20) It would be very nice, for a long list of reasons, to be able to identify people uniquely. If I was doing this in sql I'd have a People table, where I stored information like name, dob, etc. Then have Actors table that contained PersonId as a foreign key, and all the actor specific attributes. Then I'd create a view that allowed me to see the joined data. However, … -
Load data on a web page based on what was clicked on another
Is there anyway that I can pass the id of an element from one html page to another? Essentially, I have a drop down with about 50 choices and based on whats clicked I want my second html page to load data from my database corresponding to the user's choice. I have a function on the second page that loads the data using an ajax query. But is there a way t pass the id of what was clicked to that function. Or is there another way to do it? I have no idea how to go about doing this. I am really new to all of this. I am using django to populate the drop down menu and the other page. Thanks for the help =) -
calling super on base class python/django
Before you mark it as duplicate, let me state that I understand how super works and I have read these three links: What does 'super' do in Python? Understanding Python super() with __init__() methods http://python-history.blogspot.nl/2010/06/method-resolution-order.html This is how super is supposed to work in case of baseclasses: class X(object): def __init__(self): print "calling init from X" super(X, self).__init__() class Y(object): def abc(self): print "calling abc from Y" super(Y, self).abc() a = X() # prints "calling init from X" (works because object possibly has an __init__ method) b = Y() b.abc() # prints "calling abc from Y" and then # throws error "'super' object has no attribute 'abc'" (understandable because object doesn't have any method named abc) Question: In django core implementation, there are several places where they call methods using super on classes inheriting from object (case Y in my example above). For example: can someone explain me why this code works? from django.core.exceptions import PermissionDenied class LoginRequiredMixin(object): def dispatch(self, request, *args, **kwargs): if not request.user.is_authenticated(): raise PermissionDenied return super(LoginRequiredMixin, self).\ dispatch(request, *args, **kwards) # why does this work? Ref: copied this code from this talk: https://youtu.be/rMn2wC0PuXw?t=403 -
Passing a value with whitespace from an html page to a view
I'm populating a dropdown box with values from a model as follows (abbreviated): <select name="dropdown"> {% for thing in storedvalues %} <option value={{ thing.name }}>{{ thing.name }}</option> {% endfor %} </select> <input type="submit" value="Filter" id="bbutton"/> and in the view... def testpage(request): if request.method == 'POST': result = request.POST.get('dropdown') print("hey this is the value: ", result) selected_result = Song.objects.filter(name=result) return render(request, 'testpage.html', {'selected_result': selected_result,}) This mostly works correctly. I select a value from a dropdown list and it returns the all of the data relating to the selected value. However when a value has white space in it, any characters following the white space are lost. I'm not sure how to go about fixing this. If anyone could point me in the right direction it would be much appreciated -
Multi-tiered Wagtail CMS ModelAdmin Customization
Not sure if I'm over thinking an easy task or over reaching the capabilities of Wagtail ModelAdmin customizations. I'm building a new site for a local restaurant and want to provide a way for them to add add and update menu items. I'm using Snippets in conjunction with abstract models and have successfully created a ModelAdminGroup based on my Product model. I've included a Stitch annotated screenshot below. Currently I can create a new product and add a menu and price through a MenuPrices abstract model. My current challenge is trying to figure out how to allow them to create a new MenuSection I.e Salads, Starters, Pizza etc.. and then add products to those MenuSections. I know I can create a MenuSection model and add the Product model Inline, but I need the products as a ModelGroup for searching, filtering and just easier to user. Any suggestions down the right path would be awesome. Thanks. MenuSection I.e. Salads, Soups etc.. @register_snippet class MenuSection(ClusterableModel): section_title = models.CharField(null=True, blank=True, max_length=250, verbose_name='Section Title') section_intro = models.CharField(null=True, blank=True, max_length=500, verbose_name='Section Intro') class Meta: verbose_name = 'Menu Section' panels = [ MultiFieldPanel( [ FieldPanel('section_title'), FieldPanel('section_intro'), ], heading='Choose a Menu Section', classname='collapsible' ), ] def __str__(self): … -
How to create link for a file in the unix system from a django app?
I have created a web app using django5 framework. The app triggers selected PERL script in the back end as per the user's selection. The app captures the output of each PERL script and writes it to a new logfile for each run. I would like to create a link of each logfile and display it on the web page so that the users can view the contents of the logfile. I would like to know how to achieve this. Any pointers or help is greatly appreciated. I have not deployed the web app to wider audience yet. I am running the app using the following manage.py runserver 0.0.0.0 Thanks in Advance, -
Safety in webapp design, how to update saved plot?
I'm using python 3 and django to build an app. My app allows users to enter in values, which updates a plot under the entry field. This plot is saved over my png in the static directory. I don't like this! I think it would be great if the plot updated, saved somewhere local for the user, and then showed up for them under the entry field. I'm concerned with the safety of saving this file in the static directory. If several people try updating the plot at once, I would imagine either a crash would occur, or the plot would just keep updating when people don't want it to. I'm quite new to webapp development, and would like a few suggestions to handle this case. Directing me towards relevant classes or methods in the documentation would be ideal. -
Mysql AES_DECRYPT() function not working in Django raw query
When I use MySql function AES_DECRYPT() in a raw query in Django, this function didn't work. My code is like this: sql = "select AES_DECRYPT(myfield, mykey) as ssn from mytable " people_list = Peopletable.objects.raw(sql) for p in people_list: print p.ssn It printed out None, which means AES_DECRYPT() didn't work. But if I run the query in python side then I get what I need. I tried other mysql functions like SUBSTR() and they worked perfectly. Seems like only this AES_DECRYPT() doesn't work in Django. Can anyone help? Thanks a lot! -
Heroku collectstatic not correctly referencing some static files in template
The main issue that I'm having is that collectstatic runs fine however not all of the postprocessed(?) static files are correctly referenced in my templates on Heroku. So here's the <head> of my base.html on Heroku: <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.6.0/css/font-awesome.min.css"> <link rel="stylesheet" type="text/css" href="/static/css/bootstrap.min.5b993e1df812.css"> <link href="/static/css/base.ee0708264b81.css" rel="stylesheet"> <script src="/static/js/jquery-2.2.3.min.33cabfa15c10.js"></script> <script src="/static/js/moment.min.5584d3bedf9e.js"></script> <script src="/static/js/fullcalendar.min.a53fe55bda20.js"></script> <script src="/static/js/home.fe1758a85223.js"></script> Here it is in my template: <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.6.0/css/font-awesome.min.css"> <link rel="stylesheet" type="text/css" href="{% static 'css/bootstrap.min.css' %}"> <link href="{% static 'css/base.css' %}" rel="stylesheet"> <script src="{% static 'js/jquery-2.2.3.min.js' %}"></script> <script src="{% static 'js/moment.min.js' %}"></script> <script src="{% static 'js/fullcalendar.min.js' %}"></script> <script src="{% static 'js/home.js' %}"></script> (These files, of course, exist locally) Upon clicking the links on Heroku, all of them work except jquery-2.2.3.min.33cabfa15c10.js and base.ee0708264b81.css which give me a 404. Using heroku run bash then confirms that these files do not exist on Heroku but a base.css and jquery-2.2.3.min.js with a different combination of characters on the end do exist. I have tried deleting the entirety of the staticfiles directory, collecting static and then reuploading to Heroku but this doesn't work. The filenames of all of those files stays the same upon re-collecting static. How do I get Heroku to update to the correct filename? Settings.py below if necessary. … -
Using Django's cache_page decorator to built key
Using Django’s cache framework I need the cache key to be based on the Authorization: Bearer token. The error/problem I have is that Django serves me the same cache results for different tokens. url(r'^/item/?$',cache_page(3600)(ItemView.as_view()),name='item'), Is there a way to add into the URL's above a way to build the Django cache key on the token in the Authorization: Bearer header? I see Django has Very headers https://docs.djangoproject.com/en/1.10/topics/cache/#using-vary-headers which can be added to the view function. The examples don't show how I would add this to my class based view? Is this possie? I have tried this... from django.views.decorators.vary import vary_on_headers @vary_on_headers('Authorization') class ItemView(generics.ListCreateAPIView): pass -
GeoDjango tif import with "Raster needs to be opened in write mode to change values error"
I am trying to import raster file to PostGIS via Django Shell. I create a class in my model, looks like that: class MaxentModel(gismodels.Model): birdname = models.ForeignKey('BirdName', null=True) model_probability = gismodels.RasterField(srid=4326, null=True) Then I want try to import first raster data with these commands from documentation (tried in Django shell): >>>from validation_birds.models import BirdName, MaxentModel >>>taxon_name_object = BirdName.objects.filter(name_cz='name of the bird')[0] >>>rast = MaxentModel(birdname=taxon_name_object, model_probability='/path/to/file/picture.tif') >>>rast.save() But with rast.save() exceptions is raised and I get this error: raise GDALException('Raster needs to be opened in write mode to change values.') django.contrib.gis.gdal.error.GDALException: Raster needs to be opened in write mode to change values. What does it mean that raster need to be opened in write mode and why GDAL wants change values (is it because of some setting)? How can I get over this error? I cannot find some information about this exception so I will be glad for any help -
In django, can I show post's permalink in admin page?
I have a model called Post for my Blog application in Django. I have a slug field that is prepopulated by the title field. (I also use the get_absolute_url method, if that matters). What I want is to be able to see the permalink, of course without being able to edit it! Just readonly. I also believe that this field will be empty when I create a post, so only visible-active when I update a post. Thanks in advance. -
Ordering by many to many attribute on Django Rest Framework
I have a table of TransportationOrders. Every TransportationOrder has a Route.. and every Route has Places. What I need to do is to ordering by the name of the first place I have to visit. My Models simplified: class TransportationOrder(models.Model): name = models.CharField(max_length=45, unique=True) user = models.ForeignKey('auth.User') description = models.CharField(max_length=300, blank=True, null=True) routes = models.ManyToManyField(Place, through='PlaceHasTransportationOrder') class PlaceHasTransportationOrder(models.Model): place = models.ForeignKey(Place, on_delete=models.CASCADE) transportation_order = models.ForeignKey(TransportationOrder, related_name="route", on_delete=models.CASCADE) order = models.IntegerField(default=1) date = models.DateField() notes = models.CharField(max_length=400, blank=True, null=True) class Place(models.Model): name = models.CharField(max_length=45) address = models.CharField(max_length=45, null=True, blank=True, default=None) lat = models.FloatField(null=True, blank=True, default=None) lon = models.FloatField(null=True, blank=True, default=None) I tried to define a method on TransportationOrder Model, but this doesn't work whe I try to http:///url?ordering=first_place_name because this ordering works on a database level. What option do I have? def first_place_name(self): place = Place.objects.all().filter(placehastransportationorder__transportation_order=self, placehastransportationorder__order=1) return place[0].name -
Basic django-pytest tests
Even just learning the django and testwriting, so I need a bit of confirmation. I would like to know that the following tests are "correct" spelling of it. test_view.py @pytest.mark.django_db def test_create_form(client): form_data = {'title': 'Test Title', 'tags': 'HTML', 'content': 'New Content for lambs'} response = client.post(reverse("public:create"), form_data, follow=True) assert b'Test Title' in response.content @pytest.mark.django_db def test_context_create(client): form_data = {'title': 'Test Title', 'tags': 'HTML', 'content': 'New Content for lambs'} response = client.post(reverse("public:create"), form_data) assert response.context['form'].cleaned_data['title'] == 'Test Title' @pytest.mark.django_db def test_TITLE_is_blank(client): form_data = {'title': '', 'tags': 'HTML', 'content': 'New Content for lambs'} response = client.post(reverse("public:create"), form_data) assert response.context['form'].cleaned_data['title'] == '' @pytest.mark.django_db def test_CONTENT_is_blank(client): form_data = {'title': 'Test Title', 'tags': 'HTML', 'content': ''} response = client.post(reverse("public:create"), form_data) assert response.context['form'].cleaned_data['content'] == '' @pytest.mark.django_db def test_CONTENT_and_TITLE_is_blank(client): form_data = {'title': '', 'tags': 'HTML', 'content': ''} response = client.post(reverse("public:create"), form_data) assert (not response.context['form'].is_valid()) forms.py class PostForm(ModelForm): def __init__(self, *args, **kwargs): super(PostForm, self).__init__(*args,**kwargs) self.fields['title'].required = False self.fields['content'].required = False class Meta: model = Post fields = ['title', 'tags', 'content'] def clean(self): form_data = self.cleaned_data if (form_data['title'] is not "") or (form_data['content'] is not ""): return form_data else: self._errors["title"] = ["Two field is empty"] def save(self, *args, **kwargs): instance = super(PostForm, self).save(commit=False) instance.slug = slugify(instance.title) instance.save() return … -
Configurable ForeignKey model in an abstract Django model
I have an abstract model like this: class Like(models.Model): TARGET_MODEL = 'TargetModel' user = models.ForeignKey(settings.AUTH_USER_MODEL) target = models.ForeignKey(TARGET_MODEL) class Meta: abstract = True and I want to make the TARGET_MODEL be different in every subclass. For example a model LikeForPost that references the Post model from the blog application: class LikeForPost(Like): TARGET_MODEL = 'blog.Post' It doesn't seem to be working, as the TARGET_MODEL is not instantiated from the subclass. What would be the correct way to achieve this? I know that I can redefine the whole target field in the LikeForPost class, but I hope there is a more elegant solution, that allows to override only the model name. -
Django template won't run Google Maps javascript inside a block
I have a base.html and an index.html that extends base.html and fills out a {% block content %}{% endblock %}. However, for some reason, the javascript that I have in the block that deals with initiating a Google Map doesn't create the map - the page is blank. Without extending the base.html (i.e. just by typing everything in base.html out in index.html explicitly), the map works fine. The code: base.html <!DOCTYPE html> {% load static %} <html> <head> <title>Title</title> <link rel="stylesheet" type="text/css" href='{% static "mh_app/style.css" %}' /> </head> <body> <header id="header"> <div class="header-cont"> <h1> Title </h1> <nav id="nav"> <ul> <li> <a href="{% url 'index' %}">Home</a> </li> <li> <a href="{% url 'download' %}">Download</a> </li> <li> <a href="{% url 'about' %}">About</a> </li> </ul> </nav> </div> </header> {% block content %}{% endblock %} </body> </html> index.html {% block content %} <div id='map'></div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script> <script type='text/javascript'> function initMap() { var map = new google.maps.Map(document.getElementById('map'), { center: {lat: 38.3499047, lng: -100.0770253}, zoom: 4 }); } </script> <script src="https://maps.googleapis.com/maps/api/js?key=<my_api_key>&callback=initMap" async defer></script> {% endblock %} I've tried sticking some console.log statements inside initMap(), and they run just fine, so I have no idea why the map is not appearing. -
Type object 'X' has no attribute 'DoesNotExist' with django
I keep getting the has no attribute DoesNotExist error. Any ideas why? So far I tried: try: current_report = Report.objects.get(account_profile=current_profile) except Report.DoesNotExist: print("report doesn't exist") current_report=None And my debug shows type object 'Report' has no attribute 'DoesNotExist' at line current_report(etc): I also tried: from django.core.exceptions import ObjectDoesNotExist ... except Report.ObjectDoesNotExist: and try: Report.objects.get(account_profile=current_profile) except Report.DoesNotExist: print("report doesn't exist") current_report=None and try: Report.objects.get(account_profile=current_profile) except ObjectDoesNotExist: print("report doesn't exist") current_report=None Why does type object 'X' have no attribute 'DoesNotExist'? I'm using django. -
django post redirects to it's own page
I have a form which is displaying table with data and two select dropdown whit who you can choose date/year to display data, so I'm returning context for table and with get_initial I'm populating dropdowns to use current date and time. My question is how to make POST request redirects to it's own page with GET, the idea is to set values in some query parameters in the url like ?month=1&year=2016, but I don't know where to start, can someone help me understand this, thanks. from django.views.generic.edit import FormView from django.utils import timezone from .models import Rate from statistics.forms import StatisticsForm from statistics.services import StatisticsCalculation class StatisticsView(FormView): template_name = "statistics/invoice_statistics.html" form_class = StatisticsForm def get_initial(self): initial = super(StatisticsView, self).get_initial() initial["month_choice"] = timezone.now().month initial["invoice_year"] = timezone.now().year return initial def get_context_data(self, **kwargs): context = super(StatisticsView, self).get_context_data(**kwargs) default_currency = Rate.EUR currency_usd = Rate.USD currency_gbp = Rate.GBP context["can_view"] = self.request.user.is_superuser context["currency"] = default_currency context["currency_usd"] = currency_usd context["currency_gbr"] = currency_gbp context["statistic"] = StatisticsCalculation.\ statistic_calculation(supplier_default_currency) context["statistic_usd"] = StatisticsCalculation. \ calculation(supplier_default_currency_usd) context["statistic_gbp"] = StatisticsCalculation. \ statistic_calculation(supplier_default_currency_gbp) return context -
test PermissionRequiredMixin raises PermissionDenied instead of 403
I am using django 1.10.5 and the PermissionRequiredMixin. Instead of redirecting users to the login, I want to return a 403-error if they don't have the right permission. In theory, if PermissionDenied is raised anywhere, the response-object should have a status_code of 403: The only exceptions that are not visible to the test client are Http404, PermissionDenied, SystemExit, and SuspiciousOperation. Django catches these exceptions internally and converts them into the appropriate HTTP response codes. In these cases, you can check response.status_code in your test. From the documentation: https://docs.djangoproject.com/en/1.10/topics/testing/tools/#exceptions However, my tests stop on an exception django.core.exceptions.PermissionDenied This is the simplest test.py: from django.test import TestCase, RequestFactory from doingTests.views import ViewWithPermission from django.contrib.auth.models import User from django.core.exceptions import PermissionDenied class TestPermission(TestCase): def test_permission_view(self): user = User.objects.create(username="john", password="doh") permView = ViewWithPermission.as_view() rf = RequestFactory() request = rf.get('/test/') request.user = user self.assertEqual(permView(request).status_code, 403) With this view.py: from django.contrib.auth.mixins import PermissionRequiredMixin from django.views.generic.base import TemplateView class ViewWithPermission(PermissionRequiredMixin, TemplateView): permission_required="doingTests.add_mock" raise_exception=True What permission is required is actually not important, random strings, custom permissions and builtin permissions all raise PermissionDenied. Since there are so many variables here, I might just have missed something, e.g. permission_required needs a permission-object instead of a string (tried that). But I'm …