In a Tiddlywiki macro, what is the standard way to load JSON data from a JSON tiddler?
Currently, I've done this:
var my_dict = JSON.parse(this.wiki.getTiddlerText("my_json"))
Loving Tiddlywiki. Thank you!
Unless a better answer comes along:
Yes, this is the way.
But note that in some cases you'll have to use the $tw object (instead of 'this'), for example in a custom parser (such as tiddler of type 'application/javascript' and module-type: 'wikirule'):
var my_dict = JSON.parse($tw.wiki.getTiddlerText("my_json_tiddler"))
Related
I am passing a variable in my URL:
mydomain.com/app/?next_page=my_page
I can get this variable in a view with:
def mypage(request):
var = request.GET['next_page']
Is it best practice to also change the URL to require next_page? Something along the lines of:
path('app/?nextpage=<str>', mypage, name='my_page')
What's best practice? If so, what's the correct syntax for this (I know the example is incorrect)?
It depends on your needs.
Do not define a fixed url route; if you use the query parameters for filtering and there is more than one possible parameter
Example: "app/photos?size=100x100" and "app/photos/?color=blue"
Define a fixed url route; if it will be the same for each and every page, like details of a particular page:
Example: "app/orders/123123123" and "app/orders/123123123"
Btw, the correct syntax is:
path(app/<str:next_page>/, mypage, name="my_page")
You should take a look at path patterns. Enforcing a GET parameter in a path is not really a good practice. So if you want to require a username for example you can use:
path('bio/<username>/', views.bio, name='bio'),
You can find more patterns in Django documentation to catch strings, slugs, integers etc.
And in views you should define your function as such:
def mypage(request, username):
...code...
About GET:
Keep in mind that request.GET["value"] will raise a ValueError if that parameter does not exist. So you can catch that error to inform user that they are missing a parameter. (This will make this parameter obligatory.)
You can also use request.GET.get("value") which will return None if the key does not exist. If you want to use a default parameter you can use of course, request.GET.get("value", "default")
You can use as many parameters as you want in your link with or without path patterns. Their values will be stored in request.GET
Is there a way to format output that comes out from Django Rest Framework? What I'm looking for is a Django/DRF equivalent to PHP JSON_PRETTY_PRINT
Currently, the output looks like this:
{"id":1,"username":"bartalamej","city":"Ostrava","photo":"uploads/avatars/a84232eff3aa407db95ff792aec77414.jpg"}
But I'd like it to look like this:
{
"id":1,
"username":"bartalamej",
"city":"Ostrava",
"photo":"uploads/avatars/a84232eff3aa407db95ff792aec77414.jpg"
}
Does anybody know how to achieve this?
You should override the view's get_renderer_context and set an indent:
def get_renderer_context(self):
context = super().get_renderer_context()
context['indent'] = 4
return context
This will add an indent to the json.dumps call.
Alternatively, you can also leave that up to your client and add the indent within the Accept header as explained in the documentation
The BrowseableAPIRenderer formats JSON nicely for browsing. More information can be found here.
I have this code:
my_table = db.define_table('my_table',
Field('mt_table_id', 'id', requires=[IS_NOT_EMPTY()]),
I need to add something like requires= IS_LIST() to get a list e.g. ['a','b','c'] instead of ['a,b,c']. How is that done?
I ain't got what you meant, but perhaps you should look at custom validators section in web2py's book: http://www.web2py.com/books/default/chapter/29/07/forms-and-validators#Custom-validators
You may create a custom validator called IS_LIST() and change the "formatter" method to return a list in the way that you want.
Current solution:
example url:
http://localhost:3000/credit_cards?category=3
Application Route:
#controllerFor('creditCards').set 'content', App.CreditCard.find(category_id: getUrlParam('category'))
Get Url Params helper:
window.getUrlParam = (name) ->
paramsString = $(location).attr('search').substring(1)
urlParamsArray = paramsString.split('&')
for param in urlParamsArray
paramPair = param.split('=')
paramName = paramPair[0]
paramValue = paramPair[1]
return paramValue if paramName is name
Is there something better? Does Ember have it built-in out of the box?
Please note that Ember app is only a part of the app - it sits under its own root container. All the other elements are static.
Is there something better?
Depends. I'm assuming you need the query parameter because ember app is only part of your app. In that case your solution seems like a good one. Otherwise using a url like /credit_cards/3 instead would be better.
Does Ember have it built-in out of the box?
No. There is an experimental library available:
https://github.com/alexspeller/ember-query
Seems that might be overkill given how simple your example is, but if you are doing a lot of work with queryString I would recommend checking it out.
I am trying to output a set of database records in JSON as follows:
def json_dbtable(request, p):
t = MyModel.objects.filter({some query})
s = serializers.get_serializer("json")()
re = s.serialize(t, ensure_ascii=False)
return HttpResponse(re, mimetype="application/json")
However, one of the fields i'm trying to return needs to change if it is null, and to remedy this the model has a definition that is used as a property .e.g:
name = property(_get_useful_name)
So, to get to the crux of the question. How can I include this "name" property in my json serialization as well as the raw field data?
The short answer is no, the long answer, is you could serialize your MyModel instance yourself:
simplejson.dumps([{'pk': m.pk, 'name': m.name} for m in MyModel.objects.filter(...)])
I have written a serialization framework for Python called any2any
which include (de)serializers for Django
and which allows you to do that easily.
It will be way cleaner than the DIY way.
Hope that helps !