django rest framework API edit function - javascript

though I am new to django rest framework, all in all, i get how the posting and viewing works each using jquery ajax to post and angular js for rendering the API json data.
but i don't understand yet how the 'edit' and 'delete' function should be implemented here.
it means i have to load preexisting title and contents to the designated field forms and resave the post into that specific post id.
how can i do that?
and how can i check the permission when executing edit or delete function using either jquery or angular?
please consider the fact that my website is SPA (single page app) that shouldn't require any sort of page refresh.
so these concepts are fairly new to me, and i don't understand how i can manually check the permission using only the API
here is the live site : http://192.241.153.25:8000

You can use class based views for this. Using class based views you can have different end points for different functionalities, differentiating on Request types.
class AView(APIView):
def get(self, request, format=None):
pass
def put(self, request, format=None):
pass
for authentication and permissions do refer to http://www.django-rest-framework.org/api-guide/authentication/#tokenauthentication

Related

Best Practices in Razor Pages: Using AJAX or Handlers for post/get requests

Generally speaking when you're doing a POST request you want to reload the page. Though not always. When using a GET method to retrieve data you may consider using AJAX. However I am relatively new to Razor Pages and ASP.net core altogether. I am being told we should always load the page. That since we are using Razor Pages it is not correct to use AJAX to submit anything to the code-behind. Otherwise whats the purpose of using Razor Pages.
My concern is it leaves a bad user experience. If I want to run a report, retrieve the data, and show the data using a handler. I require the page to reload. If I use AJAX I require JSON but it doesn't require the page to reload. If I use a handler I can get back a model which I can use to display on the reloaded page without having to convert it to JSON.
What is the best practice with Razor Pages? It seems like if you must reload every time we are going back in time to 2003.
It's perfectly fine to use AJAX to submit to the Razor Pages code-behind, I've built a blog application's Admin Panel based on this with satisfactory results https://github.com/FanrayMedia/Fanray
The Razor Pages model-behind class serves as convenient end points that return JSON to your AJAX calls. For example, my blog's composer which is a Razor Page has an auto-save draft feature, in the view I have js code like
axios.post('/admin/compose?handler=save', this.payload, { headers: { 'XSRF-TOKEN': this.tok } }) ...
which posts to this model-behind class code
public async Task<JsonResult> OnPostSaveAsync([FromBody]PostVM post)
{
...
return new JsonResult(postVM);
}
Hope this helps!

Do we need AJAX in Spring MVC? When?

I am trying to learn Spring MVC and I wanted to get hands on in MVC. I have a simple web application where I am inputting a string from the user and displaying some results from a database back to the user. All this is happening in a single page without the page refresh. We can use RequestParam in the controller and access the elements in the JSP page. ( I am using Bootstrap for this project)
For example in home.jsp,
<form class="navbar-form navbar-right">
<input type="text" name="myValues" class="form-control" placeholder="product..." >
</form>
and, in the controller,
#RequestMapping(value={"", "/", "/home"}, method = RequestMethod.GET)
public String home(Locale locale, Model model,#RequestParam(value="myValues", required=false) String myValues) {
logger.info("Welcome home! The client locale is {}.", locale);
This will help me get the form query string in the controller.
I can then do the necessary processing and use addAttribute in the controller to return the list. (Retailerdetail is my class to implement the backend database)
ArrayList <RetailerDetail> rlist = mydata.getData();
model.addAttribute("name",rlist);
return "home";
and display it in the jsp page.
<c:forEach items="${name}" var="element">
<tr>
<td>${element.name}</td>
</tr>
</foreach>
At this point of time I am doing this without using Jquery or js. I have seen some code where people use jquery or js for ajax implementation in Spring MVC.
My question, is this AJAX? We are getting similar functionality as AJAX without using Javascript or Jquery. Why is jquery or js used for implementing AJAX when using Spring MVC. Can you please give a specific example where I might have to do the same? I have gone through tutorials of MVC as well as AJAX quite a bit, but dont have a complete understanding of the concept. I realize that I am missing some basic concepts here. But it will help me get a lot of clarity if you could explain.
To quote from What is AJAX, really?
This is the answer by Nosredna:
"The rough idea in English: You have a web page. Some event (can be
a button press or other form event, or just something triggered by a
timer) occurs and triggers JavaScript code that asks the server for
fresh information (like the latest value of GOOG stock). There's a
piece of code on the server that collects the info you passed and
sends some info back. That's different from the page-serving job the
server usually has. When the server answers, a callback function
(that you specified in the JavaScript call to the server) is called
with the info from the server. Your JavaScript code uses the info to
update something--like a GOOG stock chart."
In my code the same functionality is achieved without using Javascript? That means we can implement the AJAX functionality without using any Javascript? When do we really have to use Javascript for implementing AJAX in this case?
If you open developer tools in your browser (f12), open the network tab, and then perform the request from your web-page, you will see the the entire html page is returned in the response.
Using AJAX, the server will return just a JSON key-value map. Your javascript code can then use this to populate a section of your page, leaving most of the page unchanged.
This is more efficient and quicker.

Rails API - helpers for AJAX

