how to use array in django - python

I have a db table which has an integer array. But how can I add this field in my model? I tried writing it using IntegerField but on save it is giving error
int() argument must be a string or a number, not 'list
How can I add this field to my model? I am using this field in my views.py so I need to add it in my model. Any suggestions?

You may be interested in using a CommaSeparatedIntegerField.
If you've got a list of integers like this:
my_ints = [1,2,3,4,5]
and a model like this:
class MyModel(models.Model):
values = CommaSeparatedIntegerField(max_length = 200)
then you can save my_ints into a MyModel like this:
m = MyModel(values = ','.join(my_ints))
m.save()

I would look into database normalization. In particular, your database is not even in 1st normal form, the first and probably most significant of the normal forms which states that normalized data should not contain any repeating groups. As a result, the Django object-relational-mapper will have considerable difficulty modeling your data.
By supporting only single, non-repeating types, Django in a sense enforces 1st normal form in data. You could try to write your own SQL to manage this particular field or perhaps find some code on the internet, but perhaps better would be to refactor this field into a many-to-one relationship in its own model. You can find Django documentation on this here.

Clueless' answer is probably the best you can get, but in case you still want to store array of numbers in single field, you can do this - either by manually e.g. pickling it and then storing to TextField, or by writing custom model field that do something like this for you automatically.
Here's the doc: http://docs.djangoproject.com/en/1.1/howto/custom-model-fields/

I got it working by saying textfield in my model.Since i am only using that field for reading it doesnot effect me

Related

Django ForeignKey form field widget

First of all I have tried to research my problem but have not been able to find what I need. My problem might be related to the design of my project (any help would be appreciated).
The problem I am facing is as follows:
I have a few models
I have a model that would be used specifically to create a ModelForm
In this model I have ForeignKey field that is represented by default as a select/option input widget in the ModelForm (for each the value attribute is the ForeignKey and text between the tags is the __str__() of the model the ForeignKey points to. The user sees the __str__() and value attribute of the option tag is submitted which is great).
So far so good but I want to replace the widget with an input text field so I can implement it as a search field.
Now when the user submits the form the string entered in the text input field is submitted and of course django doesn't like that since it expects a foreign key
I already can think of a few solutions to the problem and I am sure I can make it work but each of them feels like I would be violating some best practices. So my question is what should I do?
Do I exclude this particular field from the ModelForm and implement it as an input text field then after form submission make a query with it's value and then store the ForeignKey to the DB
Do I manipulate the data with JavaScript upon submission so that Django receives correct information
Can I clean this fields data with Django and transform it from string to FK?
Am I going the wrong way with this or there is a Django feature for this type of situation?
If anyone has the same problem here is the solution (to my problem at least):
I tried to use the clean_<fieldname> method to change the user entered string to database id. The method wasn't executing because the validation process was stopping earlier because of the difference between the form field and the widget. I redefined the form field to CharField so that step of the validation was working and then the clean_<fieldname> method executes without a problem.

Can't create a form to upade part of a model field

This is really frustrating,
I can't and can't find how to create a form (I'm guessing a forms.Form form) to update just one field of a more complex model.
The model has 5 fields, and a form to create, update all of them.
But in a different case i need to let the user update only the title (a field in the model), so i need tried so many things until now (including creating an HTML form by hand and from the view to save it, creating a forms.Form and many more, nothing seem to work), There is no code here because i don't even know which one to put....
Maybe some one can help me with that, I'm sure it is a simple thing, But for some reason i am stuck on this for a long time...
Thank you,
Erez
If you're using ModelForms, you just have to define a fields attribute in Meta as a tuple containing just the names of the fields you want. See the documentation.

data validation for SQLAlchemy declarative models

I'm using CherryPy, Mako templates, and SQLAlchemy in a web app. I'm coming from a Ruby on Rails background and I'm trying to set up some data validation for my models. I can't figure out the best way to ensure, say, a 'name' field has a value when some other field has a value. I tried using SAValidation but it allowed me to create new rows where a required column was blank, even when I used validates_presence_of on the column. I've been looking at WTForms but that seems to involve a lot of duplicated code--I already have my model class set up with the columns in the table, why do I need to repeat all those columns again just to say "hey this one needs a value"? I'm coming from the "skinny controller, fat model" mindset and have been looking for Rails-like methods in my model like validates_presence_of or validates_length_of. How should I go about validating the data my model receives, and ensuring Session.add/Session.merge fail when the validations fail?
Take a look at the documentation for adding validation methods. You could just add an "update" method that takes the POST dict, makes sure that required keys are present, and uses the decorated validators to set the values (raising an error if anything is awry).
I wrote SAValidation for the specific purpose of avoiding code duplication when it comes to validating model data. It works well for us, at least for our use cases.
In our tests, we have examples of the model's setup and tests to show the validation works.
API Logic Server provides business rules for SQLAlchemy models. This includes not only multi-field, multi-table validations, but multi-table validations. It's open source.
I ended up using WTForms after all.

Django - Automatically Assign Cleaned Data to Database Fields

The usual way I do form handling is like this:
contact = Contact(
name=form.cleaned_data['name'],
email=form.cleaned_data['email'],
message=form.cleaned_data['message'],
newsletter=form.cleaned_data['newsletter']
)
but for long forms, this obviously is a tedious task. I was wondering if there was any Django method I might have missed that automatically assigns the cleaned data to their corresponding column in the database table that I don't have to manually assign them.
Any ideas? Thanks in advance!
Django offers you a Modelform class that was desgined for exactly this task.

Get POST data from a complex Django form?

I have a Django form that uses a different number of fields based on the year/month. So I create the fields in the form like this:
for entry in entry_list:
self.fields[entry] = forms.DecimalField([stuffhere])
but now I don't know how to get the submitted data from the form.
Normally I would do something like:
form.cleaned_data["fieldname"]
but I don't know what the names of the fields are. The debug screen shows my POST data as simply "Entry Object" with a value of "u''". Calling POST.lists() doesn't show anything.
I am sure I am missing something obvious, but I've been stuck on this for a few days too many. Is there a better way to do this? Is all of the data in the request object, but I just don't know how to use it?
Here is the code for the model/form/view: http://pastebin.com/f28d92c0e
Much Thanks!
EDIT:
I've tried out both of the suggestions below. Using formsets was definitely easier and nicer.
I think you might be better off using formsets here. They're designed for exactly what you seem to be trying to do - dealing with a variable number of items within a form.
In this line:
self.fields[entry] = forms.DecimalField(max_digits=4, decimal_places=1, label=nice_label)
entry is a model instance. But fields are keyed by field names (strings). Try something like:
self.fields[entry.entry_name] = forms.Decimal(...)
(substitute appropriate for "entry_name").

Categories