Giter Club home page Giter Club logo

django.js's Introduction

Django.js

image

image

image

image

Django.js provides tools for JavaScript development with Django.

Django.js is inspired from:

This is currently a work in progress (API wil not be stable before 1.0) so don't expect it to be perfect but please submit an issue for any bug you find or any feature you want.

Compatibility

Django.js requires Python 2.6+ and Django 1.4.2+.

Installation

You can install Django.js with pip:

$ pip install django.js

or with easy_install:

$ easy_install django.js

Add djangojs to your settings.INSTALLED_APPS.

Add djangojs.urls to your root URL_CONF:

urlpatterns = patterns('',
    ...
    url(r'^djangojs/', include('djangojs.urls')),
    ...
)

Documentation

The documentation is hosted on Read the Docs

django.js's People

Contributors

michaeljones avatar noirbizarre avatar randlet avatar szelga avatar thedrow avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

django.js's Issues

Support for Django 4.x

We are using django.js in our project for a long time and it was working fine until we upgraded to Django 4. The issue was import of six has been changed from Django 3 onwards. We have fixed it already by directly changing the codebase.

I would like to update the codbase of django.js to add support for Django 4.x

Thanks for django.js and eztables

No issue or feature request, just wanted to say thanks for both django.js and eztables. Both projects helped me integrated datatables into my app and it's great!

-Jay

Localize?

ImportError: cannot import name make_messages

Whats the correct way of using localize nowadays?

Adding none-named views to resolve

Just a quick question (Maybe suggestion?):

sometimes i dont have supplied names for my views, maybe like this:

url(r'^new_obj$', 'project.main.views.new_object'),
url(r'^load_obj$', 'project.main.views.load_object', name="load"),

which results in only beeing able to do the following, because new_object is not found

Django.url("load")

If, in the utils.py, the function _get_urls(...) is modified as follows, there would be a default for the name:

if issubclass(pattern.__class__, RegexURLPattern):            
    func_name =  u"{0}.{1}".format(pattern.callback.__module__,pattern.callback.__name__)
    pattern_name = pattern.name or func_name
    if pattern_name:
        ...

which would be resolved in JS as:

Django.url("project.main.views.new_object")

Maybee class-based views may mess that up, but a type-check of function would prevent that and also maybe include a Setting to prevent this. Would this be an idea worth implementing?

Greetings and thanks for the great util-package :)

Cannot import name 'patterns'

Hello, I'm having problem with djangojs in Django 1.10

return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 986, in _gcd_import
  File "<frozen importlib._bootstrap>", line 969, in _find_and_load
  File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 673, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 665, in exec_module
  File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed
  File "/usr/local/lib/python3.5/site-packages/djangojs/urls.py", line 6, in <module>
    from django.conf.urls import patterns, url
ImportError: cannot import name 'patterns'

Packages:

  • Django==1.10.1
  • django.js==0.8.2.dev0

django.conf.urls.patterns was deprecated in the others django version, and in Django 1.10 was removed.

Failing unit tests

When I use django's ./manage test, there are many failed unit tests coming from django.js. I'm using Django 1.4.5 with psycopg2. Here is a typical example:

Failure
Traceback (most recent call last):
File "/home/woltman/projects/ve/compass/lib/python2.7/site-packages/django      /test/utils.py", line 211, in inner
    return test_func(*args, **kwargs)