I have a normal rails app website, but on some pages I need to use AJAX.
I already have some working AJAX Javascript code using jQuery, but so far I haven't used any rails helper to do that, writing strings corresponding to paths manually.
But is there a more convenient way to do it in javascript ? Suppose I have a javascript function which takes an ID as argument, and must call an AJAX action. So far I've been doing it this way
var url = "/tags/tagID"
function getTag(tag_id){
$.get(url.replace("tagID", tag_id) +'.json')
.fail(function(data){
alert('Oops error !');
})
.success(function( data ) {blabla ] )
}
Is it possible to rename the .js to .js.erb and use path helpers ? So I could get rid of this url variable and write
routes.rb
resources :tags
tags.js.erb
$.get(tag_path("tagID").replace("tagID", tag_id)....
Or is there a more convenient way to do this ? I only need very little AJAX, so I don't want to use a frontend framework (Angular, etc.), just jQuery
EDIT My scenario
A user searches for a given tag thanks to an autocomplete searchbar. This searchbar will return the ID somehow.
The user can select several tags this way, and their IDs will be stored in an array. Now, upon clicking a button, I want to send a query to a non-RESTful (with the ID array as parameter) controller action via AJAX. For now I will focus on sending one item at a time (so just one ID string), for it is easier/more reactive.
This action is actually going to look in my models for projects and ingeneers that possess this tag, and return a JSON with formatted results.
Yes, you can use *.js.erb to use Rails helpers. Rails provides some handy helpers to work with Ajax. Normally with rails you can use them by using the the tag remote: true.
In your case something like
<%= link_to 'Tags', tags_path(<tag.id>), remote: true %> (roughly),
Read more about using Rails helpers with Ajax here, and this explains it nicely.
Update
Rails is using CSRF token to validate requests (except GET), so if you are going to use pure HTML/JavaScript, you want to add the token to your request. Have a look at this post on the same.
I agree there is no out-of-the-box way of doing that, but there are few workarounds.

Confusion about Backbone.js and Django

I'm trying to use Backbone.js for my Django project and it's confusing. So to my understanding, I need tastypie for the RESTful API with Django to which I'm new, so for example I have a SongResource like follow :
class SongResource(ModelResource):
class Meta:
queryset = Song.objects.all()
authorization = Authorization()
All what this does is gets back a list of all the songs I have in the database, right? To my understanding, I should use this in the Backbone.js router to get all the songs, and then do all the data manipulation in my JS code instead of the Django's view?
So if I want to get all the songs that the logged-in user purchased, I should get all the songs from Django, and search for the user's songs in JS code?
Also, what if I want to save songs the user listened to for example, I'm used to do that by sending an Ajax request to a view where I save the action.
Another thing is, let's say I have five models in my Django app, should I create the give models in Backbone.js too?
So in Backbone.js, I just get the data from Django and manipulate them in the front end instead of the Django views as I'm used to?
If you can see my confusion please guide me to some articles, tutorials, videos whatever !
Thanks a lot
You definitely have to do the filtering on Django side :) I know nothing about tastypie, but as of current (logged in) user, you have that in django session, therefore you cannot rely on Meta.queryset, instead the queryset changes for every request. You probably need to override some view method.
As of saving listened songs, you first decide when to do that (start or end of song), and upon that event you save() some Listening (Backbone) model, that will trigger the XHR request (see Backbone.sync).
Yes, you should Backbone model counterparts for your Django models if you use them client side. Again, see Backbone.sync

How to write Rails code to handle request from client (JS) for Phonegap development

EDITED Question
I understand that I can't just throw Rails code into Phonegap and I have to write create some static pages and use JS to do the server communication for data. My question is how to write Rails code to handle http request to return a JSON with information?
Thanks
OLD Question
I built a Rails mobile app and I am interested in using Phonegap to turn it into a native iPhone and Android app.
I searched around and wasn't really able to find a good tutorial on how to do this. I watched the Quick Left video and I am confused why the extra middle wear code was needed. From my understanding, to use Phonegap I need to rewrite all the front end and data fetching in javascript.
If anyone could offer some insight or point me to some tutorial to how I could integrate my Rails app with Phonegap please let me know.
Thanks
I do not think this is possible. Ruby would need an interpreter and unless it is in the browser, it cant run. I think the only way is to use javascript
You canĀ“t, but maybe you want to try Rhodes: http://rhomobile.com/products/rhodes/
Rails 3.1.x already returns JSON requests if you have a controller like this:
class EaracheMyEyeController < ApplicationController
def show
#earache_my_eye = EaracheMyEye.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.json { render json: #earache_my_eye }
end
end
end
The format.json { render json: #earache_my_eye } part will render the data as JSON if you visit the URL of the object, for example earachemyeyes/1.json
So, in your phone gap app you would call URLS GET method to receive data and add on .json on the end of the url to receive JSON formatted data.
Update:
A few things I learned recently about JSONP requests in phonegap. They are only GET requests. No posts.
However, you can append a _method=POST, and add configure.middleware.swap(Rack::MethodOverride,Rack::RestfulJsonpMiddleware to your conf/environments/(production/development/test).rb file(s)
Add something like this to your library:
https://github.com/quickleft/kbomb_phonegap_server/blob/master/lib/rack/restful_jsonp_middleware.rb
This allows you to send an actual GET request, yet it is read and processed as your _method=POST or whatever method you really need. You can't use the built in Rack::MethodOverride because it only implements POST, and nothing else (was meant to facilitate PUT and GET). So the file at https://github.com/quickleft/kbomb_phonegap_server/blob/master/lib/rack/restful_jsonp_middleware.rb builds a new Rack middleware that lets you use all HTTP methods.

Categories

Resources