Binding to (and totaling) arbitrary number of input values in AngularJS - django

I'm tackling learning a little AngularJS and have come across an issue that seems like it should have an easy resolution, but my searching of the docs and various forums are proving it's either a little more complicated or I just don't know the right terminology. Anyway, here's the short of it. I want to bind to an arbitrary number of input fields and total their values (so I can, for example, display a running total of user inputted numbers). However, not only are the number of input fields arbitrary, but the fields themselves may have different names every time.
Specifically, my data backend is Django, and for various reasons the form itself must be generated by Django's modelforms and then sent via an ajax call to the Angular front-end. I really want to avoid coupling too closely to each form (i.e. I don't want to write an Angular function for each possible permutation of form that Django might send, but instead want a single one that knows how to select the proper things to bind to).
I do have control over the construction of the forms via Django, and have been attempting to figure out what Angular directives I need to inject, but as I'm still on my way up the learning curve any guidance would be greatly appreciated.

How about using javascript array?
You can make a form with ng-model that refer to the array element.
And total() function to iterate though the array element and get the sum.
It can support arbitrary number of input elements this way.
If it is only about input elements and total function, it satisfies the requirement.
http://plnkr.co/edit/ZJCQ2m

Related

Deciding between Django's FBV and CBV

I'm trying to refactor some (4 in number) ajax views which work almost same as the following procedure:
Get some (2-4 in number) of objects using args
Return a json if any of the objects were not found, else continue
Then we extract another object (using the objects found in step 1) to update and create one if not found
Create a new form depending on the type of the object we got in step 3 and validate and update the object
Return a json in the end depending on form validity
The first 2 steps are common in all 4 ajax views. Even the models from which they try to extract the objects using args is common.
However, step 3 onwards things are very distinct in nature. The model used to extract the object and in turn the form used for validation. Also depending on the model there are certain more stuff happening in 2 of those ajax-views.
I'm quite new to Class-based Views and read this and this. Yet, I'm unable to see if I'd be making a drastically convenient future in terms of maintenance if I convert those 4 ajax-views to CBVs. And yeah, there's possibility that we create another such ajax-view once every year.
Question is: Should I use CBV or not, given that I can only stop replication of first 2 steps if I used CBV?
Personally I find class based views easier to read. Ability to use inheritance to not repeat the same code is nice even i you use it just a little bit. I find that the class based views really shine when you develop RESTful APIs, since you can process all the different request methods in the same class.

Sitecore cleanest way to store form field labels

I'm working on a Sitecore implementation where there are many forms throughout the site (before you ask, WFFM is out of the question!).
My question is, what is the best way to store the form labels? My current thinking is to use a dictionary structure and access form field labels by key. The problem with this approach is when editors want to vary the label for the same field; e.g. on form X the first name field is "First Name" then perhaps somewhere else it could be "Forename" or maybe it's a required field (with asterisk) in one place an optional in another. I don't really want to start having dictionary items called "FirstNameWithAsterisk" and "FirstNameWithoutAsterisk" etc.
One other thought I've had is to simply store the form labels in a Name Value List field. This field could then be populated with Names/Values like and editors would be free to use whatever form labels they like, without risk of inadvertently editing a dictionary entry used somewhere else.
I've been down the route before of having form fields on the page template, but this is a pretty horrible solution IMHO so I wouldn't be interested in going down this route again.
EDIT
To confirm, there are a finite number of forms for this site.
I would go with the dictionary approach. If your argument is that it could vary, then that's a reason to logically separate them. So, it sounds like you have custom forms and a finite set of forms to be built (please confirm). That said, build your dictionary just like that, e.g.
Form1
Form1-FirstName
Form2
Form2-FirstName
Or another naming convention that makes sense for you.
Logically its the "first name field" for each unique form, but they're technically two separate unrelated things, hence you would want two dictionary items for them. You could do this via a naming convention that you alluded to, but don't name them based on the content, (since that value changes!), instead name it based on what it applies to / where it's used since your code will statically refer to the key.
So I would say FirstNameWithAsterisk and FirstNameWithoutAsterisk are bad names because they tie to the content and whether it has or doesn't have an asterisk. Instead, name it by the form it applies to or some other general notion of the content.
Edit: Since the same form component can be added to more than one page then this is a perfect case for a data source of that presentation component. Simply create a template for all of the form fields, then create any number of instances of those and for each form bound to a page, point its data source to the respective item with the desired field values.
You know there is a built-in Dictionary in Sitecore, right? Take a look at a System/Dictionary. Then get values from it by calling Sitecore.Globalization.Translate.Text().
If you're for sure not going to support multiple languages... then you could conceivably co-opt this feature and make different language versions of the dictionary items actually be the different values you want for the field labels.

Application logic in view code

