input username check unique immediately with django rest framework - django

I want to realize like this: if I input any character in username input tag I can check the username if unique in server.
I know I can do like this: use javascript + debounce, after user input characters stop 0.5 second, then I send username to server(I can create single view to handle this solution), and if find duplication, I can hint some error near it.
But in fact, I am not only handle the username, I want to handle all of config form, I want to every form's field can be test before send whole form data to server like this.
There may be 100 fields, I dont' want to write a view for every field, so does django-rest-framework support some function? or is there any package suuport it, or somebody have any idea for it??
in fact, I use reactjs, but I don't think it have any relationship with this problem

No, there's no such thing. You'll have to write your own. A non rest entry point that would take a POST including field name and field value and check the unicity in the DB.

Related

Decide which model to retrieve data on Django Rest Framework

I'm trying to build a simple API which should do the following:
A user makes a request on /getContent endpoint, with the geographical coordinates for this user. By content, it means audio files.
Every time they send a request, we should just get a random object from a Model and return the URL field from it, to be consumed by the front end. For this, it can be a random one, it doesn't matter much which one.
Also, we should keep tracking about the requests each user makes. This way, we can check how many requests the user has made, and when they were made.
Every 5 requests or so, the idea is to send the user a customized content based on their location. My idea is to store this content in another model, since it would have many more fields in comparison from the standard content.
Basically, at every request, I'd check if it's time to send a special content. If not, just send the random one. Otherwise, I'd check if the time is appropriate, and the user is within a valid location based on the special content's data in the model. If this validation passes, we send the URL of the special content, otherwise, we just send the random one.
I'm having a hard time figuring out the best way to design this. My initial idea is to have two different models:
Model 1: Standard content. It has some fields to its meta data, such as duration, title and other stuff like this.
Model 2: Custom content. Besides the meta data, it should contain the geographical data, and the datetime range. This will allow the checking to be made if the content should be played or not.
Now it's the part I'm pretty much clueless. How to make it all work together?
QUESTIONS
Maybe storing every single request data from every user, and checking this data might not be very effective. It would require some writing at every request instead of just reading.
Since I'd be using two different models, how can I make the decision to happen in the view? I mean, the final output would be the same, an URL. But I'd have to make the decision process to happen in the view on which model to use.
I appreciate the help!

How to save form without validation

I want that my users can fill a post form partially, save as draft and then edit, finish and publish it. So the draft can have some required (text) fields empty. However I want the fields secure to store in the database (so, no special character, etc).
What's the best (or a good way) way to do this?
I think these solutions:
1) make two different models, one with required=False fields or
2) fill the empty text field with a temporary string ('draft'), then delete it e redraw as needed while edit, publish, save the draft. Or
3) deactivate the validation (novalidation, I'm not sure this works).
or what else?
I'm looking to the second way because the first I think will give me problems to manage two models and the third maybe is not secure.
PS I'm using ajax to call the views.

Tastypie sanitize input?

What would be the most effective way to sanitize a user's input using Tastypie? Right now, if a user enters something like hi, the HTML tags get saved, so when it is displayed, the text is displayed as bold. How would I sanitize all input besides changing the obj_create for each resource?
Also, since I am a newb at web security, should I be sanitizing a user's input at the front end, too? I am not sure if I should sanitize the input before sending the POST request to the tastypie API or if I should sanitize the input when tastypie is processing the input?
Edit: I did find out that I can escape HTML in my underscore templates by displaying data with <%- %> rather than <%= %>. Why doesn't underscore do this by default? I feel like it is a big security risk.
If I accidentally forget to do this somewhere, then I am screwed.
I think the above fixes the front end security problem, but what about the back end? Is there a way I can see if I am vulnerable to SQL injections? Will tastypie sanitize input when I do a POST/PUT request?
Never, Ever, Ever render untrusted user input to the browser. The only way you're seeing that in the browser is if you have |safe on the output filter. Don't do that. Don't set the property as mark_safe=True in the model either.
I added a dehydrate method to the resource that overwrote the dangerous field on it's way to the browser, like so:
def dehydrate(self, bundle):
bundle.data['field_to_sanitize'] = bundle.data['field_to_sanitize'].replace("&", "&").replace("<", "<").replace(">", ">").replace("'", "'").replace('"', """)
return bundle
Now, this isn't the best solution, but it will escape many of the most dangerous entities. If you have a htmlescape function handy, you can use that.

Assigning a "database id" to multiple html ids on a page

I will use model.id when referencing the id for the table in the database, and id when referencing the id given to elements in my html.
I have a django project where I am using some hidden form fields (all forms have the same id right now for that hidden field) to house the model.id. This works great as long as the model.id is known when the page is rendered.
I am now attempting to modify the process to work when no model.id is given (ie someone has chosen to create a new instance of my model). As far as the backend goes I have this working. No model.id supplied and the view knows it should give empty forms. At this point I choose not to create a new instance of the model, as I only want to if the user actually enters something in one of the forms.
If the user enters something in a form then the form processing creates a new instance of model and passes the id back to the users browser. What I was attempting to do is use the jquery form plugin to save the return data somewhere hidden, which I would then look at and use val to set all of the hidden fields' ids to the model.id that was returned so the next field/form the user submits will know to write to the model that was just created.
Now looking at this I'm guessing the idea of having multiple elements with the same id is bad, but I really do want them to always be the same and only have the hidden fields there to house that same Model.id on every form on the page.
I tried doing something like follows. However only one of the ids on the page actually got the value assigned. Is there a different way I should be accomplishing this goal? Is there something I should add to make all occurrences of id to be set with something like .val(model.id)? If not, does anyone have any suggestions on how to go about this? Maybe django provides a cleaner way of doing exactly what I'm trying to accomplish?
A response returned from form submission.
<response>
<the_model_id_brought_back>3732</the_model_id_brought_back>
...
<response>
The jQuery code attempting to set all of the "id_in_multiple_places" ids to the model.id returned.
jQuery('#descriptionForm').ajaxForm({
target: '#response',
success: function(data) {
the_model_id = jQuery('#response').find("the_model_id_brought_back").html();
jQuery('#id_in_multiple_places').val(the_model_id);
}
});
To explain why I have multiple forms like this. Forms consist of 1 visible field. Multiple forms are on the page. When a user leaves a field (which means they leave the form as well) I will submit that form to the server. This will allow their data to always be saved even if they stop half way through and throw their computer out a window. They can go to a different computer and pick up where they left off.
Thanks.
Now looking at this I'm guessing the idea of having multiple elements with the same id is bad
It's not only bad, it's impossible. You cannot do this. You can get around this by using classes, which don't have to be unique, but you probably shouldn't.
What you should do, is assign the elements sensible class names, and assign their common ancestor the ID. You can start at that element and traverse downwards to find the sub-elements by class name.

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.