Django saving models by JS rather than form submissions? - javascript

I have a contract job for editing a Django application, and Django is not my main framework to use, so I have a question regarding models in it.
The application I am editing has a form that each user can submit, and every single model in the application is edited directly through the form.
From this perspective, it seems every model is directly a form object, I do not see any model fields that I could use for custom variables. Meaning instead of a "string" that I could edit with JS, I only see a TextField where the only way it could be edited is by including it on a form directly.
If I wanted to have some models that were custom variables, meaning I controlled them entirely through JS rather than form submissions, how would I do that in Django?
I know I could, for example, have some "hidden" form objects that I manipulated with JS. But this solution sounds kind of hacky. Is there an intended way that I could go about this?
Thanks!
(Edit: It seems most responses do not know what I am referring to. Basically I want to allow the client to perform some special sorting functions etc, in which case I will need a few additional lists of data. But I do not want these to be visible to the user, and they will be altered exclusively by js.
Regarding the response of SColvin, I understand that the models are a representation of the database, but from how the application I am working on is designed, it looks as if the only way the models are being used is strictly through forms.
For example, every "string" is a "TextField", and lets say we made a string called "myField", the exclusive use of this field would be to use it in templates with the syntax {{ form.myField|attr:"rows:4" }}.
There are absolutely no use of this model outside of the forms. Every place you see it in the application, there is a form object. This is why I was under the impression that is the primary way to edit the data found in the models.
I did the Django tutorial prior to accepting this project but do not remember seeing any way to submit changes to models outside of the forms.
So more specifically what I would like to do in this case: Let's say I wanted to add a string to my models file, and this string will NOT be included/edited on the form. It will be invisible to the user. It will be modified browser-side by some .js functions, and I would like it to be saved along when submitting the rest of the form. What would be the intended method for going about doing this?
If anyone could please guide me to documentation or examples on how to do this, it would be greatly appreciated! )
(Edit2: No responses ever since the first edit? Not sure if this post is not appearing for anyone else. Still looking for an answer!)

There is some terminology confusion here, as SColvin points out; it's really not clear what you mean by "custom variables", and how those relates to models.
However your main confusion seems to be around forms. There is absolutely no requirement to use them: they are just one method of updating models. It is always possible to edit the models directly in code, and the data from that can of course come from Javascript if you want. The tutorial has good coverage of how to update a model from code without using a form.
If you're doing a lot of work via JS though, you probably want to look into the Django Rest Framework, which simplifies the process of converting Django model data to and from JSON to use in your client-side code. Again though DRF isn't doing anything you couldn't do manually in your own code, all without the use of forms.

Related

Where should you validate/sanitize data?

I am building a traditional MVC app. I have a /lib folder that defines functions that deal with database operations and dealing with external APIs. When processing user input, where should I validate the data? Should I validate it in the route controllers and then send that validated data to the database functions? Or should I do no validation in the route controllers and have the functions in the /lib folder do all the validation?
For me the most natural place is in the model because it contains the data. The GRASP Expert Principle says that you should assign responsibilities to an object that has the information to fulfill them.
We could argue that the controller may have all the information (data) required to do the validation but for me controllers should be light. Moreover, I think that "all the information" means not only having the data you must validate, but also knowing its format, and that's the model's concern. The controller may know how the data that a certain model needs should be, but that model could also be used outside that controller scope, so it should not rely on the controller's validation to work well as the model is (almost) your last chance to detect invalid data (you can, and must, also do that on the database, but data should be validated and sanitised before it goes into it, although normally there's a direct match between the database schema and the validation you should do in the model).
Every time you do CRUD operations with a model you will probably need to validate the data and you will be ensuring that your data is almost always correct. Moreover, the controller could also change the data that then goes into that model, so even if the controller validated it previously, it may produce invalid data.
However, think about that. The controller may change the data and in fact a lot of time they do so. It is unusual to always have a direct map between the fields in a form and a model and sometimes you will have inputs that have nothing or little to do with any model, so you should validate them outside the model. For example, think about the "Repeat password" field. It has nothing to do with the model! Only the "Password" field should reach it.
Other people would say that they prefer anemic models and that may fit best than rich models in some scenarios, but they also have some drawbacks and rich ones fit best in general.
You should also consider having validation in the client side (i.e. JS) so that you can give him a fast feedback about what he is doing instead of sending the data to the server to be validated and then wait the response or even load the whole page again!
One good way to do that is to use regex because you will have similar expressions between the different languages that you are using, although more often than not that won't be enough. Or better, you could use JS everywhere with Node.js and totally forget about that problem.
This may not be the answer you was looking for, but there is not only one right way to do validation as it is different for each application. Most times, validation should occur in different places, doing the same validation in some different layers of your application and different validation between some others.
There are more questions about this topic on StackOverflow, so you could check them to have different opinions from other people:
Best Place for Validation in Model/View/Controller Model?
MVC Question: Should I put form validation rules in the controller or model?
MVC - User input validation: controller, model or both
Where should data validation occur?
One of the nicest approaches I've seen is to define services and layer validation over the top of them using decorators. If validation errors occur an custom exception is raised containing the validation errors which is caught and handled by the controller and sent back to the client.
Controllers should be thin, and deal with things like requests and responses rather than business logic. Whatever approach you use I'd advise trying to keep it decoupled from the controllers.