Should I be writing application logic in my view code? For example, on submission of a form element, I need to create a user and send him an activation email. Is this something to do from a view function, or should I create a separate function to make it easier to test down the road? What does Django recommend here?
I found it very hard to figure out where everything goes when I started using django. It really depends on the type of logic you are writing.
First start with the models: model-methods and managers are a good place to perform row-level logic and table level logic i.e. a model manager would be a good place to write code to get a list of categories that are associated with all blogposts. A model method is a good place to count the characters in a particular blogpost.
View level logic should deal with bringing it all together - taking the request, performing the necessary steps to get to the result you need (maybe using the model managers) and then getting it ready for the template.
If there is code that doesn't fit in else where, but has a logical structure you can simply write a module to perform that. Similarly if there are scraps of code that you don't think belong, keep a utils.py to hold them.
You shouldn't perform any logic really in your templates - instead use template tags if you have to. These are good for using reusable pieces of code that you you neither want in every request cycle nor one single request cycle - you might want them in a subset (i.e. displaying a list of categories while in the blog section of your website)
If you do want some logic to be performed in every request cycle, use either context processors or middleware. If you want some logic to be performed only in one single request cycle, the view is probably the place.
TLDR: Writing logic in your view is fine, but there are plenty of places that might be more appropriate
Separating the registration code into it's own function to make testing easier is a good reason. If you allowed admins to register users in a separate, private view, then a registration function would be more DRY. Personally, I don't think a little application logic in the code will do to much harm.
You might find it instructive to have a look at the registration view in the django-registration app -- just to see how it's written, I'm not saying you should or have to use it. It has encapsulated the user registration into it's own function (there's a level of indirection as well, because the registration backends are pluggable).

django - allowing arbitrary user inputted data to be entered to filter() - is this secure?

As far as I know (I haven't looked into the django's admin source code deeply enough to figure out) Django's admin translates GET query parameters directly to the query filter conditions.
I was wondering, is this approach secure enough to be used in user-facing application? I have a list of data, that has to accept arbitrary WHERE clauses, and I'm thinking of implementing it by converting the GET parameters into a dictionary so that it can be passed into the filter() method of the queryset.
Yes.
The input will be escaped, so there can be no SQL injection attacks or anything similar. However the input might be invalid for the field(s) you are searching on. Or it may make no sense at all, so it is a good idea to do some form of validation (like the input date must be bigger than some other date, the input value must be smaller than X, etc)
However, if you want to display the data you received from the user as part of a page, you need to make sure to escape it properly. Documentation on the autoescape tag
I think the correct answer is "No, it's not safe"
http://www.djangoproject.com/weblog/2010/dec/22/security/
Django just released security fixes to 1.2.4 and 1.3b1 preventing users from constructing arbitrary query filter. With sufficient knowledge of the underlying data model and usage of regular expressions, arbitrary information, such as user's password hash, can be extracted.

Role of django filters. Filtering or upfront formatting within the view?

I would like to hear your opinion about this.
I have a django application, where the data obtained from the model are rough. To make them nicer I have to do some potentially complex, but not much, operation.
An example, suppose you have a model where the US state is encoded as two letter codes. In the html rendering, you want to present the user the full state name. I have a correspondence two-letters -> full name in another db table. Let's assume I don't want to perform joins.
I have two choices
have the view code extract the two-letter information from the model, then perform a query against the second table, obtain the full name, and put it in the context. The template renders the full state name.
create a custom filter which accepts two-letter codes, hits the db, and returns the full-length name. Have the view pass the two-letter information into the context, and put in the template the piping into the filter. The filter renders the two-letter code as a full string.
Now, these solutions seem equivalent, but they could not be, also from the design point of view. I'm kind of skeptical where to draw the line between the filter responsibility and the view responsibility. Solution 1 is doing the task of the filter in solution 2, it's just integrated within the view itself. Of course, if I have to call the filter multiple times within the same page, solution 1 is probably faster (unless the filter output is memoized).
What's your opinion in terms of design, proper coding and performance?
It seems to me your model should have a method to do the conversion. It seems like extra work to make a filter, and I don't think most Django developers would expect that sort of thing in a filter.
A filter is meant to be more generic - formatting and displaying data rather than lookups.
My oppinion is that the first solution is much cleaner from a design point of view. I'd like to see the template layer as just the final stage of presentation, where all the information is passed (in its final form) by the view.
It's better to have all the "computation logic" in the view. That, way:
It's much easier to read and comprehend (especially for a third party).
I you need to change something, you can focus on a particular view method and be sure that everything you need to change is in there (no need to switch back and forth from view to template).
As for performance, I think your point is right. If you want to do the same lookup multiple times, the 2nd solution is worse.
Edit:
Referring to ashchristopher's comment, I was actually trying to say that it definitely does not belong to the template. It's never really clear what business logic is and where the line between "data provision" and "business logic" lies. In this case it seems that maybe ashchristopher is right. Transformation of state codes to full state names is probably a more database related encoding matter, than a business logic one.