File "/home/woltman/projects/ve/compass/lib/python2.7/site-packages/djangojs/tests/test_urls.py", line 134, in test_urls_namespaces_whitelist
self.assertIn('ns1:fake', self.result)
AssertionError: 'ns1:fake' not found in {u'grp_doc_filter': u'/grappelli/grp-doc/filter/', u'grp_doc_mueller_grid_system_layouts': u'/grappelli/grp-doc/mueller-grid-system-layouts/', u'grp_doc_groups': u'/grappelli/grp-doc/groups/', u'grp_doc_basic_page_structure': u'/grappelli/grp-doc/basic-page-structure/', u'grp_doc_modules': u'/grappelli/grp-doc/modules/', u'js_catalog': u'/djangojs/translation', u'grp_m2m_lookup': u'/grappelli/lookup/m2m/', u'selectable-lookup': u'/selectable/<lookup_name>/', u'grp_doc_admin_index': u'/grappelli/grp-doc/admin-index/', u'grp_doc_submit_rows': u'/grappelli/grp-doc/submit-rows/', u'grp_related_lookup': u'/grappelli/lookup/related/', u'grp_doc_errors': u'/grappelli/grp-doc/errors/', u'grp_autocomplete_lookup': u'/grappelli/lookup/autocomplete/', u'grp_doc_change_list': u'/grappelli/grp-doc/change-list/', u'grp_doc_navigation': u'/grappelli/grp-doc/navigation/', u'grp_doc_pagination': u'/grappelli/grp-doc/pagination/', u'django_js_urls': u'/djangojs/urls', u'grp_doc_mueller_grid_system_tests': u'/grappelli/grp-doc/mueller-grid-system-tests/', u'grp_doc_change_form': u'/grappelli/grp-doc/change-form/', u'grp_doc_mueller_grid_system': u'/grappelli/grp-doc/mueller-grid-system/', u'grp_doc_context_navigation': u'/grappelli/grp-doc/context-navigation/', u'grp_doc_form_fields': u'/grappelli/grp-doc/form-fields/', u'grp_doc_object_tools': u'/grappelli/grp-doc/object-tools/', u'grp_doc_tables': u'/grappelli/grp-doc/tables/', u'django_js_context': u'/djangojs/context', u'grp_doc': u'/grappelli/grp-doc', u'grp_doc_tools': u'/grappelli/grp-doc/tools/', u'grp_doc_fieldsets': u'/grappelli/grp-doc/fieldsets/', u'grp_doc_date_hierarchy': u'/grappelli/grp-doc/date-hierarchy/', u'django_js_init': u'/djangojs/init.js', u'grp_doc_search_form': u'/grappelli/grp-doc/search-form/'}

What should I do to get these tests passing?

user.id is stale because of cache.

I use Django.user.is_authenticated or Django.user.id in my javascript.

