Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Run python script with Django
I need to run this simple python script and display the output in html. how do i do this in django? here is the script import urllib r='http://c.lo.com/cl/PHP/grweather.php' openurl= urllib.urlopen(r) readurl= openurl.read() date= readurl[10:20] humidity= readurl[62:66] temperature= readurl[83:87] windspeed= readurl[136:140] print(date, humidity, temperature, windspeed) thanks in advance :) -
Updating element in database using a user defined primary key Django
I understand that the save() method decides whether it should insert or update depending on whether the primary key is already in the database. I am using a charField as a primary key. My problem is that when I try and submit the form it gives an error saying that there already is an element with that primary key in the database, which is what I am testing but it should update that row instead of just throwing an error. So the error is happening in is_valid but I am not sure how to by pass this. Because if I just take that out then it gives an error saying that the data was not validated. views.py def sxsw(request): if request.method == 'POST': form = SXSWForm(request.POST) if form.is_valid() : form.save() return redirect('/sxsw/formSubmitted/') else: print form.errors else: form = SXSWForm() return render(request, 'sxsw/sxsw.html', {'form': form}) models.py class SXSWDemo(models.Model): SIMULATIONS = ( ('ABC', 'ABC'), ('Asterix', 'Asterix'), ('Home', 'Home'), ) PET = ( ('Dog', 'Dog'),('Cat', 'Cat'), ('Fish','Fish'),('Hamster', 'Hamster'), ) COLOR = ( ('Red', 'Red'), ('Blue', 'Blue'), ('Green', 'Green'), ('Purple', 'Purple'), ('Black', 'Black'), ('White', 'White'), ) firstAndLastName = models.CharField(max_length = 50, primary_key=True) email = models.EmailField(null = True, blank = True) simulation = models.CharField(max_length = … -
Save and retrieve a form with session?
I have a context_processor.py file with the following function def include_user_create(request): if 'form' not in request.session: form = CreateUserForm() else: form = request.session['form'] return { 'create_user_form' : form } I use this to display my register in my base.html template, so that I may reuse it for all pages. A function create_user handles the form submit def create_user(request): form = CreateUserForm(request.POST or None, request.FILES or None) if request.method == 'POST': if form.is_valid(): user = form.save(commit=False) user.save() user = authenticate(username=user.email, password=user.password) else: request.session['form'] = form #<--- save next = request.POST.get('next', '/') return HttpResponseRedirect(next) If the form is invalid I'd like to save the form so that the context_processor may reuse the form, for the purpose of saving the errors so they may be displayed in the template. Doing this gives me a error: TypeError: <CreateUserForm bound=True, valid=False, fields=(email;password;confirm_password)> is not JSON serializable Is it possible to get this to work somehow? -
Trying to organize my urls
My site has different urls for different categories, which returns a filtered queryset based on the category, e.g. /sport/ will return Post.objects.filter(category='sport') urls urlpatterns = [ url(r'^news/$', boxes_view, name='news'), url(r'^sport/$', boxes_view, name='sport'), url(r'^technology/$', BV, name='technology'), url(r'^science/$', BV, name='science'), url(r'^cars/$', BV, name='cars'), url(r'^television/$', BV, name='television'), url(r'^(?P<category>\w+)/(?P<id>\d+)/', article, name='article'), view def boxes_view(request): category = 'news' for a, b in CATEGORY_CHOICES: name = resolve(request.path_info).url_name if b == name: category = a posts = Post.objects.all().filter(category=category) choices.py CATEGORY_CHOICES = ( ('1', 'news'), ('2', 'sport'), ('3', 'technology'), ('4', 'science'), ('5', 'cars'), ('6', 'television') ) Instead of listing every category in my urls, is there anyway I can write just 1 uniform url pattern to account for all of them? -
Optimizing a Friendship Query?
Optimizing a Friendship Query? Hi, I'm doing unit tests on my application and found that the method for listing user friends takes twice as long to run compared to any other unit test. Can anyone suggest an optimization? models.py class Friend(models.Model): user = models.ForeignKey(User) friend = models.ForeignKey(User, related_name="friends") state = models.PositiveIntegerField(choices=FriendState.choices(), default=FriendState.WAITING) created_at = models.DateTimeField(_('date created'), default=timezone.now) view.py I use a modified Django Channels library, but it follows the same logic as a "simple view" class UserFriendsBinding(ResourceBinding): model = Friend available_actions = ('list',) serializer_class = FriendBasicInfoSerializer permission_classes = (IsAuthenticated,) send = '__self__' def get_queryset(self): queryset = Friend.objects.filter(Q(user=self.user) | Q(friend=self.user)) return queryset serializer.py class FriendBasicInfoSerializer(serializers.ModelSerializer): class Meta: model = Friend fields = ('user', 'friend', 'state',) def to_representation(self, obj): if obj.user == self.context.get('user'): user = obj.friend you_invited = True else: user = obj.user you_invited = False friend_data = UserBasicInfoSerializer(user).data friend_data['you_invited'] = you_invited friend_data['situation'] = obj.state return friend_data (I modified the name of the "state" to "situation", because the serializer of the User object already has the variable "state") PS: I'm Brazilian, I'm sorry for my English. -
Check for template fails because "No templates used to render the response"
I am working through Test-Driven Development with Python by Harry J. W. Percival. I have a Django view with the following code: def view_list(request, list_id): list_ = List.objects.get(id=list_id) items = Item.objects.filter(list=list_) return render(request, 'list.html', {'items':items}) And the following Django test: def test_uses_list_template(self): list_ = List.objects.create() response = self.client.get('/lists/%d' % (list_.id,)) self.assertTemplateUsed(response, 'list.html') urls.py has the following entry: url(r'^lists/(.+)/$', views.view_list, name='view_list'), The test fails with the following error: self.fail(msg_prefix + "No templates used to render the response") AssertionError: No templates used to render the response This was very surprising, because the view rendered successfully when I used the browser to evaluate it manually. And an automated functional test worked without error. I looked at the HTTP server, and it was showing a redirect for a circumstance similar to this test: [time] "GET /lists/2 HTTP/1.1" 301 0 [time] "GET /lists/2/ HTTP/1.1" 200 476 -
How do I see the error logs for a Django App hosted on Digital Ocean?
I created a simple Django website and tried deploying it. Unfortunately I ran into a 502 bad gateway error. When I searched online, people were giving the error logs that they were given, which I don't see on mine. I am using the terminal to connect to the IP address of my website, and using Filezilla to move files onto my server, since I find the GUI version easier to use. My question is, what commands do I need to do in order to see the error logs? It uses Nginx and Gunicorn to host the website. -
Django - HttpResponse 2 query result in JSON format
I have 2 query results from the database and try to return it in json format like this. gt_buffer = ev_ground_truth.objects.filter(alg=_alg, exp=_exp,nFrame=_nframe) dt_buffer = ev_detection.objects.filter(alg = _alg, exp=_exp, nFrame=_nframe) json_gt_bb = serializers.serialize('json', gt_buffer) json_dt_bb = serializers.serialize('json', dt_buffer) dict_bb_buffer = {'gt': json_gt_bb, 'dt': json_dt_bb} json_bb_buffer = json.dumps(dict_bb_buffer, ensure_ascii=False) return HttpResponse(dict_bb_buffer, content_type = "application/json") And at the front-end, $.ajax({ url: '/results/get_nframebbs', data: { 'exp':_exp, 'alg':_alg, 'nframe':data[i]['fields'].nFrame }, dataType: 'json', success: function (data) { alert(data.length) } }); However the alert never be called. But if I just serialize 1 query result and return the alert is called successful with a popup. gt_buffer = ev_ground_truth.objects.filter(alg=_alg, exp=_exp,nFrame=_nframe) json_gt_bb = serializers.serialize('json', gt_buffer) return HttpResponse(json_gt_bb, content_type = "application/json") What did I do wrong? -
Django FormPreview: Save form data to database
Probably a simple question but having trouble implementing a form preview page using django-formtools. I've configured everything per the docs. I'm stuck on what to add to the done() method to save the data to db. forms.py class JobForm(ModelForm): class Meta: model = Job fields = ('title', 'category', 'company', 'website', 'description',) class JobFormPreview(FormPreview): def done(self, request, cleaned_data): # add what here to save form data as object? return HttpResponseRedirect('/success') urls.py ... url(r'^jobs/new/$', JobFormPreview(JobForm), name='job_form'), ... Using the default templates. The form and preview both render fine, but obviously data doesn't save on submit. Tried self.form.save() per this answer but get an error save() missing 1 required positional argument: 'self'. I appreciate any guidance. -
Django admin: Can I search through a field from another data table in search_fields?
Is it possible to search through a field from different database table using serach_fields in django? Please see the following example for better understanding. model.py class test1(models.Model): sources = models.CharField(max_length=50, null=True, blank=True) class test2(test1): name = models.CharField(max_length=50, null=True, blank=True) admin.py class test1Admin(admin.ModelAdmin): search_fields = ['sources'] class test2Admin(test1Admin): ... In this case, the search_fields at test2 is not working. I know why it is not working. However, I was wondering if there is any way to search 'sources' field from test2 table? -
django-tables2 header always stay on top
I want to have table header from django-tables2 stay always on top to a non-paginated table and not scroll with rest of table. I read for a lot of general (jquery, css) table header solutions but all of them have limitations (fixed column width, not responsive etc). Is there any native support from django-tables2 or any advice how i can achieve this? -
Why does a checkbox input looks so awful on a horizontal Django crispy form?
My project uses Twitter bootstrap on the front-end, the backend is Django, we also use crispy forms. fifth_year is a simple boolean model field class MyModel(models.Model): first_name = models.CharField(verbose_name="First Name", max_length=100) last_name = models.CharField(verbose_name="Last Name", max_length=100) school = models.CharField(verbose_name="School Type", null=True, blank=True, max_length=100, choices=WIDGET_SCHOOL_CHOICES) grad_yr = models.CharField(verbose_name="Class", null=True, blank=True, max_length=100, choices=WIDGET_GRAD_YR_CHOICES) fifth_year = models.BooleanField(verbose_name="5th Year", default=False) ... Essence of the form definition: self.helper = FormHelper(form=self) self.helper.form_class = 'form-horizontal' self.helper.label_class = 'col-sm-3 col-md-2' self.helper.field_class = 'col-sm-9 col-md-10' self.helper.layout = Div( FormActions( Submit('save', 'Save', css_class='btn-success'), Button('delete', 'Delete', css_class='btn-danger') ), Field('school'), Field('grad_yr'), Field('fifth_year'), # this is the boolean field Field('first_name'), Field('last_name'), Comes out ugly as hell: To my surprise I didn't find any good leads about why is it like that. I've seen InlineCheckboxes, but that doesn't help. -
Django - query does not seem to be right
What I want to accomplish: Admin is logging in to see all of the members in his group. What I get in return is all the members from others group which i do not want. I only want Admin to see members who are in his group. I am not getting the filters i want. Searching for solutions here with no luck and still a newbie so appreciate your help! admin\models.py class Administrator(AbstractUser): ... association = models.ForeignKey(Association) class Meta: db_table = 'Administrator' member\models.py from pl.admin.models import Administrator class Member(models.Model): member_no = models.AutoField(primary_key=True) association = models.ForeignKey('Association') ... class Meta: db_table = 'Member' class Association(models.Model): asoc_name = models.CharField(max_length=50, null=True, blank=True) class Meta: db_table = 'Association' Views.py class member_overview(ListView): model = Member template_name = 'member/member_overview.html' def get_members(self, *args, **kwargs): return Member.objects.filter(association=self.request.administrator.association) -
Reuse form on HttpResponseRedirect
I'm trying to create a feature so users can register no matter which page they're on. And on top of that I'm using this request.path so that I may redirect the user to the page they were on before registration. But my trouble is, if the user makes errors, they won't be shown from the form field.errors because it'll be a new form displayed. So my question is can I do something about this? Can I make sure the form with the errors can be used along with the HttpResponseRedirect? Or maybe some other way. template <form class="form" autocomplete="off" novalidate="novalidate" action="{% url 'Eapp:create_user' %}" method="POST"> <input type="hidden" name="next" value="{{request.path}}" /> {% csrf_token %} {% include 'Eapp/user_create-template.html' %} <button type="submit" class="btn btn-primary">Submit</button> </form> create_user view def create_user(request): form = CreateUserForm(request.POST or None, request.FILES or None) if request.method == 'POST': if form.is_valid(): user = form.save(commit=False) user.save() user = authenticate(username=user.email, password=user.password) else: print('error') #Else reuse the form. next = request.POST.get('next', '/') return HttpResponseRedirect(next) my index def index(request): context = {} context['create_user_form'] = CreateUserForm() return render(request, 'index.html', context) -
Django - int() argument must be a string, a bytes-like object or a number, not 'Association'
I want to register an admin with a dropdown-list you can choose association and create a relation between Administrator and Association. Is there something i'm missing? Still a newbie so appreciate your help, folks! admin\models.py class Administrator(AbstractUser): ... association= models.ForeignKey(Association) class Meta: db_table = 'Administrator' member\models.py from pl.admin.models import Administrator class Association(models.Model): asoc_name = models.CharField(max_length=100) member_no = models.ForeignKey(Member) class Meta: db_table = 'Association' forms.py class SignUpForm(forms.ModelForm): ... association = forms.ModelChoiceField(queryset=Association.objects.all()) ... class Meta: model = Administrator fields = [..., 'association', ...] views.py def signup(request): if request.method == 'POST': form = SignUpForm(request.POST) if not form.is_valid(): return render(request, 'admin/signup.html', {'form': form}) else: ... asoc_pk = form.cleaned_data.get('association') asoc = Association.objects.get(pk=asoc_pk) ... Administrator.objects.create_user(... association=asoc, ...) user = authenticate(... association=asoc, ...) return redirect('/') else: return render(request, 'admin/signup.html', {'form': SignUpForm()}) -
Django Form Field not showing up
I just started learning Django and for this project I'm following the "Tango with Django" tutorial book. I have a problem with the input field of a form not showing up, while the button seems to be rendered fine. Here's my code: models.py [...] class Idea(models.Model): keyword = models.ForeignKey(Keyword) word = models.CharField(max_length=120) count = models.IntegerField(default=1) def __str__(self): return self.word forms.py [...] class Meta: model = Keyword fields = ('name',) class IdeaForm(forms.ModelForm): word = forms.CharField(max_length=120) count = forms.IntegerField(widget=forms.HiddenInput(), initial=1) class Meta: model = Idea fields = ('word',) exclude = ('keyword',) views.py [...] def keyword_detail(request, keyword_name_slug): form = IdeaForm() context_dict = {} try: keyword = Keyword.objects.get(slug=keyword_name_slug) ideas = Idea.objects.filter(keyword=keyword) context_dict['keyword'] = keyword context_dict['ideas'] = ideas except Keyword.DoesNotExist: context_dict['keyword'] = None context_dict['ideas'] = None if request.method == 'POST': form = IdeaForm(request.POST) if form.is_valid(): idea = form.save(commit=False) idea.keyword = keyword idea.count = 1 idea.save() return keyword_detail(request, keyword_name_slug) else: print(form.errors) context_dict['form'] = form return render(request, 'openminds/keyword.html', context_dict) keyword.html [...] <h3>Add a new Idea</h3> <div> <form id="idea_form" method="post" action="">{% csrf_token %} {% for hidden in forms.hidden_fields %} {{ hidden }} {% endfor %} {% for field in forms.visible_fields %} {{ field.errors }} {{ field }} {% endfor %} <input type="submit" name="submit" value="Add Idea" /> </form> </div> -
How to store long dictionary in Django using postgresql
I am trying to add list of airport codes and their name in Django postgresql database using models. My target is that airport name shows up when someone types airport code like you see of airlines' websites. I have made a dictionary like this airports = {"JFK": 'New York', "AAE": 'Annabah', "AAF": 'Apalachicola', "AAG": 'Arapoti', "AAH": 'Aachen', "AAI": 'Arraias', "AAJ": 'Awaradam' "...": '........' } So when someone types JFK code, the airport name New York will show up. I understand I'll have to use ajax and jquery for that. But first I have to save the dictionary of hundreds of airports in my postgresql database. Any help what is the best way to save this dictionary and I dont want to type them by hand one by one because they are hundreds. -
Django form shows as unbound even if instantiated with model instance
I am having difficulties with using the admittedly pretty snazzy properties of the Django form and ModelForm classes. In particular I am having trouble determining if a form instance has data associated when it is instantiated with a model instance. First here's a look at a pretty simple set of forms in forms.py from django.forms import ModelForm from .models import ItemCoeff, MonthCoeff class MonthForm(ModelForm): """A class that defines an HTML form that will be constructed for interfacing with the Monthly Coefficients""" title='Set Month Coefficient' class Meta: model=MonthCoeff fields = ['first_of_month', 'product_category', 'month_coeff', 'notes'] class ItemForm(ModelForm): """ A class that defines a Django HTML form to be constructed for interfacing with the ItemCoeff model. """ title='Set Item Coefficient' class Meta: model=ItemCoeff fields = ['item_num','item_name','item_coeff','notes'] Next we get to the part of views.py where I use the form def set_month_form(request, myid=False): if myid: mcoeff=MonthCoeff.objects.get(id=myid) form=MonthForm(instance = mcoeff) categories = False else: form=MonthForm() categories=list(MonthCoeff.objects.values('product_category').distinct()) import pdb; pdb.set_trace() return render(request,'coeffs/forms/django_form.html',{'form':form, 'user': request.user}) And when I am rendering the form in my template I am trying to use the is_bound property to set the caption of my submit button, like so: {% if form.is_bound %} <button type="submit" name="button">Update</button> {% else %} <button class="btn btn-lg btn-primary" … -
No Reverse Match when calling url from html file - Django
So I am trying to call my url by using the following in one of my html templates - <a href="{% url 'socialx:index' %}"> My apps urls.py file looks like this - from django.conf.urls import include, url from django.contrib import admin urlpatterns = [ url(r'^socialx/', include('socialx.urls')), url(r'^admin/', include(admin.site.urls)), ] And the root urls.py file is like this - from django.conf.urls import include, url from django.contrib import admin urlpatterns = [ url(r'^socialx/', include('socialx.urls'), name='socialx'), url(r'^admin/', include(admin.site.urls)), ] When navigating to the app via browser I get the following error - NoReverseMatch at /socialx/ 'socialx' is not a registered namespace -
Multiple one-to-many relations in Django
I need to express multiple one-to-many relations in Django. That is, given several different models, I need each of these to have a one-to-many relation with a single table. Logically, the relation belongs to the model "owning" the one-to-many relation, but Django forces me to use a many-to-one relation on the target table, instead of a one-to-many relation on the source table. Here's what I wish I could do: class Sink(models.Model): name = models.CharField('name', max_length=24) class A(models.Model): name = models.CharField('name', max_length=24) sink = models.ManyToOneField(Sink) class B(models.Model): name = models.CharField('name', max_length=24) sink = models.ManyToOneField(Sink) but ManyToOneField doesn't exist. Instead, I'm supposed to use ForeignKey for each one-to-many field, like: class Sink(models.Model): name = models.CharField('name', max_length=24) a = models.ForeignKey(A) b = models.ForeignKey(B) class A(models.Model): name = models.CharField('name', max_length=24) class B(models.Model): name = models.CharField('name', max_length=24) which is logically just wrong, since there is never a case where I want both Sink.a and Sink.b to be non-null. If ManyToManyField allowed me to specify that it's not really many-to-many, I could do that, but it doesn't seem to allow that. What's the right way to do something like this? -
Django Query Sort by Value of String
I have a model that allows my client to create menus for his restaurant. Everything works great except I would like to set the explicit ordering by the string value of a model. For instance; he is creating sections like Salads, Pastas, Pizzas etc.. but they are displayed through the template in the order they are added to the system. How can I add a sort to my query that I can set the order manually? Below is my current snippet. I am using Django 1.10.5, Wagtail 1.9, Python 3.5x Snippet @register.inclusion_tag('tags/_lunch-menu-list.html', takes_context=True) def lunch_products(context): sections = Section.objects.all().prefetch_related('product').filter(product__lunch_menu=True).distinct() return { 'sections': sections, 'request': context['request'], } -
Can I get django-oscar to work under Python 3?
I am working with Python 3.6.0, Django 1.10.6, and Oscar version 1.4.0 final. I've seen similar-looking error messages discussed and reported solved by certain solutions (e.g. updating what was "still" an old-time autogenerated wsgi.py), or adding import django and django.setup() almost near the top (i.e. before SECRET_KEY and INSTALLED_APPS, moved up near the top). I've found closer matches to the error message on Github, where for the purposes of Raven people have been given the all-clear to delete standard user or authentication modules from their project. However, I have not found a place where someone reports the error and there is a solution other than an all-clear to delete a standard Django app from an unrelated Django-based project. The specific error message and trace does not shout out to me what line is at issue beyond suspicions it is being triggered by inclusion of 'django.contrib.contenttypes' in INSTALLED_APPS. The trace I get when I try to run it is: (store-env) ~/store $ python manage.py migrate Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/Users/christos/store-env/lib/python3.6/site-packages/django/core/management/__init__.py", line 367, in execute_from_command_line utility.execute() File "/Users/christos/store-env/lib/python3.6/site-packages/django/core/management/__init__.py", line 359, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/christos/store-env/lib/python3.6/site-packages/django/core/management/base.py", line 294, in run_from_argv self.execute(*args, **cmd_options) File "/Users/christos/store-env/lib/python3.6/site-packages/django/core/management/base.py", … -
Using filters with list_routes in drf
Is there a way to use filters for @list_route the same way you use them for the root ViewSet in DRF? I have a model that I have configured filters for and a detail route that I cannot: class ListingViewSet(viewsets.ModelViewSet): # disable listing after 5 flags queryset = Listing.objects.all() serializer_class = ListingSerializer filter_backends = (DjangoFilterBackend, OrderingFilter, SearchFilter) permission_classes = (ListingOwnerCanEdit,) filter_class = ListingFilter @list_route() def homepage(self, request): queryset = Listing.objects.filter(flags__lt=5, closed=False) ### Doesn't work # filter_backends = (DjangoFilterBackend, OrderingFilter, SearchFilter) # permission_classes = (ListingOwnerCanEdit,) # filter_class = ListingFilter # ordering_filter = OrderingFilter() # ordering_fields = ('price', 'views') # search_fields = ('title', 'description') serializer = ListingSerializer(queryset, many=True, context=self.get_serializer_context()) return Response(serializer.data) And ListingFilter is: class ListingFilter(django_filters.rest_framework.FilterSet): min_price = django_filters.NumberFilter(name="price", lookup_expr='gte') max_price = django_filters.NumberFilter(name="price", lookup_expr='lte') author_pk = django_filters.CharFilter(name='author_pk') class Meta: model = Listing fields = ['price_type', 'sale_type', 'category__name', 'min_price', 'max_price', 'description', 'title', 'listing_date', 'views', 'number_of_inquiries', 'author_pk', 'closed', 'closing_date'] Is there a way to use ListingFilter with the homepage list route? -
Django - Cannot assign "'1'": "Administrator.association" must be a "Association" instance
I want to register an admin with a dropdown-list you can choose association and create a relation between Administrator and Association. Is there something i'm missing? Still a newbie so appreciate your help, folks! admin\models.py class Administrator(AbstractUser): ... association= models.ForeignKey(Association) class Meta: db_table = 'Administrator' member\models.py from pl.admin.models import Administrator class Association(models.Model): asoc_name = models.CharField(max_length=100) member_no = models.ForeignKey(Member) class Meta: db_table = 'Association' forms.py class SignUpForm(forms.ModelForm): ... association_choices = [(i['pk'], i['asoc_name']) for i in Association.objects.values('asoc_name', 'pk')] association = forms.ChoiceField(choices=association_choices, widget=forms.Select(attrs={'class': 'form-control'}), required=True) ... class Meta: model = Administrator fields = [..., 'association', ...] views.py def signup(request): if request.method == 'POST': form = SignUpForm(request.POST) if not form.is_valid(): return render(request, 'admin/signup.html', {'form': form}) else: ... asoc_pk = form.cleaned_data.get('association') asoc = Association.objects.get(pk=asoc_pk) ... Administrator.objects.create_user(... association=asoc, ...) user = authenticate(... association=asoc, ...) return redirect('/') else: return render(request, 'admin/signup.html', {'form': SignUpForm()}) -
Authenticating static media for users authenticated within Django App
I have a Django 1.10 install hosting a large app through mod_wsgi and I wanted to secure a series of static pages so that only people who are currently authenticated to the Django app have access. I found this documentation that enabled me to get BASIC authentication working, but it failed to authenticate with my custom authentication middleware. More importantly, I didn't feel it should be necessary to have people authenticate a second time on the server, a fundamental flaw of using BASIC authentication techniques. Eventually I discovered a method to do exactly what I want, however I have a few questions about my approach. To be clear, my question is not "How Do I Make This Work" (because it already 'works'), but more "Is This Wise?". In my Apache Config, I added the following directive at the bottom of my Django's VirtualHost: Alias /secure /var/www/secure <Location "/secure"> WSGIAccessScript /path/to/wsgi.py </Location> And within the wsgi script I added the following code: import sys import django.db import django.core.handlers.wsgi def allow_access(environ, host): django.db.reset_queries() #Question 1 environ["wsgi.input"]=sys.stdin Handler=django.core.handlers.wsgi.WSGIHandler() Request=Handler.request_class(environ) #Question 2 for middlewareFunction in Handler._request_middleware: middlewareFunction(Request) return_value=False if Request.user.is_authenticated: return_value=True django.db.close_old_connections() return return_value Question 1: I have to manually set "wsgi.input" otherwise Django …