Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Stripe - 'exp_month' parameter should be an integer (instead, is 02 ) in Django View
I am in the beginning stages of building a checkout payment form using Stripe. I am using the jquery.payment library for formatting my month and year https://github.com/stripe/jquery.payment. I created an exp input field to collect the data, but in order to get the Stripe required exp_month and exp_year fields I created them as new variables and took the value of my exp field and sliced the values I needed, then passed them to my view. The correct values are being passed to my view but when it hits stripe.Token.create I get the stripe.error.CardError: Request req_A16AvRkITlz3Oi: The 'exp_month' parameter should be an integer (instead, is 02 ). error in console. Side note: This form worked perfectly when I had a field specific for exp_month and exp_year but how much fun is that? :) Below is my code for review: ajax var fields = { number: 'null', cvc: 'null', exp: 'null', exp_month: 'null', exp_year: 'null' }; $('#plaqueFormBTN').click(function (e) { e.preventDefault(); fields.number = $('#id_number').val(); fields.exp = $('#id_exp').val(); fields.cvc = $('#id_cvc').val(); $('#loader').show(); var exp_month = fields.exp.slice(0, 3); var exp_year = fields.exp.slice(5); console.log(exp_month); console.log(exp_year); $.ajax({ type: 'POST', data: { csrfmiddlewaretoken: getCookie('csrftoken'), number: fields.number, exp: fields.exp, exp_month: exp_month, exp_year: exp_year, cvc: fields.cvc }, url: $('#plaqueForm').attr('action'), cache: … -
How can run a function at a specific time in Django?
I have the function def restart: """ The function restart the current points number """ self.hour_points = 0 Now I want to execute this function in each hour at minute 0 and second 0 def restart_hourly: """ This function is call in each hour and call self.restart """ self.restart NOTE: I want to execute automatic in each hour e.g. : 10:00:00 -> Execute 11:00:00 -> Execute 12:00:00 -> Execute 14:30:00 -> Don't Execute NOTE 2: The time is the server time -
Django specifying password reset email subject
I have setup my django application to use the built in auth.views to reset password. The problem is that this is what the message looks like: Subject: Password reset on 127.0.0.1:8001 You're receiving this email because you requested a password reset for your user account at 127.0.0.1:8001. Please go to the following page and choose a new password: http://127.0.0.1:8001/accounts/reset/MQ/4j3-d83f7cdb7f0203afe85e/ Your username, in case you've forgotten: myuser Thanks for using our site! The 127.0.0.1:8001 team It seems like it's pulling localhost from the gunicorn deployment. I have it set up so that nginx routes the domain @port 80 to localhost at port 8001. How do I go about changing this to have "http://mydomain/accounts/reset...." instead? -
Ignore a request in Django
What is the most efficient method to have Django ignore a request at the View layer (don't return anything) and drop the connection (don't block future requests)? -
Accessing excluded fields in Django form's clean method
Imagine we have a Django ORM model, let's call it MyModel, and it's respective form, let's call it MyForm. Also, let's imagine that there's a field in MyModel which has been excluded from MyForm. Let's call this field excluded_field. The question is, how do we tackle the situation when we have to use excluded_field during the validation of the form (meaning, the form's clean method)? I like encapsulating user input validation and corresponding customized error messages in form's clean and field_name_clean method as suggested by doc, because moving all business logic to forms makes my views elegant and simple and the entire code DRY. Just to be specific, consider the following code: Model: class MyModel(models.Model): # ...some fields excluded_field = models.CharField() class Meta: managed = False db_table = 'my_model' And the respective form: class MyForm(forms.ModelForm): def clean(self): # how do I access excluded_field here ? One might ask why I exclude this field from the form ? Well, it's because this field's value is generated programmatically, and the user does not - and should not - know anything about its value. So, the question is, can we access excluded fields in form's clean method if we need it for user … -
Django foreign key in template
On the home page of the site I am building I am trying to pull in data from two apps, Blog and Portfolio. Blog is working great, but Portfolio is not showing up. I assume it's because I have foreign keys in my model. I chose this project structure because the site is predominantly a blog, but I want the home page to show some recent portfolio work on the side bar. As you can see, the index.html template doesn't need all of the info from the Portfolio.portfolio model, hence I tried to import over only some of the fields. How do I include the foreign key relationship in my template so that the data can traverse the apps? Template - index.html {% for i in IndexPortfolio %} <div class="col-xs-12 col-sm-6 thumb"> <a class="thumbnail" href="{{ IndexPortfolio.get_absolute_url }}"> <img class="img-responsive" src="{{ IndexPortfolio.cover_image.url }}" alt=""> <p>{{ portfolio.title }}/{{ portfolio.client_name }}</p> </a> </div> {% endfor %} Project structure mysite/ blog/ templates/ blog/ blog_list.html blog_detail.html index.html bio.html resume.html models.py views.py portfolio/ templates/ portfolio_list.html portfolio_detail.html models.py views.py blog/models.py from django.db import models from datetime import date from django.urls import reverse # Used to generate URLs by reversing the URL patterns class IndexPortfolio(models.Model): title = models.ForeignKey('portfolio.Portfolio', … -
How can I extract parts of a Django Postgres DateRangeField
I would appreciate some help. I can't get my head around this. I want to use the Django Postgres DateRangeField for a model in my app. It will hold two dates: a from-date and a to-date like in a booking system. from django.contrib.postgres.fields import DateRangeField class Booking(models.Model) from_to = DateRangeField() All works fine and nicely. I can play around with it in the Admin. In order to confirm the booking, I'd like to extract the 2 dates in variables again, and that's where I hit a wall :) The printed object looks a lot like a tuple to me, with from-date and to-date and the bounds-definition DateRange(datetime.date(2017, 2, 1), datetime.date(2017, 3, 31), '[)') however, any attempt to extract one of the dates fails. fromdate = self.from_to(0) 'DateRange' object is not callable I'm sure it's simple, however, there is no documentation about that (at least not any I could find) Your help is more than appreciated. -
Django posting images
I started building a blog/website with django and I'm having some problems with uploading pictures to photos. I'm unsure whether to create a separate class of pictures in models or just create a textfield and then use the url in html. When I do the latter, images show up as blue boxes with ?s in it. When I tried out the first, I had to upload photos from the admin login page and I couldn't display the photos once again. Can anyone guide me on how to approach this issue? -
Youtube Data API options request parameter
I want to use Search API method of YouTube Data API but I am not able to understand the request parameters correctly. Below is the snippet I have written to get a part:snippet for "In the End" song but I am not getting correct response. def getVideos(request): youtube = build(YOUTUBE_API_SERVICE_NAME,YOUTUBE_API_VERSION,developerKey=DEVELOPER_KEY,credentials=credentials) videos = [] search_response = youtube.search().list(q="In the end",part="snippet",maxResults = 1).execute() return JsonResponse(search_response,safe=False) Response from service is this Object { nextPageToken: "CAEQAA", kind: "youtube#searchListResponse", items: Array[1], regionCode: "IN", etag: ""GM4ZnRh2gk1X1BLWgHklTm-3cgQ/iAA4sb…", pageInfo: Object } I am expecting to get kind = "youtube#video" Actuaky response from service is this, when I am passing my request in YoutubeApi reference site. { "kind": "youtube#searchListResponse", "etag": "\"GM4ZnRh2gk1X1BLWgHklTm-3cgQ/U9emDJOo6YZym_1_ROXkALusG9E\"", "nextPageToken": "CAUQAA", "regionCode": "IN", "pageInfo": { "totalResults": 1000000, "resultsPerPage": 5 }, "items": [ { "kind": "youtube#searchResult", "etag": "\"GM4ZnRh2gk1X1BLWgHklTm-3cgQ/FFkgBGbwrdk_aCU9r0FqFX_FHNY\"", "id": { "kind": "youtube#video", "videoId": "eVTXPUF4Oz4" }, "snippet": { "publishedAt": "2009-10-26T18:31:10.000Z", "channelId": "UCZU9T1ceaOgwfLRq7OKFU4Q", "title": "In The End (Official Video) - Linkin Park", "description": "Linkin Park's \"In The End\" off of the album HYBRID THEORY. Directed by Joe Hahn and Nathan \"Karma\" Cox. Watch the lyric video: ...", "thumbnails": { "default": { "url": "https://i.ytimg.com/vi/eVTXPUF4Oz4/default.jpg", "width": 120, "height": 90 }, "medium": { "url": "https://i.ytimg.com/vi/eVTXPUF4Oz4/mqdefault.jpg", "width": 320, "height": 180 }, "high": { "url": "https://i.ytimg.com/vi/eVTXPUF4Oz4/hqdefault.jpg", … -
How to assign default value to django form with variable?
This was my view (I use django-cart) def product_update(request, id): product = Product.objects.get(id=id) cart = Cart(request) quantity = request.POST['quantity'] unit_price = product.price cart.update(product, quantity, unit_price) return HttpResponseRedirect('%s?status_message=%s' % (reverse('get_cart'), _('Product updated!'))) and my form in template <form action="{% url 'product_update' item.product.id %}" method="POST" class="update-quantity"> {% csrf_token %} <div class="col-xs-3 col-sm-2"> <input type="number" class="form-control input-sm" id='quantity' name="quantity" value="{{ item.quantity }}"> </div> <div class="col-xs-1"> <button type="submit" class="btn btn-link btn-xs update-product"> <span class="glyphicon glyphicon-refresh"> </span> </button> </div> </form> I changed it to django Form class QuantityUpdateForm(forms.Form): quantity = forms.IntegerField( min_value=1, max_value=50) so now I have view def product_update(request, id): form = QuantityUpdateForm(request.POST) if form.is_valid(): product = Product.objects.get(id=id) cart = Cart(request) quantity = request.POST['quantity'] unit_price = product.price cart.update(product, quantity, unit_price) return HttpResponseRedirect('%s?status_message=%s' % (reverse('get_cart'), _('Product updated!'))) and form <form action="{% url 'product_update' item.product.id %}" method="POST" class="update-product"> {% csrf_token %} <div class="form-group col-xs-3 col-sm-2"> {{ form.as_p }} </div> <div class="col-xs-1"> <button type="submit" class="btn btn-link btn-xs update-product"> <span class="glyphicon glyphicon-refresh"> </span> </button> </div> </form> input value was assigned with 'value={{item.quantity}}'. How can I assign value of input to {{item.quantity}} now? -
Django import-export with preview Update creates new entry
I'm trying to update existing entries with new values using Django import-export. My model Book is below: author = models.ForeignKey(Author) book_no = models.CharField(max_length=35, null=True, blank=True) published_date = models.DateField(null=True, blank=True) document = S3PrivateFileField(upload_to='/') As per the documentation, I have declared import_id_fields = ('author', 'book',) in resources file So with author and book, I will be updating other published_date and book_no. In the preview after uploading excel file, I get in each row as "Update" but after clicking "Confirm Import" it creates a new entry. I tried to make author and book as a unique field, but I get an error like "Unique constraint failed....". Any suggestion would really help!! -
Django admin: how to show create button in ManyToMany field?
I've already read a lot of answer, and I've done everything but the "Create" button doesn't appear: @python_2_unicode_compatible class TextTranslated(models.Model): text = models.CharField(max_length=200) def __str__(self): return self.text @python_2_unicode_compatible class QuestionTextTranslated(models.Model): question = models.ForeignKey('Question') text_translated = models.ForeignKey(TextTranslated) def __str__(self): return u'{} - {}'.format(str(self.question), str(self.text_translated)) @python_2_unicode_compatible class Question(BaseModel): class Meta: app_label = 'app' description = models.CharField(max_length=200) translations = models.ManyToManyField(TextTranslated, blank=True, through='QuestionTextTranslated', symmetrical=False) And in the admin.py i've done this: class QuestionTextTranslatedInlineAdmin(admin.StackedInline): model = Question.translations.through extra = 0 verbose_name = _(u"Question translated") verbose_name_plural = _(u"Questions translated") class QuestionAdmin(admin.ModelAdmin): fieldsets = ( (None, { 'fields': (('description',), ) }), ) inlines = (QuestionTextTranslatedInlineAdmin,) admin.site.register(QuestionTextTranslated) admin.site.register(Question, QuestionAdmin) Almost all solutions I've found talk about declaring QuestionTextTranslated in the admin.py file, and this is what I've done but no success. -
OSError: [Errno 22] Invalid argument, running Django on a shared hosting
I'm migrating my web to another server, and I'm setting up everything for django the work. I could solve lots of problems but this one beat me. I have no idea what can cause it. This is the log: Traceback (most recent call last): File "/home/usuario/public_html/cgi-bin/dispatch.cgi", line 24, in <module> runfastcgi(method="threaded", daemonize="false") File "/home/usuario/test/lib/python3.4/site-packages/django/core/servers/fastcgi.py", line 182, in runfastcgi WSGIServer(get_internal_wsgi_application(), **wsgi_opts).run() File "/home/usuario/test/lib/python3.4/site-packages/flup/server/fcgi.py", line 114, in run ret = ThreadedServer.run(self, sock) File "/home/usuario/test/lib/python3.4/site-packages/flup/server/threadedserver.py", line 85, in run clientSock, addr = sock.accept() File "/home/usuario/test/lib/python3.4/socket.py", line 184, in accept fd, addr = self._accept() OSError: [Errno 22] Invalid argument .htaccess: AddHandler dispatch.cgi Options +FollowSymLinks RewriteEngine On RewriteBase / RewriteCond %{REQUEST_URI} !(cgi-bin/dispatch.cgi) RewriteRule ^(.*)$ cgi-bin/dispatch.cgi/$1 [L] dispatch.cgi: #!/home/usuario/test/bin/python3.4m import sys, os import traceback sys.path += ['/home/usuario/app-test'] os.environ['LD_LIBRARY_PATH'] = '/home/usuario/test/lib' #Switch to new python PYTHON_EXE = '/home/usuario/test/bin/python3.4' sys.path.insert(0,'home/usuario/test/bin') sys.path.insert(0,'home/usuario/test/lib/python3.4/site-packages/django') sys.path.insert(0,'home/usuario/test/lib/python3.4/site-packages/flup') sys.path.insert(0,'home/usuario/test/lib/python3.4/site-packages') os.environ['DJANGO_SETTINGS_MODULE'] = "app.settings" try: from django.core.servers.fastcgi import runfastcgi runfastcgi(method="threaded", daemonize="false") except: traceback.print_exc(file=open('/home/usuario/public_html/log.txt','w')) It's important to point out I dont have ssh access on the server, so if anyone comes up with a solution it would have to be without the need of ssh. Is it a configuration problem ? Or is it server sided ? And if it is, is there a workaround ? -
How to create custom model fields in django, and how does it works
I am new to django development , i knew and always used defaults model fields provided by django, but while reading a book i came across below code and came to knew django has custom model field, can somebody let me know what below code does. Thanks for your response. Models.py class Module(models.Model): course = models.ForeignKey(Course, related_name='modules') title = models.CharField(max_length=200) description = models.TextField(blank=True) order = OrderField(blank=True, for_fields=['course']) fields.py class OrderField(models.PositiveIntegerField): def __init__(self, for_fields=None, *args, **kwargs): self.for_fields = for_fields super(OrderField, self).__init__(*args, **kwargs) def pre_save(self, model_instance, add): if getattr(model_instance, self.attname) is None: # no current value try: qs = self.model.objects.all() if self.for_fields: query = {field: getattr(model_instance, field) for field in self.for_fields} qs = qs.filter(**query) last_item = qs.latest(self.attname) value = last_item.order + 1 except ObjectDoesNotExist: value = 0 setattr(model_instance, self.attname, value) return value else: return super(OrderField,self).pre_save(model_instance, add) -
Selecting additional values after annotate in Django
I have a model, IndividualResult, for an athlete's performance during a competition. To select the fastest time for each athlete I used: qs.values('athlete').annotate(pb=Min('time')) This returns only the athlete_id and its fastest time. How can I access the other fields in my IndividualResult model? -
Bootstrap rendering different on server
I'm making a Django application using Bootstrap for styling, and I have an inconsistency between my computer and the server regarding how the page renders. Local: Server: The upper black stripe is a navbar. Code: <nav class="navbar navbar-inverse navbar-fixed-top"> <div class="container-fluid"> <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="#">OSV</a> </div> <div id="navbar" class="navbar-collapse collapse"> <ul class="nav navbar-nav navbar-right"> <li><a href="#">Realizar Busqueda</a></li> </ul> </div> </div> </nav> <div class="container-fluid"> <div class="container"> <div class="row"> <div class="col-md-offset-4 col-md-4"> <form action="{% url 'buscador_ingresar_calle' %}" method="get"> {{ form.non_field_errors }} {% for field in form %} <div class="form-group"> {{ field.errors }} <label for="{{ field.id_for_label }}">{{ field.label }}</label> {{ field }} </div> {% endfor %} <button type="submit" class="btn btn-default btn-blue btn-lg btn-block">Enviar</button> </form> </div> </div> </div> </div> -
Django-registration-redux restrict registration to edu emails
Hello I'm trying to restrict my users to have edu emails. I'm using django 1.10 on python 2.7 and Django-registration-redux. I've seen answers like this one but it requires editing the package directly. This seems like a bad idea? I'm using django-custom-user to use the email as a username, and i have extended the user model like so: models.py class CustomEmailUser(AbstractEmailUser): ''' These are inherited from AbstractEmailUser: id = models.AutoField(primary_key=True) #this is always present, its a django default email = models.CharField(unique=True, max_length=255) password = models.CharField(max_length=128) last_login = models.DateTimeField(blank=True, null=True) is_superuser = models.BooleanField() is_staff = models.BooleanField() is_active = models.BooleanField() date_joined = models.DateTimeField() ''' first_name = models.CharField(max_length=50, default='') last_name = models.CharField(max_length=50, default='') All the forms are taken care of by these two packages (which is great!) but i'd like to restrict the email domains to .edu and I'm unsure of how to do this without editing the packages directly. Any suggestions? Thanks! -
Get gmail email using django allAuth
I'm new to that Auth things so I have a problem. I've connected allAuth to my django application, with "socialaccount.providers.google", I created google application, authorized through it and now I need to request my emails from Gmail, and I really can't understand where to put all those secret keys and tokens in the request. P.S. Sorry for such a dumb question. -
Django "with" in tamplate
I am having touble with a tamplate that hits the data too many times. I know that I can use "with" fot that not to happen, but I do not know how to use "with". Here is my code in the tamplate <table class="calendar1"> <tr> {% for month, game in one_month %} {% for day in month %} <td> {{ day }} <br /> {% if forloop.parentloop.counter == 1 and day == 1 %}New Year's Day{% endif %} {% if forloop.parentloop.first and day == 16 %}Martin Luther King, Jr. Day Observance.{% endif %} {% if forloop.parentloop.counter == 1 or forloop.parentloop.counter == 11 or forloop.parentloop.counter == 12 %}No game today{% endif %} {% if forloop.parentloop.counter == 2 and day < 25 %}No game today{% endif %} {% if forloop.parentloop.counter == 10 and day > 1 %}No game today{% endif %} {% if forloop.parentloop.counter == 2 %} {% if day == 14 %}Pitchers and catchers report & physicals{% endif %} {% if day == 15 %}Pitchers and catchers first workout{% endif %} {% if day == 17 %}Position players report & physicals{% endif %} {% if day == 18 %}First full squad workout{% endif %} {% for game in mlbgames %} {% … -
Haystack Elasticsearch filtering dates using lte
Using haystack + elasticsearch I found some problems with lte an dates. It works as lt. I am having no problems with gte. This is elasticsearch generated query: "query": {"query_string": {"query": "(date_added:({* TO \"2017-01-25T00:00:00+01:00\"}) AND date_added:([\"2017-01-25T00:00:00+01:00\" TO *]))" One option might be using range but not always I am using closed range, just one of the boundaries. -
Configure POST endpoint to respond only to cron.yaml requests
I have a Django app running on Elastic Beanstalk and want to run a job every night (reindex of search engine). According to AWS docs I can use cron.yaml to automatically make POST requests to my app at the right time, and configure my app to respond appropriately. How can I ensure my app only responds to the auto-generated POST requests, and not random requests to the same URL? -
Form Validation Reversed
Django Version 1.10.5 I can't find this answer in the documentation or the code source. Using the example form below I am expecting my form validation on submit to run in the order of which I have defined. So validate_status, validate_employee_id, etc... would run in that order. However when submitting the form it would appear that the validators are running in a reversed order. Where validators.RegexValidator, validators.MinLengthValidator, etc... would run. Is this expected? class FormLogin(forms.Form): # Employee ID employee_id = forms.CharField( label=_('employeeId'), required=True, widget=forms.TextInput( attrs={ 'id': 'employee_id', 'placeholder': _('employeeId'), 'class': 'form-control' } ), validators=[ validate_status, validate_employee_id, validators.MaxLengthValidator(20), validators.MinLengthValidator(1), validators.RegexValidator('^[1-9][0-9]*$', _('validatorStartsWithZero')) ] ) # Password password = forms.CharField( label=_('password'), required=True, widget=forms.PasswordInput( attrs={ 'id': 'password', 'placeholder': _('password'), 'class': 'form-control' } ), validators=[ validators.RegexValidator('^[^ \\\' ]+$', _('validatorPasswordInvalid')), validators.MaxLengthValidator(128), validators.MinLengthValidator(5) ] ) -
Can i edit the tags from a Model field?
myapp/models.py class BookDetails(models.Model): user = models.ForeignKey(User) book_language = models.CharField(max_length=10, default='English') book_title = models.CharField(max_length=100, blank=False) book_author = models.CharField(max_length=100, blank=False) myapp/views.py class BookDetailsForm(forms.ModelForm): class Meta: model = BookDetails fields = ('book_language', 'book_title', 'book_author',) so the html generated is : <tr><th><label for="id_book_language">Book language:</label></th><td><input id="id_book_language" maxlength="10" name="book_language" type="text" value="English" required /></td></tr> <tr><th><label for="id_book_title">Book title:</label></th><td><input id="id_book_title" maxlength="100" name="book_title" type="text" required /></td></tr> <tr><th><label for="id_book_author">Book author:</label></th><td><input id="id_book_author" maxlength="100" name="book_author" type="text" required /></td></tr> desired HTML <tr><th></th><td><input id="id_book_language" maxlength="10" name="book_language" type="text" value="English" placeholder='language'required /></td></tr> <tr><th></th><td><input id="id_book_title" maxlength="100" name="book_title" type="text" placeholder='title' required /></td></tr> <tr><th></th><td><input id="id_book_author" maxlength="100" name="book_author" type="text" placeholder='Author' required /></td></tr> Label tag removed and placeholder tag added. I know we can do it by custom widget as mentioned here. I want to just edit the existing model parameter and add these tags. Is it possible? -
Filtering Haystack results
I am trying to build a full text search for Recipes. I have specified the ingredient as the document field. Everything is working fine but i also want to put on some more constraints to the Search Results. For example i want to perform a full text search on field ingredients but want the models to be searched only those matching the category specified. I looked through the docs and was not able to find any Query parameters that would need to be set nor I found any changes I have to do to the Index. I am using elasticsearch in the backed for Indexing, if that matters. class ArticleIndex(indexes.SearchIndex,indexes.Indexable): text = indexes.CharField(document=True,model_attr='ingredients') title = indexes.CharField(model_attr='title') category = indexes.CharField(model_attr='category') image_link = indexes.CharField(model_attr='image_link') publication_date = indexes.DateTimeField(model_attr='publication_date') def get_model(self): return Article -
Serving static files of a django site with gunicorn and apache
I've written a small django site. It works wuite well on my webspace. There I run the app with gunicorn test_site.wsgi:application --timeout 120 -R --log-level "debug" --error-logfile ~/log/test_prod.gunicorn.log --reload --bind 127.0.0.1:61955 The static files are served with an an apache webserver and my .htaccess looks like this: RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-f RewriteBase / RewriteRule ^(.*)$ http://127.0.0.1:61955/$1 [P] RequestHeader set X-Forwarded-Proto https env=HTTPS Everything works quite perfectly. Now I'm trying to run the whole thing on a local machine. The code is completely unchanged, the gunicorn line also. But I tried to create a real virtual host configuration in sites-enabled to replace the .htaccess file. This is my current sites-enabled/test.conf file (I had to remove the RewriteBase line because it is not allowed in a virtual host): <VirtualHost *:80> ServerName test.localhost DocumentRoot "/var/www/html/test/" RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^(.*)$ http://127.0.0.1:61955/$1 [P] </VirtualHost> But the conditional rewrite does not quite work. When I open up "test.localhost" the django site is shown, but without static files like main.css and the like. A look in the gunicorn log tells me, that those static requests are also forwarded to the gunicorn instance instead of being served by the apache server. gunicorn log: [2017-01-28 …