When user logs in for instance, Django.user.id value doesn't change to the logged-in user's id. (I guess it's because of the cache)

Is there a way for me to invalidate the cache when needed?

djangojs does not handle unimported installed_apps, throws error.

When the djangojs.urls file is processed, any apps in INSTALLED_APPS that are not explicitly imported cause processing to fail. Traceback below. A work-around is to ensure that any such apps are imported e.g. in settings.py:

import widget_tweaks

A better fix would be to ensure these apps are imported directly in djangojs.urls.

Traceback:

mod_wsgi (pid=4728): Exception occurred processing WSGI script '/home/rumple/webapps/project/project/project/wsgi.py'.
Traceback (most recent call last):
  File "/home/rumple/webapps/project/lib/python2.7/django/core/handlers/wsgi.py", line 241, in __call__
    response = self.get_response(request)
  File "/home/rumple/webapps/project/lib/python2.7/django/core/handlers/base.py", line 179, in get_response
    response = self.handle_uncaught_exception(request, resolver, sys.exc_info())
  File "/home/rumple/webapps/project/lib/python2.7/django/core/handlers/base.py", line 224, in handle_uncaught_exception
    if resolver.urlconf_module is None:
  File "/home/rumple/webapps/project/lib/python2.7/django/core/urlresolvers.py", line 323, in urlconf_module
    self._urlconf_module = import_module(self.urlconf_name)
  File "/home/rumple/webapps/project/lib/python2.7/django/utils/importlib.py", line 35, in import_module
    __import__(name)
  File "/home/rumple/webapps/project/project/project/urls.py", line 12, in <module>
    url(r'^djangojs/', include('djangojs.urls')),
  File "/home/rumple/webapps/project/lib/python2.7/django/conf/urls/__init__.py", line 24, in include
    urlconf_module = import_module(urlconf_module)
  File "/home/rumple/webapps/project/lib/python2.7/django/utils/importlib.py", line 35, in import_module
    __import__(name)
  File "/home/rumple/lib/python2.7/djangojs/urls.py", line 35, in <module>
    url(r'^translation$', 'django.views.i18n.javascript_catalog', js_info_dict(), name='js_catalog'),
  File "/home/rumple/lib/python2.7/djangojs/urls.py", line 23, in js_info_dict
    module = sys.modules[app]
KeyError: 'widget_tweaks'

Issue with automatic installation

When I install django.js on a Ubuntu 14.04 machine in Python 3.4 virtual environment I get the following error message below. My work around is to manually install it which works and the automatic installation which uses ansible recognises that it is installed and all is ok.

Downloading/unpacking django.js==0.8.1 (from -r /home/ubuntu/projects/galleria/requirements/base.txt (line 15))
  Running setup.py (path:/home/ubuntu/.virtualenvs/galleria/build/django.js/setup.py) egg_info for package django.js
    Traceback (most recent call last):
      File "<string>", line 17, in <module>
      File "/home/ubuntu/.virtualenvs/galleria/build/django.js/setup.py", line 36, in <module>
        rst('CHANGELOG.rst'),
      File "/home/ubuntu/.virtualenvs/galleria/build/django.js/setup.py", line 28, in rst
        content = open(filename).read()
      File "/home/ubuntu/.virtualenvs/galleria/lib/python3.4/encodings/ascii.py", line 26, in decode
        return codecs.ascii_decode(input, self.errors)[0]
    UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 1543: ordinal not in range(128)
    Complete output from command python setup.py egg_info:
    Traceback (most recent call last):

  File "<string>", line 17, in <module>

  File "/home/ubuntu/.virtualenvs/galleria/build/django.js/setup.py", line 36, in <module>

    rst('CHANGELOG.rst'),

Support script prefix (subpaths)

It would be great if the URLs in init.js could be prefixed by the SCRIPT_NAME header, which facilitates running projects on a subpath (eg http://example.com/myproject/).

Otherwise it looks like you have to manually add the prefix. Or is there a better way I'm not seeing?

Any guidance on doing this? Would be glad to give it a shot.

django-cms apphooks are not displayed in javascript resolver

see info on apphooks.

to reproduce it you could use my test project: https://github.com/szelga/js-cms-test

on page http://127.0.0.1:8000/admin/cms/page/ create root page with some content, and, say, page with slug 'test2' hooked with 'My App' application (advanced settings tab). make sure that pages are published and you also clicked "publish draft" button. then test it.

on page http://localhost:8000/djangojs/init.js hooked app is not displayed, and it should be something like

"myapp-view": "/test2/",

django.js seems incompatible with social_auth

Hi,

when using any of the django social_auth templates context processors, the django.js init.js view fails because it can't serialize the request context to JSON. That's because social_auth installs one or more LazyDict in it, instead of a plain dict(), and the default JSONEncoder doesn't know how to serialize a lazy dict.

You've got the full stack trace here:

http://dev.1flow.net/development/1flow-dev/group/448/

I'd like an advise or at least your point of view on this issue:

  • Is it really needed to serialize all the context in {% django_js_init %} ? I currently don't use the serialized context in any way. It would be interesting in this case to be able to disable context serialization in settings, for example. This would make us gain a few cpu cycles.
  • or perhaps a more granular approach: provide a list of context variables that will not be serialized at all. This could be also from a setting, like DJANGO_JS_CONTEXT_IGNORE=['social_auth', … ]. This would make some things not available client side, but it's a bad for a good.
  • or even more granular: to be able to provide my own serializers from settings, eg DJANGO_JS_CONTEXT_PROCESSORS=['myapp.context_serializers.process_social_auth'], that would be looked up the same way as django.js already does today, (eg. if hasattr(cls, 'process_%s' % key) … ). This would allow me to provide the processors cleanly, without having to monkey patch djangojs.utils.ContextSerializer, which should work perfectly but is kind of rough and not friendly.

What would be your prefered approach ? I personaly prefer the third, and if you agree I can try to write a clean patch for django.js. In the patch, I could include my social_auth serializer (which will obviously just dump the LazyDict as a standard dict()) which could eventually be enabled by default, given the fact that social_auth is kind of common nowadays. Adding the second approach as an alternative seems easy, too. I can implement both.

Anyway, your feedback on this issue will be appreciated. I didn't study enough django.js to know if the first approach (completely disabling serialization) makes sense, or not.

best regards,

management commands incompatible with Django<1.5

it needs OutputWrapper class, which is present since django 1.5

  File "/home/szelga/soft/Projects/my_project/env/local/lib/python2.7/site-packages/djangojs/management/commands/js.py", line 9, in <module>
    from django.core.management.base import BaseCommand, handle_default_options, OutputWrapper
ImportError: cannot import name OutputWrapper

Looking for maintainers

Hi everyone !

It's been a pleasure to develop and maintain this application for Django.
Unfortunately, I can't maintain it anymore, mostly because I'm not using Django anymore and I don't have the time to follow the new versions.

I will very soon migrate this repository here: https://github.com/djangojs

I'm currently looking for maintainers so anyone interested in, please comment here.

Ordering of js_files not preserved

When passing an array of files to the js_file parameter of views JasminView or QUnitView, the ordering is changed by StorageGlobber.glob(). Example below.

ps. Django.js is awesome, big thank you.

In [2]: from djangojs.utils import StorageGlobber
In [3]: js_files=[
...: 'js/libs/underscore/underscore-min.js',
...: 'js/libs/backbone/backbone-min.js',
...: 'js/backbone.models.js',
...: 'js/tests/*.tests.js',
...: ]

In [4]: StorageGlobber.glob(js_files)
Out[4]:
[u'js/backbone.models.js',
u'js/libs/backbone/backbone-min.js',
u'js/libs/underscore/underscore-min.js',
u'js/tests/something.tests.js']

double make minify

in Makefile message and documentation.

$ make
Makefile for Django.js                                               

Usage:                                                               
   make serve            Run the test server                         
   make test             Run the test suite                          
   make coverage         Run a caoverage report from the test suite  
   make pep8             Run the PEP8 report                         
   make pylint           Run the pylint report                       
   make doc              Generate the documentation                  
   make minify           Minify all JS files with yuglify            
   make dist             Generate a distributable package            
   make minify           Minify Django.js with yuglify               
   make clean            Remove all temporary and generated artifacts

Django 1.7 app loader

Django.js doesn't seem to understand the new app loading system added in Django 1.7 when using custom AppConfig for application.

Tried with Django Debug Toolbar, we have KeyError exception when searching the module name of the application.

Having multiple JasmineSuite test cases fails

I've separated my coffeescript into their respective Django apps. As such, I have multiple test cases, one for each app. When I have one test case run, everything is fine, but when I add a second, the test fails. It actually "feels" like the tests run, but the output never makes it back.

Here is the output with verbosity turned on:

======================================================================
 ERROR: test (uln_ui.systemlist.tests.SystemListJSTestCase)
 ----------------------------------------------------------------------
 Traceback (most recent call last):
   File "/home/travis/src/uln/eggs/django.js-0.8.1-py3.3.egg/djangojs/runners.py", line 285, in test
     self.run_suite()
   File "/home/travis/src/uln/eggs/django.js-0.8.1-py3.3.egg/djangojs/runners.py", line 170, in run_suite
     self.phantomjs(self.phantomjs_runner, url, title=self.title)
   File "/home/travis/src/uln/eggs/django.js-0.8.1-py3.3.egg/djangojs/runners.py", line 154, in phantomjs
     raise JsTestException('Failed javascript assertions', failures)
 nose.proxy.JsTestException: Failed javascript assertions
  + encountered a declaration exception - expected: 'undefined', got: 'undefined'
         http://localhost:8081/static/js/djangojs/django.min.js:1
         :8
         :308
-------------------- >> begin captured stdout << ---------------------

======================================================================
                       SystemList Jasmine Suite
======================================================================
Executing: ('phantomjs', '--cookies-file=/tmp/tmpul5kx_', '/home/travis/src/uln/eggs/django.js-0.8.1-py3.3.egg/djangojs/phantomjs/jasmine-runner.js', 'http://localhost:8081/jasmine', '3')
Coffee: systemlist/tests.coffee

# module:  ULN System List App
    # module:  SystemList Controller
    # test: encountered a declaration exception
    not ok 1 - expected: 'undefined', got: 'undefined', source: at http://localhost:8081/static/js/djangojs/django.min.js:1
    #    at :8
    #    at http://localhost:8081/static/js/test/libs/jasmine.js:819
    #    at http://localhost:8081/static/js/test/libs/jasmine.js:603
    #    at :308
    #    at http://localhost:8081/static/js/test/libs/jasmine.js:819
    #    at http://localhost:8081/static/js/test/libs/jasmine.js:603

TypeError: 'null' is not an object (evaluating 'match[1]')
  http://localhost:8081/static/js/test/libs/jasmine-djangojs.js:100
  http://localhost:8081/static/js/test/libs/jasmine-djangojs.js:85
  http://localhost:8081/static/js/test/libs/jasmine-djangojs.js:74
  http://localhost:8081/static/js/test/libs/jasmine.js:1788
  http://localhost:8081/static/js/test/libs/jasmine.js:2343
  http://localhost:8081/static/js/test/libs/jasmine.js:2348
  http://localhost:8081/static/js/test/libs/jasmine.js:2377
  http://localhost:8081/static/js/test/libs/jasmine.js:2106
  http://localhost:8081/static/js/test/libs/jasmine.js:2086

'waitFor()' timeout

======================================================================
ULN System List App
    SystemList Controller
        encountered a declaration exception (ko)
======================================================================

--------------------- >> end captured stdout << ----------------------

I did some digging, to the extent I could follow, and it looks like it is failing trying to communicate with phantomjs. The tests all run fine if I run them manually in the test server.

My workaround is probably going to be using a single test case that includes all of my test specs, but I find it sub-optimal. :)

Server Error on djangojs/init.js

Hey Guys,

I'm using Django.js for a lot of my personal project. It's a great package and thanks for this amazing work !

On the new django's version (it seems to be fine until 1.7), I've got this error when I try to load the init.js file:

http://localhost:8000/djangojs/init.js

AttributeError at /djangojs/init.js
'module' object has no attribute 'urlpatterns'
Request Method: GET
Request URL: http://localhost:8000/djangojs/init.js
Django Version: 1.7
Exception Type: AttributeError
Exception Value:
'module' object has no attribute 'urlpatterns'

In order to make it worked, I had to change the _get_urls function in the urls_serializer file.
I test if the module contains an urlpatterns attributes if not I create a new tuple.

def _get_urls(module, prefix='', namespace=None):
    urls = {}
    if isinstance(module, (six.text_type, six.string_types)):
        try:
            __import__(module)
            root_urls = sys.modules[module]
            if hasattr(module, 'urlpatterns'):
                patterns = module.urlpatterns
            else:
                patterns = tuple()
        except ImportError:  # die silently
            patterns = tuple()
    elif isinstance(module, (list, tuple)):
        patterns = module
    elif isinstance(module, types.ModuleType):
        patterns = module.urlpatterns       
    else:
        raise TypeError('Unsupported type: %s' % type(module))

    for pattern in patterns:
        urls.update(_get_urls_for_pattern(pattern, prefix=prefix, namespace=namespace))

    return urls

It's probably not the best solution but so far it works.

And I don't know if it's important but the module that causes this error is the one detailled below (seems to be related to a string python module)
:
['add', 'class', 'contains', 'delattr', 'doc', 'eq', 'format', 'ge', 'getattribute', 'getitem', 'getnewargs', 'getslice', 'gt', 'hash', 'init', 'le', 'len', 'lt', 'mod', 'mul', 'ne', 'new', 'reduce', 'reduce_ex', 'repr', 'rmod', 'rmul', 'setattr', 'sizeof', 'str', 'subclasshook', '_formatter_field_name_split', '_formatter_parser', 'capitalize', 'center', 'count', 'decode', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'index', 'isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']

Namespaced url pattern is repeated without namespace, collides with other patterns

I've got the following url patterns defined:

api:account:account-detail # api url
account:account-detail # web url

However, in init.js the url patterns are repeated with its namespaces stripped off. Now when I want to use the account:account-detail url pattern, it wrongfully uses the api:account:account-detail url pattern, as it comes first.

api:account:account-detail # api url
account:account-detail # api url
account-detail # api url
account:account-detail # web url
account-detail # web url

In init.js I only need the exact url pattern names, not with their namespaces stripped off. How can I do this?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.