In AngularJS, can/should I augment the model from a controller?

I'm very new to Angular and MV* in general (short of what I've gleaned from watching other devs work with Ruby on Rails for years), so please pardon what's probably a naive question.
I'm trying to set up a typeahead field where users can enter a street address and get live suggestions from the Google Geocoding API. I started verbatim with this example from UI Bootstrap (the "Asynchronous results" example in the middle field):
http://angular-ui.github.io/bootstrap/#/typeahead
It's working locally, but now I want to extend it to gather other pertinent details of the address and submit those along with the other form data. For example, if the Geocoding API returns a country type in address_components in its results (example here), I'd like to add that to the form data that I POST to the server. (There will be other logic to how/what properties I need to capture, but that's a good starting point.)
Right now, only the formatted_address property returned by the Geocoding API is submitted with the form, as the ui.bootstrap.typeahead directive binds that to the typeahead directive's <input> using ng-model.
So, my question is twofold (but please feel free to address either separately):
If I were starting from scratch (i.e., wasn't bound to the design/implementation decisions made in UI Bootstrap), what would be the most "Angular" way to implement this? Should the directive create an <input> bound with ng-model for every value I might want to capture, and then the controller would handle filling in the ones that are available?
Since I'm not starting from scratch, what is a reasonable way to augment the existing code to provide this functionality? Is there a way that I can add features to the existing directive? Does this behavior belong in the controller, or would I be better off abstracting it into a service? Or am I overthinking this - is there a simpler or better way that I haven't considered? Per the UI Bootstrap example, the only obvious place that I see to put this code right now is in the success function passed to .then() within $scope.getLocation(), where I'm handling the $http response, but my gut says that that's not ideal. All I can imagine doing there is adding properties to the form values object that I'm building (i.e., the object I'll POST on form submit), but then I have to know the names of those properties, so now my controller is tied too closely to the form in which it's used.
Thanks in advance for any help. I hope this makes sense. Since I'm still grasping the fundamental concepts, it would be especially useful if you could point me to any existing code that does something similar, or refer to specific documentation or articles that could lend some insight.
On #1, the Angular-UI design is a very "Angular" way to implement it - I don't see any issue with it. The directive takes a list and returns the selected list item. This is how the controller sees it. Put it in other words, another directive, say a typical <select> or a custom infinite scroll or a yelp-style map, would provide a different View behavior, but would be functionally equivalent from the controller's point of view - which keeps the separation of concerns intact, and thus very MVVM-y.
I also think that you have some confusion about ng-model. ng-model should be used with input controls (not only <input>) with which the user interacts with directly. In this case, the only input is a typeahead directive.
On #2, it depends whether the the "other pertinent details" are natural part of the service API or if they need to be fetched after selection. Assuming the former, the correct place is, in theory, in a service. The controller should only marshal data from Services to the ViewModel and back.
For your specific example with the country code, the API returns multiple components in address_components property. The extraction of the country code - as well as checking if it exists or not and other business logic - is best to handle in a service, probably with another service API after selection, or when the original list of addresses is obtained - whatever makes sense for your case.
For a simple case in a simple app, like in the example, you could just modify the $scope.getLocation() function to return a list of actual objects that your controller (or rather your ViewModel) actually needs, and then have the View return the selected object (as per #1).

mvc approach with javascript / jquery no framework

I'm developing a large scale application. Initially my approach was confused , I am a beginner in javascript even if I develop since January.
I was looking for an mvc approach and I found some guide lines, like :
Model : contains AJAX call , and services
Controller: e.g. jQuery widget and so on
View: e.g. rendering of HTML and so on..
I don't really have clearly how to structure a javascript application following perfectly the three above suggestions. I can do everything, I can manage template I can write jQuery manipulation , I can do AJAX call.
What is not clear to me is how to get really divided these three modules. When I try this approach I'm not able to make any module to do only what it has to do.
I tried also an MV* approach which, for what I see and for my needs maybe it's a better approach, because I have to do bind tons of divs , generate events , all by client side, receiving only data from server side.
What I would like to know:
Which are the really competences of each Module?
If, for example, I have to bind a click event to a button , where do I have to write the
.on('click',callback)
method? Where I have to write the callback he's gonna call?
I wrote : no framework because I'm sure that if I don't understand an approach writing it from scratch, its impossibile I will completely understand the use of a complete framework.
I hope that my doubts were clear, if not, please comment, I'll try to explain better if I can.
Sorry for my english in any case.
This is not an answer because there is no one answer. I just want to mention a few do's and don't's.
Do store pure data in the model. Think of it as business objects rather than display objects. For example, money should be stored in the model as a number, probably with some digits after the decimal point, plus an indicator of what currency it is, if that matters. Don't store the number as a string with local choices of the characters to separate the 1000's and the integer part from the fractional part and the right number of digits after the decimal point.
Do put the handler code for the click events (and similar user actions) in the controller.
Do put the code that causes updates the screen on load or on any external event in the controller. (An external event might be something like an update to a stock price due to stock exchange data or an update to the weather report coming into the application.)
Do put the HTML or the code that generates HTML as part of the view.
Do have the controller call the view to get the display updated/changed at the right times.
Do have either the controller or the view call the model to get the current model data values or the update the the current model data. (See similar "don't" below.)
Do reduce the connectivity between the three parts--M, V and C. Define clearly who can talk to whom for what purpose and keep that rule sacred. If you find an exception, its a smell indicating a problem with the big picture of those rules.
And some more things
Don't put the code that displays the screen on load in the controller. That's clearly a view concern. This means the controller has to call into the view somehow.
Don't spaghetti connect the M, V and C code in random fashions. For example, you might make a rule that the model never calls code in the view or controller.
Don't have both the controller and the view talking to the model.
Questions:
Where does the code go that hooks up the event handlers?
Where do you put the "business logic"? This is the code that knows the rules of your application. Validation, for example, is business logic. Some code may need to know how zip codes look for the US and postal codes for the UK or Canada. If the validation fails, the controller is the one that tells the view to show an error message or red mark or vibrating box or whatever. Does the business logic of validation rules also go in the controller?
Where does the code go that loads data from external data sources? (servers, JSON web services, databases, screen scraping, etc.) You might think "model" but then the model has to call into the controller when new data comes back to tell it to update the view. That doesn't seem right.
Similarly, what is the code that handles the equivalent of a "submit" button, moving to another screen.
If converting data from a form that is displayable on the screen to a form that is pure data is too slow, what do you do?
There are always self-contained portions of the screen that can be built with their own MV&C. How do you set up interactions between multiples of those little MVCs and the big MVC that is the whole screen? Are those little guys the views for the big MVC? Or are the controllers? Can they be both at once? Is there a big model with the little models in it or does data flow between little models and big models? Who knows about all this?
Is there an even bigger MVC comprised of multiple screens? It would probably be on the server if it exists.
How do you handle "synthetic" events? This is something like an "event" that occurs when the data was ok but is now in a bad state (or was incomplete and is now complete). Listeners to this event can disable the "Submit" button and display error messages or animations calling the user attention to the problem. It could be anything that isn't a generic event built into the framework or language. Perhaps its a message to the server indicating a change in the state of a multiplayer game's world view.
This is just a list of things that pop to mind when you are writing your own MVC or when evaluating an existing framework.
There is no clear answer outside a specific framework. Although the general responsibilities of the MVC pattern are (almost) clear to everyone, each framework has its own interpretation of exactly what pieces of code to put in each of these layers - some frameworks even skip some layers, or add different ones instead.
I know you don't want to use a framework, but still, it's worth to have an overview of how the current solutions work, so you can make an informed decision if you like the way they work or if you prefer to roll your own.
I recommend you at least take a look at one server side MVC framework (such as Ruby on Rails or Asp.Net MVC) and some client side MVC frameworks too (Backbone.js, Angular.js, etc. - javascript only). Read their documentations, and learn from the choices others have made (and tested). The site todo mvc can help you to compare different client MVC frameworks to find the approach you like better.
This is not a simple topic, and discussing the pros and cons of each approach from scratch can take forever.

Is there an equivalent to Spring:bind for binding forms and data on the front end?

I asked this question a few weeks ago and didn't get the answer I was looking for, so figured I'd ask again a little differently.
I need to construct a form in my UI which will allow users to view and edit complex, nested objects. If I were doing this the JSP way, I would use Spring's bind functionality to associate form fields with backing objects. Each field would be tagged with an "address" indicating which field in the back object it's associated. Is there an equivalent front-end technology which will allow me to associate form fields with nested objects? I'm imagining a syntax that would look something like this:
<input class="boundInput boundTo:mailingAddresses[0].street" type="text" value=""/>
And an acommpanying javascript function which would examine all of the "boundInput" fields on the page and attach listeners which would update a backing js object intelligently based on the boundTo: class.
Does anything like this exist? Does anyone agree that it would be nice to have?
Here's the question I asked before:
Best way to link UI elements with backing javascript objects
I don't know about a library, but there's always this, assuming you're dealing with a global:
<input onchange="mailingAddresses[0].street=this.value" type="text" value=""/>
If not a global, there's DOM ways around that
As per my knowledge there is no such plugin or similar available. I think if I can give you a brief idea about how this binding works, you may see things in a different view and you may need to redesign your application accordingly.
Spring has special tag libraries to work with this form bindings. So when designing the forms in your jsp, you have to use these taglibs to code your form.
When you add an object with a specific key in the modal and then use the same key in your form tag as modalAttribute, spring looks up the object with the key and then for every attribute you access inside that form, it will use it to lookup and set the value to the control. Seriously there is very little magic in here.
When you are posting data to the form, spring does a little magic by looking at the RequestParam Annotation and then tries to bind all possible attributes to that object based on OGNL paths.
So what you are asking may not be available is my guess. I am working in spring and MVC for more than 4 years and never needed such a thing. If you can elaborate your problem I can help you more...

Connecting a form to a Javascript Object (and other best practice advice)

I've been using javascript to do lightweight functionality on sites for years - DOM manipulation etc - but just now im beginning to investigate using it to do a lot more of the heavy lifting (in combo with PHP). I've only just started getting into OO JS, and im still trying to get my head around the best-practices and design patterns that work well with it.
To be more specific - my question is, can anyone here suggest techniques for connecting a form to a javascript object?
In my current implementation I have an JS object that can be edited by a (fairly large) form. When I instantiate the object I attach an onchange observer to the form, whose callback syncs the form fields with the object parameters. I'm handling the form submitting through AJAX - there is also a periodic request that saves a temporary version of the form info to a mySQL DB. One thing I wonder is whether it is possible to easily handle syncing in the other direction - onchange of the object the form fields update (on form reset for instance).
I am interested to know if this approach is a correct/sensible one, and more generally I would be very interested to hear advice with regard to OOJS form handling.
Cheers in advance :)
(Im using Prototype btw)
You can use $("form").serialize(true);
http://www.prototypejs.org/api/form/serialize
You dont need the onchange event, you can just call the serialize() method every time you need to get the form data.
Why not create a method in you object that resyncs the object with the form? And call that on every change of the object? You could create a special change function to assure that it gets called on every change.
It's a perfectly reasonable approach. JS doesn't entirely encourage this sort of thing due to its curious object system and in particular the way bound methods are not first-class objects, but with a bit of suitable metaclass and callback glue it's eminently possible.
You might also want to look at a widget library if you'd like to get more of this kind of low-level form handling stuff for free. Haven't tried the ones built on top of Prototype; other possibilities include YUI's one.
Updating the model from the server can be pretty simple. Generally you'd poll an AJAX request and have the server pass back either diffs, if it knows them, or else just timestamp each object update, send the new object details to the client side on each update, and have the client decide how to merge that with any changes the user has made in the meantime.

Categories

Resources