I wanted to add another model to my Django application. I'm storing using Postgres. There's nothing serious about this -- it's fairly simple. Still, I encountered an error.
The Problem
I don't have the exact error on-hand at the moment, but essentially, Django was trying to store data submitted by form in my Postgres database. When I added a new model for a field and tried submitting a completed form with the new field included, Django raised an error because the Postgres column of the new field didn't exist.
The Solution
A new column needed to be created in the Postgres database prior to rendering/submitting the form. Even if the form displays, storage is a separate process from rendering, so the database tables need to be on the same page as the Django models.
To add the column, you can use South to perform a database migration.
OR
You can go with manually adding the column via the Postgres shell.
Example Django application name: Ads
Initial Django model:
class DooSomething(models.Model): name = models.CharField(max_length=50) email = models.EmailField() category = models.CharField(max_length=3, choices=CATEGORIES) expire = models.DateField()
Initial Postgres table:
CREATE TABLE ads_doosomething ( id serial NOT NULL, name character varying(50) NOT NULL, email character varying(75) NOT NULL, category character varying(50) NOT NULL, expire date NOT NULL, CONSTRAINT ads_doosomething_pkey PRIMARY KEY (id) )
Final Django model:
class DooSomething(models.Model): name = models.CharField(max_length=50) email = models.EmailField() category = models.CharField(max_length=3, choices=CATEGORIES) location = models.CharField(max_length=3, choices=LOCATIONS) #THE CHANGE expire = models.DateField()
Go to your Postgres shell and connect to the appropriate database (the one with your table in it).
Once connected, enter the following, with the appropriate substitutions:
ALTER TABLE ads_doosomething ADD COLUMN <model_name [postgres restraints]>;
In the case of our above model, we want to add the location field with a 3-char restraint. Therefore:
ALTER TABLE ads_doosomething ADD COLUMN location varchar(3);
Everything should work now.
I miss you, Renee. It's insane. Going to keep driving. A lot more to work for.