Django : array within a query string as foo[]=bar1&foo[]=bar2 - arrays

I need to prepare a Django microservice that offer the following url pattern :
http://<myserver>/getinfo/?foo[]=bar1&foo[]=bar2
it seems to be a very PHP way of doing but i have to mimic it in django ...
Is there a standard way in Django for both designing the URL and retrieving the querystring parameter as a list in the View ?

wrt/ "designing the url", Django's urlpatterns ignore the querystring (they only match on the path), so you don't have anything to do here.
wrt/ retrieving the querystring params as a list, that's already handled by Django's QueryDict:
QueryDict.getlist(key, default=None)
Returns a list of the data with the requested key. Returns an empty list if the key doesn’t exist and a default value wasn’t provided. It’s guaranteed to return a list unless the default value provided isn’t a list.
NB: forgot to add that Django will not automagically remove the brackets from the key so you'll need foos = request.GET.getlist("foo[]") (thanks Daniel Roseman)

Related

Wagtail Search in CMS

I'm trying to search through all of my pages on the backend to find instances of urls with outdated domain names. But when I search, it only seems to get hits based on the title of the pages, and not their content. Is there something I need to configure to make this work?
Thank you!
To search on fields beyond the ones that are common to all page types (such as title), you'll need to define a search_fields property on your page model, such as:
from wagtail.search import index
class MyPage(Page):
body = StreamField(...)
search_fields = Page.search_fields + [
index.SearchField('body')
]
After setting this up, you'll need to update the search index to contain this new data, by running ./manage.py update_index.
If you're running 2.14.x or earlier, you'll also need to set up an alternative search backend such as Postgres or Elasticsearch - the default wagtail.search.backends.db search backend was very limited and only supported searching on the 'core' fields such as title. As of 2.15, a new wagtail.search.backends.database backend is available and enabled on new projects out of the box, and this has full support for searching across all fields.

how to make django post accept str rather than pk

I have relational DB and a file info to post in it.
DB provides 3 entities holding ForeignKey in some attributes.
Entities are:
File, WorkFile and WorkFileStage
My issue is, when I post info of specific file, I must post on those endpoints, but e.g. WorkFile holds attribute file = ForeignKey(File) - it's an id filed. Which makes me POST all the File data, then GET it for acquring IDs, then POST on WorkFile with those IDs.
THIS IS A LOT OF POSTINGGETINGITERATINGANDPROMISING (as my request are done with axios on react).
What I've tried, is for POST data construct object with just a file=file_name, then search it in the DB on the Django side and serialize.save(). But POST requires pk rather than str for foreignKeys.
With this though process I ended up with:
axios.post().then(axios.get().then(axios.post(then))))
Is there any easy/good practice way of doing it?
Django's POST view can accept whatever you want. As for querying your models via related model properties, check the official documentation: https://docs.djangoproject.com/en/3.1/topics/db/queries/#lookups-that-span-relationships
In your case it should be something like this:
def my_post_view(request, file_name):
try:
work_file = WorkFile.objects.get(file__name=file_name)
except WorkFile.DoesNotExist:
raise Http404
...
where file_name is passed as a part of your endpoint URL.

SuiteCommerce Advanced - Show a custom record on the PDP

I am looking to create a feature whereby a User can download any available documents related to the item from a tab on the PDP.
So far I have created a custom record called Documentation (customrecord_documentation) containing the following fields:
Related item : custrecord_documentation_related_item
Type : custrecord_documentation_type
Document : custrecord_documentation_document
Description : custrecord_documentation_description
Related Item ID : custrecord_documentation_related_item_id
The functionality works fine on the backend of NetSuite where I can assign documents to an Inventory item. The stumbling block is trying to fetch the data to the front end of the SCA webstore.
Any help on the above would be much appreciated.
I've come at this a number of ways.
One way is to create a Suitelet that returns JSON of the document names and urls. The urls can be the real Netsuite urls or they can be the urls of your suitelet where you set up the suitelet to return the doc when accessed with action=doc&id=_docid_ query params.
Add a target <div id="relatedDocs"></div> to the item_details.tpl
In your ItemDetailsView's init_Plugins add
$.getJSON('app/site/hosting/scriptlet.nl...?action=availabledoc').
then(function(data){
var asHtml = format(data); //however you like
$("#relatedDocs").html(asHtml);
});
You can also go the whole module route. If you created a third party module DocsView then you would add DocsView as a child view to ItemDetailsView.
That's a little more involved so try the option above first to see if it fits your needs. The nice thing is you can just about ignore Backbone with this approach. You can make this a little more portable by using a service.ss instead of the suitelet. You can create your own ssp app for the function so you don't have to deal with SCAs url structure.
It's been a while, but you should be able to access the JSON data from within the related Backbone View class. From there, within the return context, output the value you're wanting to the PDP. Hopefully you're extending the original class and not overwriting / altering the core code :P.
The model associated with the PDP should hold all the JSON data you're looking for. Model.get('...') sort of syntax.
I'd recommend against Suitelets for this, as that's extra execution time, and is a bit slower.
I'm sure you know, but you need to set the documents to be available as public as well.
Hope this helps, thanks.

