How to save an array of text in PostgreSQL using Django model.? - django

I am trying to save an array of text containing category types for a hotel system which looks something like this ['category-1', category-2', category-3, category-4] . I am using category_type = ArrayField(models.CharField(max_length=200),null=True) in my models.py
The error i get is
malformed array literal: "" LINE 1: ..., '{category-1,
category-2}'::varchar(200)[], ''::varcha...
^ DETAIL: Array value must start with "{" or dimension information.
The error persist even after processing python list from ['category-1', category-2', category-3, category-4] to {category-1, category-2, category-3, category-4}.
I have gone through postgresql documentation and have found very limited help,
https://pganalyze.com/docs/log-insights/app-errors/U114 this is something similar posted to what i am facing problem with.
Could someone please tell me what am i doing wrong? Any help would be appreciated.
EDIT:
Following is in my View.py
hotel_category=categoryTable(category_type=categorytype)
hotel_category.save()
and i am using categorytype=request.POST.getlist('category-type') in my Views.py to get it from the POST request after user submits the form. This returns a Python list that i have mentioned above, i have manipulated this list to match PostgreSQL ArrayField with '{','}' but i still have this error. If there is anything else you would like me to add, please let me know. :)

This is an update/answer to my question for anyone who faces this issue in the future. After struggling to find help from different resources, i decided to use JSON string to store my python list.
I am using :
categorytype = json.dumps(request.POST.getlist('category-type'))
to encode and using JSONDecoder() to fetch from database and decode. I have no idea how would this impact my further development but for now it seems a decent approach since personally i think ArrayFields are not well supported and documented in Django.
I will keep this post updated as i progress further on how this approach has impacted my development.
Have a nice day.

Related

How can I fix the internal error in Django?

I don't have a lot of experience in Django and I am a fairly green developer. When I run the localhost I keep getting a Internal Error. I have tried most of the solutions to similar problems here and none of them works. Can anyone help me? The code is not mine so I don't want to alter it as such either.
Here is a picture of the errors I keep getting:
The only thing you can do without altering the code is to enter the value "shop_all_art" in the HomePage table in the database.
Do not share code via images. You should also share the related code.
Your stacktrace clearly says, that Python is not able to access first element of HomePage.objects.filter(value='shop_all_art') in file bidgala/bidgala/pages/views.py. all_art_img is most probably empty.
Looks like all_art_img is empty.
you should check if a Query has any elements before with a method such as
if all_art_img.exists():
all_art_img[0]

Mongoid 4 finding embedded documents by ID

I have a project that is my first serious dive into Mongoid.
I saw a tip to use the following command:
Parent.where('childrens._id' => Moped::BSON::ObjectId(params[:id])).first
But this doesn't work. Error message was:
NameError: uninitialized constant Moped::BSON
I found that BSON is no longer included, so I added it to my Gemfile, as well as Moped. Then, I did another fix I found (placing Moped::BSON=BSON in application.rb).
This still didn't work, but the error changed to:
NoMethodError: undefined method `ObjectId' for BSON:Module
So I am assuming that this method got deprecated or something. Does anyone have any other tips?
Just to be clear, I am finding myself in the situation where I want to sort embedded documents using jquery-sortable. This requires me to update them in the database, but the serialize from that doesn't include the parent document in the hash. So I figured I'd try to get it on the back end using an ID from the embedded document. That is why I need it.
Thanks again for any help you can provide.
Try simply:
Parent.where('childrens._id' => params[:id]).first
I have solved the question though this won't be of much help to people in the future. The requirements have changed and now I am using human-readable strings as IDs to assist in friendly URLs and some other stuff.
Therefore, I don't have any issues with ObjectIds. Cortex's solution should (from what I have read) work for dealing with ObjectIds but I cannot verify it now.

Passing negative values as arguments to custom management commands in django

Like many others, I've been learning web development on django through building a test app. I've the basic models set up. I've populated a few of the tables with the absolute minimum data needed for further testing though using fixtures.
Now for a different table, I want to create data tuples through a custom management command which takes the required arguments. If this works as expected, I'll save the created data to the database by adding the --save option.
The syntax of the command is like this
create_raw_data owner_id temperature [--save]
where owner_id is required and temperature (in C) is optional. Within the Handle method, I'm using factory boy to create the raw_data with the given arguments etc.
I did have some issues but searching on SO, google, django docs etc, I've got the command working fine.
EXCEPT when I input a negative temperature...
Then I get the following error
Usage: C:\test\manage.py create_raw_data [options]
Creates a RawData object. Usage: create_raw_data owner_id temperature [--save]
C:\test\manage.py: error: no such option: -5
The code I have for parsing the args is like this
for index, item in enumerate(args):
if index == 0:
owner_id = int(item)
else index == 1:
temp = int(item)
I put a print(args) as the 1st line inside Handle but it seems the control is not even reaching here.
I'm not sure what is wrong... please help...
Thanks a lot
got the issue fixed so providing an answer to others who may come across this.
The issue was with parse_args method of optparse. I've read in a number of places that though optparse is deprecated and instead argparse is recommended, django recommends using optparse since that is what it uses. Long story short, the link at link suggested a few alternatives and using create_raw_data 1 -- -5 works as expected. So I did get a workaround. Thanks.

How do you access/configure summaries/snippets in Django Haystack

I'm working on getting django-haystack set up on my site, and am trying to have snippets in my search results roughly like so:
Title of result one about Wikis ...this special thing about wiki values is that...I always use a wiki when I walk...snippet value three talks about wikis too...and here's another snippet value
about wikis.
I know there's a template tag that uses Haystack code to do the the highlighting, but the snippets it generates are pretty limited:
they always start with the query word
there's only one snippet value
they don't support asterisk queries
and other stuff?
Is there a way to use the Solr backend to generate proper snippets as shown above?
Bottom line is that the Solr highlighting can't really be used by Haystack in a flexible way. I spoke to the main developer for Haystack on IRC, and he said basically, if I want to have the kind of highlighting I'm looking for, the only way to get it is to extend the Solr backend that Haystack uses.
I dabbled in that for about half a day, but couldn't get Haystack to recognize my custom back end. Haystack has some magic backend loading code that just wasn't working with me.
Consequently, I've switched over to sunburnt, which provides a lighter-weight and more extensible wrapper around Solr. I'm hoping it will fare better.
from haystack.utils import Highlighter
my_text = 'This is a sample block that would be more meaningful in real life.'
my_query = 'block meaningful'
highlight = Highlighter(my_query)
highlight.highlight(my_text)
http://docs.haystacksearch.org/dev/highlighting.html

django database sync problem

In my web django, I do a query of Models.objects.all() or actually any other models in the views.py. It returns me a [,] value (empty array) - view from logs. However back in the manage.py shell, it is able to retrieve the objects. In mysql database, the data entries are there!
I have no idea how to debug from here, is there a way to resolve this error? This is not my first time. I have been doing django project for several months already. Only today, it is giving me this problem.
EDIT : This problem is very weird, I'm just curious whether anybody has encountered this problem before, I'm using Eclipse to edit the scripts(views.py, models.py etc).
Do you have __repr__ defined for your objects? Take a look at the HTML source generated by Django -- there's a good chance it looks like:
[<Model: model object>, <Model: model object>, ...]
Your web browser then interprets the <...> as an HTML tag that it doesn't understand, and thus can't render, and displays only the content outside the tags (the "[", ",", and "]" characters).