Is it possible to configure Gulp Livereload for Django?
Asked Answered
K

6

8

I would like to use gulp-liveReload with Django, is it possible? I have read that there is an alternative for Grunt, but I would prefer work with Gulp, it is easier for me.

Thanks,

Krause answered 28/9, 2014 at 13:31 Comment(0)
R
5

I wrote up how to do it in a recent blog post here:

http://www.revsys.com/blog/2014/oct/21/ultimate-front-end-development-setup/

Basically you just need to write gulp tasks that watch what files you want to trigger livereloads, so for me that's templates:

/* Trigger a live reload on any Django template changes */
gulp.watch('**/templates/**').on('change', livereload.changed);

But you could also trigger it on models.py, views.py, or anything else you want really.

Radmilla answered 15/1, 2015 at 22:46 Comment(2)
I'm using this and it works fine for CSS file changes, etc., but not templates. The only way it works with templates is if I touch or make changes to a .py file and then change a template. Did you run into this problem or is it working as-is for you somehow?Venereal
Hi Mike, apologies I had a typo in the above it should be '/templates/' not what I originally had which is '*/templates/'. Hope that helps!Radmilla
O
1

have you try this django-livereload ?

Olwena answered 30/9, 2014 at 7:22 Comment(1)
No, I haven't try it. Finally I have installed gulp-livereload and it works ;). Thanks.Krause
M
1

I also was struggling to find an answer howto to start a django server and get the browser live reloading working at the same time, however it turned out that it is easy to achieve (even when working cross platform on windows and linux):

//jshint node:true
'use strict';

var gulp          = require('gulp'),
    ....
    gutil         = require('gulp-util');

var browserSync = require('browser-sync').create();

var serverUrl = 'localhost:8000';

var exec = require('child_process').exec;

var isProd = gutil.env.type === 'prod';

....
gulp.task('sass', function() {
  return sass(sources.sass, {
    compass: true,
    sourcemap: true,
    style: isProd ? 'compressed': 'expanded',
  })
  ....
  .pipe(sourcemaps.write('.'))
  .pipe(gulp.dest(targets.css))
  .pipe(browserSync.stream());
});
....

gulp.task('watch', function() {
  gulp.watch(sources.sass, ['sass']);
  gulp.watch(sources.pug, ['html'])
    .on('change', browserSync.reload);
  gulp.watch(sources.ts, ['typescript'])
    .on('change', browserSync.reload);

  // update browser on python change
  gulp.watch('website/**/*.py')
    .on('change', browserSync.reload);
});


// start django server
gulp.task('webserver', function() {
  var isWin = /^win/.test(process.platform);
  var cmd =  '. venv/bin/activate && PYTHONUNBUFFERED=1 ';

  if (isWin) { //for Windows
    cmd = 'venv\\Scripts\\activate.bat && set PYTHONUNBUFFERED=1 && ';
  }

  var proc = exec(cmd + 'python manage.py runserver ' + serverUrl);
  proc.stderr.on('data', function(data) {
    process.stdout.write(data);
  });

  proc.stdout.on('data', function(data) {
    process.stdout.write(data);
  });
});


// start livereload
gulp.task('browser-sync', ['typescript', 'html', 'sass', 'webserver'], function() {
    browserSync.init({
      proxy: serverUrl,
      port: 8080,
      reloadDelay: 300,
      reloadDebounce: 500
    });
});
Maraca answered 18/6, 2016 at 20:35 Comment(0)
D
0

I assumed that you are talking about the static assets (stuff under static) in your django project.

The key step is to make the pages served by python manage.py runserver be aware of changes from the livereload server (usually implemented by tiny-lr)

A simple way to do so is to inject the following code to your base.html (assuming it as the parent template for the rest of html templates in django project)

# views.py
from django.conf import settings
# other imports ...
def index(request):
    ctx = {'debug': settings.DEBUG, }
    # other context setup...
    return render(request, 'index.html', ctx)

# other views' definitions...

<!-- base.html -->
{% if debug %}
    <!-- 
         assuming your livereload server runs at localhost:35729 
                                         (default host:port for livereload )
    -->
    <script src="//localhost:35729/livereload.js"></script>
{% endif %}

// gulpfile.js
var gulp = require('gulp'),
    gutil = require('gulp-util'),
    coffee = require('gulp-coffee'),
    livereload = require('gulp-livereload'),
    debug = require('gulp-debug'),
    watch = require('gulp-watch');

// other tasks definitions...

gulp.task('watch', function(){
    livereload.listen();    // starts a tiny-lr server, 
                            // default livereload server port is 35729
    gulp.src('static/src/**/*.coffee')
        .pipe(watch('static/src/**/*.coffee'))
        .pipe(coffee())
        .pipe(gulp.dest('static/dist'))
        .pipe(livereload()); // send a signal to tiny-lr server 
                             // to make the page with livereload.js 
                             // to perform a reload action
})    
Daphinedaphna answered 21/9, 2015 at 13:24 Comment(0)
V
0

I tried Frank Wile's answer, but I was having issues with it. The only way it worked for me with templates is if I saved a .py file and then made a change to a template.

I extended Frank's approach with a function that essentially touches a .py file before calling livereload.changed():

function touchPy() {
    gulp.src(appName + '/__init__.py')
        .pipe(gulp.dest(appName));
}

gulp.task('watch', function() {
    livereload.listen();

    // Changes to .css files works fine w/ Frank's approach
    gulp.watch(paths.static).on('change', livereload.changed);

    // Changes to .html files don't trigger a runserver refresh w/o touching a .py file 
    gulp.watch(paths.templates).on('change', function(file) {
        touchPy();
        livereload.changed(file);
    });
});
Venereal answered 20/11, 2015 at 1:52 Comment(0)
N
0

You must include:

<script type="text/javascript" src="http://127.0.0.1:32700/livereload.js" />

to django main template. See http://argskwargs.io/blog/javascript/django-typescript-gulp-part-three/ . This is example for js and css files:

var gulp = require('gulp');
var watch = require('gulp-watch');
var livereload = require('gulp-livereload');

var gzip_options = {
    threshold: '1kb',
    gzipOptions: {
        level: 9
    }
};

gulp.task('css', function() {
    return gulp.src('static/css/*.css')
        .pipe(livereload());
});

gulp.task('js', function() {
    return gulp.src('static/js/*.js')
        .pipe(livereload());
});

/* Watch Files For Changes */
gulp.task('watch', function() {
    livereload.listen(32700);
    gulp.watch('static/css/*.css', ['css']);
    gulp.watch('static/js/*.js', ['js']);

    gulp.watch('static/css/*', 'static/js/*').on('change', livereload.changed);
});

gulp.task('default', ['css', 'js', 'watch']);
Nide answered 11/8, 2017 at 8:57 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.