Support for query parameters in Dart for Google Endpoints?

I have a Dart application that's getting data from a custom Google endpoint. I'm using discoveryapis_generator to generate the client library. I would like to issue a query like the following:
import endpoints_api.dart as EndpointsApi;
api = new EndpointsApi.MyApi();
api.photos.list(api.Photo.post_id == "post1");
endpoints_api.dart is the client library generated by discoveryapis_generator generate.dart. MyApi is my custom endpoints API, and photos is one of its services. I think Photo is an endpoints model class which has an instance property post_id.
Issuing the request results in an error to the effect that Photo has no static getter "post_id". This is close to how to the syntax of a query in the Python API, so it was the only way I could think of to specify it here.
I don't know what else might be helpful in describing my request. Hopefully it is self-evident. There's an active enhancement described here, but it seems to refer to limiting the fields, rather than items, in the response.
Update:
Poking around in the client library, I found the source for the list methods. It certainly looks like query parameters are supported. But it seems to me that it's not entirely correct. The formal parameter list contains the query parameters specified in the API surrounded by braces:
async.Future<PhotoCollection> list({core.String postId, core.String regionId}) {...
But in the method body, there's the following:
if (regionId != null) {
_queryParams["region_id"] = [regionId];
Are the brackets in [regionId] to extract region from the parameter list?
I pulled the braces out of the parameter list. Since I only ever expect to query by postId, that's the only parameter:
async.Future<PhotoCollection> list(core.String postId) {...
Voila. I can now add a parameter to the query by just specifying its value in the call:
api.photos.list("post1");
If you wrap the parameters of a method in curly braces, you make them optional.
So you can still use your method with the given signature. You just have to add the name of the parameter you want to pass:
api.photos.list(postId: "post1");

Dynamic queryset for foreignKey in Single Page Application with Django

I have a single page application with AngularJs and Django. On my main page, I get all the forms needed when loading the page. BUT, some fields are dynamically updated.
Let's say I have
class Model1(models.Model):
pass
class Model2(models.Model):
model_1 = models.ForeignKey(Model1)
forms:
class Model2Form(forms.ModelForm):
class Meta:
model = Model2
fields = ('model_1', )
My SPA allows me to create instances of Model1 (without reloading the page). I know how to filter the options shown and dynamically add the new instances in the select field BUT, doing so, when the html is first rendered, before angular magic takes place and filter the available options, I get the queryset made by django which is by default model.objects.all(). All right, I'd like to display none of that. I tried to add in the init of my function:
self.fields['model_1'].queryset = Model1.objects.none()
and indeed no option is displayed in the select field when the form is first rendered but then, I can't validate my form, I get the error: Select a valid choice. That choice is not one of the available choices. (obviously, it had no option available due to the queryset.none() )
I'd really like not to load forms when called but doing it when my page first load. Is there any option to help me do so?
Cheers guyz,
Keep rocking
You need to specify that the model_1 field of Model2 can be null, as specified here:
Allow null in foreign key to user. Django
model_1 = models.ForeignKey(Model1, null=True, blank=True, default = None)
I find out how to handle that problem. It is quite stupid, I did not give you all the parameters of the problem.
The forms are rendered on load but when I validate it, it goes through a CRUD operation and an OTHER form is initialized at this point which will handle the data I'm sending. So I can override the queryset in the init of that (second) form based on some extra kwargs to differentiate between the form I'm using for the first rendering and the form to handle my data.
No need to make any field nullable or add extra validation.
Hope I'm clear enough. Cheers

Resources