I'm trying to create a filter system on a click event - using an AJAX post method to update the context that is shown on the template.
I'm currently using:
return HttpResponse(json.dumps(context), content_type="application/json")
To return a response with a context object. However, this doesn't quite work with certain object types:
TypeError: is not JSON serializable
I know there's something regarding serialisers but I'm currently unable to either a.) use them correctly or b.) use them at all.
For some context I'm passing filter variables to the view with the AJAX post method - then:
posts = Post.published.filter(category__name__in=category_filter_items)
And adding this to my context:
context['posts'] = posts
Would anyone know the correct way to update the context is such a manner?
First of all, you should know that once the Django template is rendered, you can't dynamically modify its context without rendering it again. See template documentation.
Before modifying dynamically your template, you should really consider a way to filter your data by calling a view that renders the template again with the context you need.
Option 1: Render the template again
def my_view(request):
posts = Posts.objects.all()
# TODO: Filter the posts against the request
template = loader.get_template('template.html')
context = {
'posts': posts,
}
return HttpResponse(template.render(context, request))
Option 2: Modify your template dynamically
If you're sure that modifying your template dynamically is your best / only choice, you've got different ways to achieve this.
One of them is changing your template via jQuery, loading a subtemplate that is rendered by your filtering view. Take a look at this issue.
Another way is to get your filtered data via a JSON Api and make sure your template is updated accordingly. You may want to use Angular for instance, which uses a MVVM architecture pattern.
How to serialize models in Django?
Django provides serialization of models as a core feature.
Serializing your models to JSON is as simple as:
from django.core.serializers import serialize
serialize('json', SomeModel.objects.all())
If you need to implement an API with serialization of models AND filtering, you may want to use django-rest-framework.
What about use JsonResponse instead of HttpResponse? also you need to define a serializer for Post model.
Related
I've been using arrow-kt and spring together a lot lately. I've actually constructed a bridge between the two with several key features, one of which is a spring controller that returns an Either will automatically unwrap it and either handle the exception (Left) or return the result (Right). My long term goal is to publish this as a library.
My latest obstacle is Swagger, or more accurately springdoc openapi. Obviously it is seeing the Either, but i want it to show only the Right value as the success response type. While I know there are annotations where I can set the response model on each controller method individually, I'm trying to avoid this.
My real goal is to setup some global converter so that wherever Swagger sees an Either it will automatically unpack this. I'm just not super familiar with the customization API in Spring doc, and everything I Google just points me to the ApiResponse annotation solution.
How can I define default handling for this type of response?
I am getting the data from server in JSON and I am converting that to my viewModal. Now I am loading the a new view using return router.navigate('results'). But at the same time I want to pass the viewModel which I created from the JSON object to be passed to this view. By default the "results" viewModel is getting called but it is having blank values.
A small code snippet will be helpful as I am new to Durandal JS.
The best answer I have is to store that information in a separate module, like so:
storage.js
define(function(require) { return []; });
viewmodel.js
define(['storage'], function(storage) {
$.get('uri', function(data) {
data.forEach(function(obj) {
storage.push(obj);
});
});
});
This is not the most elegant solution. I'm really interested if there is a clean way to pass data from and to separate view models on activation, but so far I have found none.
Ended up finally something like this.
In the module where I want to navigate, I created an "Initialize" function which accepts a JSON object. Using this JSON object I initialized all properties in the viewModel.
From the page from where I have to navigate there I did a "require" on the module where I want to navigate next. Then I called the "Initialize" method and passed my JSON object.
After this I used router.navigate method to go that module.
This way when I navigated, I got all the values which I wanted to pass from one view to other. Hope this approach will help someone else.
The answer from Matthew is certainly similar to the way that I currently do it, once the data is held within your separate module (i have a path called modules/data/someDataStorage) you can use either events or a knockout observable to make the data update through to your view models.
In your case I would make updates to your shared module to store information on your request and then on the activation of your results module, go and get the data from that shared module.
http://www.playframework.com/documentation/2.1.x/JavaTodoList
Using the above tutorial as a reference, I have created an application which sends data from the model to view via the Application controller.
I have managed to display the model(Tasks) as a high chart. The code is here.
public static Result format(){
return ok(views.html.frmt.render("Visualize it",Task.all()));
}
This goes to this view page.
http://ideone.com/ycz9ko
Currently, I use scala templating inside the javascript code itself. Refer to lines 9-14 and lines 20-24.This unelegant style of doing things is not really optimal.
I want to be able to accomplish the above using Json instead.
public static Result jsonIt(){
List<Task> tasks = Task.all();
return ok(Json.toJson(tasks));
}
My Qns are how to send the JSON objects to a view template.
And how to parse it into a Highcharts format. Is there some standard procedure to do this ? Or else I have to write my own method to do this ?
It'll great if someone can show me a code snippet. Also I would prefer a post not using Ajax. I would just want to know how to do this first.
I also found this stackoverflow post useful.how to parse json into highcharts. However, it didnt answer the part about converting from Play format to Highcharts format.
Thanks in advance
You don't need to pass a json object to your template, instead you might do an ajax call from your client side javascript (your template) and get json response that you could use futher in javascript code to build a chart. For example :
You have some path that is bind to your controller jsonIt() like so /chartsdata/json
then using jquery shorthand for ajax request:
var chart_data = $.get('/chartsdata/json', function(data) {
return data;
});
now you can use a chart_data that is an array of objects where each object represents a Task, in your further javascript code to build a chart.
We are currently trying to set up routes in such a way that the returned content-type can be set using a route parameter. The routing is all working properly now, but there is one problem. If one requests html, then the normal view script is rendered. The data we provide to this script can be anything from a string to a collection of objects, and the view script decides what to show to the user.
If however JSON response is requested, then we just provide the data returned from our controller as JSON. However, some data should not be made publicly available to the user, and hence some filtering is required. Is there any possibility to use JSON view scripts (as in ZF1 with context-switch) in order to support such filtering? Or maybe another method?
There is no such thing as a JSON script which lets you decide what to render and what not. You have to provide the proper data in the view model such that only the data is given that is eligible to be displayed.
I have been thinking about a hook in the JSON renderer so you can filter the view model's data based on the context of the request, but such thing does not exist yet. Unfortunately, you have to select the data in your controller or model.
I am implementing a multiselect autocomplete textbox (similar to one that Stackoverflow uses for tags input), using fcbkComplete. For implementation, I need to transfer JSON objects to a Jquery function from JSF. (There's a need to specify JSON url as parameter to fcbkComplete).
$("select0").fcbkcomplete({
json_url: "fetched.txt"
});
I am using JSF 2.0 with Primefaces 3.0M3. I would appreciate if someone can show me a direction as to how I can specify a JSON url to a js method in a JSF based application.
Thanks
At its simplest, you can just let a JSF managed bean getter return the desired JSON as a String and assign it to a JS variable which is inlined in the view template:
<script>
var json = #{bean.json};
// ...
</script>
(note that the variable value is unquoted! i.e. using var json = '#{bean.json}'; won't work out)
You can if necessary use among others Google Gson to easily convert between Java objects and JSON strings. You can if necessary put that <script> inside a <h:panelGroup> with an id so that it can be re-rendered upon an ajax request. You can if necessary end up wrapping this in a composite component.
True, it's very spartan, PrimeFaces may have better ways for approaching this, but I'm not aware of any.
As a completely different alternative, when the data does not depend on anything in the JSF context (expect of maybe some session scoped managed bean, which is available as a HttpSession attribute anyway), you can also create a simple servlet which does the job upon a jQuery.ajax() call. You can find several examples in this answer: How to use Servlets and Ajax?