jrief / django-angular Goto Github PK
View Code? Open in Web Editor NEWLet AngularJS play well with Django
Home Page: http://django-angular.awesto.com/
License: MIT License
Let AngularJS play well with Django
Home Page: http://django-angular.awesto.com/
License: MIT License
Add a flag to djangular/styling/bootstrap3/forms.py which enables to render
placeholder="<label>"
in input fields.
This has turned out to be more involved than I thought it would be.
Issue #59 addressed a problem with initial data.
I am now struggling with django-angular attempting to add the hidden html for errors. The problem comes from the fact that django puts errors from hidden fields at the top of the form, along with non_field_errors
.
So using form.as_ul we get:
<ul class="errorlist"><li>(Hidden field hide_me) This field is required.</li></ul>
The top_errors
are generated in BaseForm._html_output, as an ErrorList, where each item is a string. The string for a hidden field error looks like: (Hidden field hide_me) error_message
. Using TupleErrorList replaces error_message with a tuple, but since it is unside we end up with a string like: u"(Hidden field hide_me) ('RHVtbXlGb3Jt.hide_me', 'djng-field-errors', '$pristine', '$pristine', 'invalid', u'This field is required.')"
.
TupleErrorList is then expecting a tuple, but gets a string, so we end up with a rendered li
element like below:
<li ng-show="(.d" class="d">e</li>
This error occurs even when there are no errors, since django-angular is generating the hidden error text for client-side validation.
New features in 0.7.1 are:
action
against a private HTTP-headerDjNg-Remote-Method
. Added template tags djng_all_rmi
and djng_current_rmi
whichWithout the NgFormValidationMixin the post works fine, with it I get:
{"requests": {"content": "djangular.forms.angular_validation.KeyErrorList object at 0x1070b4510", "deadline": "djangular.forms.angular_validation.KeyErrorList object at 0x1070b4550", "email": "djangular.forms.angular_validation.KeyErrorList object at 0x1070b43d0", .....
A workaround I've found is to subclass the Form adding the validation just when used in the view. see here: https://github.com/simod/global_atlas/blob/master/maps/forms.py
I am new to django-angular, and would like to use it with a form field in which the ng-model is attached to a custom directive (not an input or select element). In this case I am using a modified version of http://mbenford.github.io/ngTagsInput/.
I will probably use a modified version of django-angular which will look for that specific directive. I have not yet started those changes, so I am opening this issue for discussion and suggestions, in the interest of making those changes worthy of a pull-request.
I've been using this directive, from the examples - however because our page has one form handled by django-angular and another one made by the django debug toolbar, it breaks when it finds these.
To make it work I changed it to look for a "djng-form" attribute - not sure if this is the best solution.
djng_forms_module.directive('djng-form', function() {
return {
restrict: 'A',
scope: 'isolate',
I'm looping through fields in a template to render a form, but have noticed that {{ field.errors }}
gets rendered as a string. I can get it to work by using the 'safe' filter, so it appears that it's not being marked safe for rendering. I attempted to fix this on TupleErrorList
and NgBoundField
but have had no luck
{% for field in form %}
<div class='has-feedback form-group'>
{{ field.label_tag }}
<div class='col-md-4'>
{{ field }}
{{ field.errors }}
</div>
</div>
{% endfor %}
Will it be a big rework to support python 3? pip-3.3 gives me the following error: File "/usr/local/lib/python3.3/dist-packages/djangular/core/urlresolvers.py", line 48
except KeyError, key:
I may be able to find the time to fork and work on it myself.
djng_forms_module.factory('djangoForm', function() ...
Long version
In my app I've used the djangoForm service and pass it my own 'errors' which come back from the server after I have posted the data via ajax (which I do on each keypress, for a sort of ghetto instant apply).
This works, although there is no easy way to clear the data, so I cheat .. by passing setErrors an object containing all the field names and an empty array:
{
field_name: [ "" ],
}
This is pretty dirty but works, the problem is that I get a tick after modifying a field, then when the server responds it disapears.
TLDR
Please can we have 'clearErrors'.
I'm using the Bootstrap3Mixin and am rendering a form that contains a checkbox. The template for the form uses field.label_tag
to render the label
{% for field in form %}
<div class='has-feedback form-group'>
{{ field.label_tag }}
<div class='col-md-4'>
{{ field }}
{{ field.errors }}
</div>
</div>
{% endfor %}
but this is the output
<label class="checkbox-inline">
<input id="id_signin.remember" class="ng-pristine ng-valid" type="checkbox" ng-model="signin.remember" name="signin.remember">
<django.utils.functional.__proxy__ 0x10de41a10="" at="" object=""></django.utils.functional.__proxy__>
</label>
I am losing the validation getting passed to angular when I use helper.layout in crispy forms. When I remove this snippet:
self.helper.layout = Layout(
Fieldset('Configure System Settings', 'expire_session_on_browser_close',
'idle_timeout_minutes', 'default_image_display')
)
Everything works fine and all of the validation gets passed through. But with it none of the ul or li tags with the validations are getting through.
Any suggestions on how to fix this?
Hi,
When I try to install it I meet the following error :
(soca) foxmask@foxmask:~/.pyenv/versions/soca$ pip install django-angular
Downloading/unpacking django-angular
Downloading django-angular-0.7.0.tar.gz
Running setup.py (path:/home/foxmask/.pyenv/versions/soca/build/django-angular/setup.py) egg_info for package django-angular
Illegal option -s
Installing collected packages: django-angular
Running setup.py install for django-angular
Illegal option -s
Successfully installed django-angular
Cleaning up...
this error occurs from the function read()
I use python 3.4.0
$ python --version
Python 3.4.0
but the issue come from which
- which does not have a -s option
$ which -s
Illegal option -s
Usage: /usr/bin/which [-a] args
system info about my OS & shell :
$ uname -a
Linux foxmask 3.2.0-4-amd64 #1 SMP Debian 3.2.54-2 x86_64 GNU/Linux
$ cat /etc/debian_version
7.4
Regards
I've got a choicefield with ng-model="group.selectedMessage.fields.sponsor".
That ng-model has a value of "AA", which is one of the options in the SELECT.
On loading, the model gets set back to undefined.
As a test, I tried changing the widget to a TextInput, if i did this then it didn't reset the value. Something about the SELECT is resetting the value.
I have the list of possible values client side, but I need to actually check that the new entry isn't a duplicate of another entry. I can do it outside the form framework, but it seems like I should be able to do this within the form.....
When using NgModelFormMixin on a form with field with a MultiWidget, all widgets within that MultiWidget get the same ng-model attribute, and so in angular all widgets(from that MultiWidget) are bound to the same variable.
The python docs for repr state:
For many types, this function makes an attempt to return a string that would yield an object with the same value when passed to eval(), otherwise the representation is a string enclosed in angle brackets that contains the name of the type of the object together with additional information often including the name and address of the object
In the case of TupleErrorList only a single element is returned, which is not intuitive. The Django class ErrorList uses this:
def __repr__(self):
return repr([force_text(e) for e in self])
While it doesn't strictly follow the python documentation (since running eval() on the rendered string would create a python List object) it is much more intuitive, which really helps when debugging.
I came across this while trying to deal with some hidden fields, which render errors in the same place as non_field_errors
. I will open a separate issue to discuss hidden fields.
I'm trying to use Bootstrap with django-angular, and I'm having problems with spurious errors being displayed. When I load the form for the first time, every field has an error set (in the django template variable {{ field.errors }}). This leads to incorrect formatting in templates that render the errors, which is standard behaviour for django forms.
I've tracked it down to the NgModelFormMixin.get_field_errors
method, which is adding the following tuple to field.errors: ('UmVjaXBlRm9ybQ.name', '$pristine', '$message', 'invalid', '$message')
.
This is obviously being set for a reason, but I can't spot why. What's the intended usage for field.errors
in django-angular? And, is it possible to work around this incompatibility to get field.errors
to not contain these spurious error messages?
For those of you, who used Crispy-Forms, please test the next upcoming release: 0.7.3.
It finally will be possible to style Forms rendered by django-angular in a way similar to Crispy-Forms. Currently the default Boostrap form styling is implemented, but it is quite easy to adopt django-angular to other styles in a pluggable way.
Please check the demo http://djangular.aws.awesto.com/base_form/
All code is available in the examples directory.
Please, register django-angular into bower, so django-angular.js can be installed with bower. For example, look into django.js bower.json https://github.com/noirbizarre/django.js/blob/master/bower.json
I don't have any staticfiles inside my main django projects, and I don't serve staticfiles from same server where django running. With bower will be easier to include django-angular into any front-end project which is being developed separate from backend django project.
The angular attributes come over, but the <ul> for each error in the field field only contains one <li>, the one for min_value's. The required <ul>, however, seems to show up/work (which seems to be present whether or not the form required=True is passed as a param or not). EmailField doesn't seem to work with angular in the example even though the <ul> is in the DOM.
After updating to 1.6.2, all of the expected <li>'s came with it (min_length, etc), and EmailField works.
However, my team isn't ready for 1.6 yet... :(
1.5.5 doesn't work.
1.6 does.
Hello!
*Subject
Need add generating code for client-side validation from django models
First of all I want to say that djangular + django-websocket-redis looks great. Really looking forward to get started using it.
I cloned django-angular, and set up a virtualenv with these packages:
Django==1.6.1
argparse==1.2.1
django-angular==0.5.0
django-websocket-redis==0.2.3
gevent==1.0
greenlet==0.4.2
redis==2.9.1
uWSGI==2.0
wsgiref==0.1.2
When opening multiple browser windows (Both Chrome and Firefox, or a combination of both), in some cases, the clients start overwriting each other. I'm not sure why, but it seems to happen when I type too quickly into the form. Try hammering the number keys in the Phone-field.
The result is that CPU usage goes to 100%, as the clients are sending changes all the time. One client adds a character, and the other one removes it.
I realize the three way binding is a new addition to the library, and the fact that I'm running both the server and clients locally, may all play a role here. Still, I thought it'd be worth an issue.
Has anyone else experienced this?
Simple CRUD query to get all objects returns HTML page instead of object, generating the following error
Error: [$resource:badcfg] Error in resource configuration. Expected response to contain an array but got an object
Hello:
I am getting this error "'ascii' codec can't encode character u'\xf3' in position 22: ordinal not in range(128)" when using Spanish language and there is an EmailField in the form. It looks like the validation text; u'Introduzca una direcci\xf3n de correo electr\xf3nico v\xe1lida.' (Introduce a valid email address) is not ready for encoding. The last 2 files in the traceback are (in order of appearance):
1: /usr/local/lib/python2.7/dist-packages/django_angular-0.7.3-py2.7.egg/djangular/forms/angular_base.py in as_ul
at line 54:dirty_list_items.append(format_html(li_format, *err_tuple))
2: /usr/local/lib/python2.7/dist-packages/django/utils/html.py in format_html
at line 82:return mark_safe(format_string.format(_args_safe, *_kwargs_safe))
Thank you very much,
Currently setup.py does a popen('pandoc') which when not installed causes an error.
Maybe the error could be handled and a meaningful error displayed around why you might want to install pandoc, or maybe silently ignore the missing program and just not print an error.
I noticed, that the current naming conventions are not very consistent.
Django-Angular's Javascript code, Directives start with djng-...
, which is in my opinion is a good choice.
Django-Angular modules start with ng.django.
... , which is distracting. In my opinion, a better prefix would be to also use djng.
...
Django-Angular Providers start with django
, for instance djangoForm
, djangoRMI
and djangoWebsocket
. This in my opinion is somehow acceptable, since they already are part of a Django-Angular namespace.
In Django-Angular's Python code, Mixins are Prefixed with Ng...
. For consistency, shouldn't they rather be renamed to say DjNg...
or djng
?
Please participate and point my on conventions used in similar third party modules.
The CheckboxChoiceInput class is not present in django 1.5.
https://github.com/django/django/blob/1.5.8/django/forms/widgets.py
This is the changeset where it was implemented:
django/django@9ac4dbd
Trying to use a focus-on directive. If I add it to the widget attributes it has to have a value. Seems like there should be some way to have it put the attribute in without the ="something" part.
For number fields there is no error message for field.$error.number
. You can see this problem in the demo if you input non-number characters into a number field. Instead of displaying a message about being an invalid number it says "This field is required". If you have a number field that is not required, it will display no error message(but still highlights the field in red).
When subclassing NgCRUDView and trying to return Django GeometryField coordinates from MySQL db like that: {{ object.coordinates }}
, Django-angular returns POINT (25.1806640625000000 54.5975278521138989)
. The Model's field looks like that:
from django.contrib.gis.db import models as gis_models
coordinates = gis_models.PointField()
{{ object.coordinates.x }}
or {{ object.coordinates.y }}
does not work at all.
If you want to get exact object coordinates, you must write your own serializer. Here's the code to make it work (ignore the comments) :
views.py
:
serializers.register_serializer('python_json', 'realestate.serializers')
class NgCRUDGeoView(NgCRUDView):
json_content_type = 'application/json;charset=UTF-8'
def serialize_queryset(self, queryset):
"""
Return serialized queryset or single object as python dictionary
serialize() only works on iterables, so to serialize a single object we put it in a list
"""
object_data = []
is_queryset = False
query_fields = self.get_fields()
try:
iter(queryset)
is_queryset = True
raw_data = serializers.serialize('python_json', queryset, fields=query_fields,
use_natural_keys=self.serialize_natural_keys)
except TypeError: # Not iterable
raw_data = serializers.serialize('python_json', [queryset, ], fields=query_fields,
use_natural_keys=self.serialize_natural_keys)
for obj in raw_data: # Add pk to fields
obj['fields']['pk'] = obj['pk']
object_data.append(obj['fields'])
if is_queryset:
return object_data
return object_data[0]
# my main view:
class PropertyMapView(NgCRUDGeoView):
model = Property
fields = ['name', 'coordinates', ]
serializers.py
:
from django.core.serializers.python import Serializer as OverloadedSerializer
from django.utils import simplejson
from django.contrib.gis.db.models.fields import GeometryField
from django.contrib.gis.geos.geometry import GEOSGeometry
from django.utils import simplejson as json
class Serializer(OverloadedSerializer):
def handle_field(self, obj, field):
"""
If field is of GeometryField than encode otherwise call parent's method
"""
value = field._get_val_from_obj(obj)
if isinstance(field, GeometryField):
self._current[field.name] = value.coords
else:
super(Serializer, self).handle_field(obj, field)
Now when querying:
http://mydomain.com/myapp/crud/mymodel/?pk=1
it returns:
{"pk":1,"name":"Pastatas A","coordinates":[24.43359375,54.661123722066399]}
instead of:
POINT (25.1806640625000000 54.5975278521138989)
Hi, I am trying to use your library to generate a form with checkboxes. The following field definition:
x = forms.MultipleChoiceField(choices=(('a', 'A'), ('b', 'B')), widget=forms.CheckboxSelectMultiple)
generates the following html code:
<li><label for="id_x_0"><input id="id_x_0" name="x" ng-model="my_model.x" ng-required="true" type="checkbox" value="a" /> A</label></li>
<li><label for="id_x_1"><input id="id_x_1" name="x" ng-model="my_model.x" ng-required="true" type="checkbox" value="b" /> B</label></li>
which results in an unusable form (i.e. either both checkboxes are checked or none of them are checked).
pull request coming...
I'm trying to add additional classes to a form field through a filter, but it appears that when the ng classes are added, it replaces any classes that are already assigned to the field
http://django-angular.readthedocs.org/en/latest/angular-model-form.html#sample-code
This example appears to be rendering an html template through django tempting, and then sending the filled out form back to the server through ajax.
Angular’s url router works off of static html partials to load in a new view. Am I correct in assuming that your examples are all using django-processed html to load in that partial?
This occurs at forms.angular_base line 113.
I am planning to omit the label suffix altogether, although I suspect that will insert a ":", which may not be desirable in all cases.
Hi!
I'm contributing to OpenStack project and I would like to integrate django-angular on it. The problem is that it is needed that django-angular be packaged in Ubuntu/Fedora.
Are you planning to do it? Can I help in some way?
Thanks!
Best Regards,
Verónica Musso
In the non django-angular part of my app I use the 'AS' part of selects, to do something like this:
<select ng-options="proposition as proposition.name for proposition in strategy_propositions">
Is there a way I can tell a django-angular SELECT to do do this ? I guess ideally I could pass this as an option to the widget or field somehow ?
It is more as a question, is there a reason to support django forms instead of django-rest-framework (or tastypie)? DRF seems much more in line with the ideas of a single page web app.
If there is no reason then this is a request for support for DRF, and I can help with it :)
Given the slugs in use, I am guessing that one should be "reverse urls"
There is another module which uses the same package namespace djangular
:
https://github.com/appliedsec/djangular
This is rather unpleasant as it disallows to install both packages at the same time.
Docs here https://github.com/jrief/django-angular/blob/master/docs/angular-form-validation.rst
Says that form you can pass variable name to form. But its incorrect.
As i see in source code it should be form_name, not just name. If you pass name the error appears.
init() got an unexpected keyword argument 'name'
Replace console.log
-ing by Angular's own $log
provider.
Is there any way to use this with crispy forms ?
We had a look, it seems tricky since crispy changes the whole way forms are rendered, we had to turn off crispy for the parts where django angular is used.
What is the feasibility to use something like https://github.com/emmaguo/angular-poller in the case where websockets are not available?
In this case, sending to the server would be push based (HTTP POST/PATCH/PUT) and pulling new content from the server would occur on some poll frequency (GET).
Using the demo for ModelForm Validation, the birth date does not validate, even if it is valid input. When using the ajax submit it also will not accept a new value after the form fails to submit.
I have a quick question in regards to django-websocket-redis and django-angular.
It is my understanding (unless i am reading this wrong) that django-websocket-redis uses channels and events.
conn = redis.StrictRedis()
conn.publish('_broadcast_:foobar', 'Hello World')
where broadcast would be the event and foobar would be the channel.
wouldn't it make more sense to have control over what channel you are using instead of leaving it up to $window.location.pathname?
I am currently working on implementing inline formsets locally. Has anyone else used django-angular with inline formsets.
What I have in mind is putting the inline forms into an array, so I can use ng-repeat as I add or remove forms.
so the scope_prefix object would look something like this:
{ field1 : ,
field2: ,
child_model: [
{childfield1,
childfield2},
{childfield1,
childfield2},
...
]}
The other issue to address is putting ng-model on the django management forms, so those can be manipulated as forms are added/removed.
I am opening this issue as a place to keep track of how to implement this, if my workload permits I will update the demo and docs when I get it working. Any feedback or ideas are greatly appreciated.
Honestly, not sure whats happening, been trying for a few hours now to fix this with no luck. I have isolated the problem to this I am fairly sure. If I return address, the data is passed back to angular fine which then displays it. If I pass back an object or list I keep getting :
POST http://127.0.0.1:8000/ 500 (INTERNAL SERVER ERROR) angular.js:8467
(anonymous function) angular.js:8467
sendReq angular.js:8263
$http.serverRequest angular.js:7995
wrappedCallback angular.js:11485
wrappedCallback angular.js:11485
(anonymous function) angular.js:11571
Scope.$eval angular.js:12595
Scope.$digest angular.js:12407
Scope.$apply angular.js:12699
(anonymous function) angular.js:18941
(anonymous function) angular.js:2822
forEach angular.js:325
eventHandler
My view.py code
class HomeView(JSONResponseMixin, TemplateView):
template_name = 'angular/base.html'
@allow_remote_invocation
def main_query(self, in_data):
address = in_data.get('address')
list = Restaurant.objects.all()
data = {
'returns': address, #Returning list doesnt work.
}
return data
I think it has something to do with TemplateView, however if I just use View, it keeps giving me a KeyError for {% djng_current_rmi %}
Any ideas?
Hi,
I don't see PartialGroupView defined anywhere. Is it a work in progress or some alias ?
best,
https://docs.djangoproject.com/en/dev/topics/forms/#looping-over-the-form-s-fields
In django forms, I use custom django template looping to output html the way that makes most sense. I usually do this by looping over the fields in the form, and within those fields, outputting the field.errors near the field and field.label_tag. It ouputs a
If this isn't possible, please make a note of it in the docs. I just spent a couple hours trying to figure out why there was just a memory-location string being output :P
Also, looping over field.errors doesn't work either (probably the same issue).
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.