tags:

views:

136

answers:

2

I installed Django for the first time yesterday and trying it out in earnest today. I'm only planning to use it for the beautiful admin interface, Zend Framework for the rest.

I imported an existing table event into the admin. There's no join needed. But the primary key is not 'id' it's called "event" (following this naming convention). I obviously don't want this column's id# to appear in the data entry form.

Everything works fine, EXCEPT when adding a new event, I click Save and Continue Editing, it adds the event, but redirects the URL to http://127.0.0.1:8000/admin/events/event/None/ and spits out this error

ValueError at /admin/events/event/None/

invalid literal for int() with base 10: 'None'

This is my models.py:

from django.db import models

class Event(models.Model):
    event = models.IntegerField(primary_key=True)
    title = models.CharField(max_length=150)
    address_1 = models.CharField(max_length=150)
    url = models.URLField(max_length=500,verify_exists=False)
    start_date = models.DateField()
    end_date = models.DateField()
    ACTIVE_CHOICES = (
        (0, 'InActive'),
        (1, 'Active'),
    )
    active = models.CharField(max_length=1, default=1, choices=ACTIVE_CHOICES)
    def __unicode__(self):
        return self.title
    class Meta:
        db_table = u'event'

Any ideas what I'm doing wrong or how to fix this?

+4  A: 

You probably want the PK to be an AutoField instead of an IntegerField so Django will automatically fill it in for you. Otherwise you have to do it yourself in the save method or the admin interface:

class Event(models.Model):
    event = models.AutoField(primary_key=True)
Steve Losh
Bingo! Thanks again!
joedevon
+2  A: 

This isn't a fix, but hopefully it can help shed light on this situation.

Behind the scenes when you hit "Save and Continue" what's happening is there are 2 URLs that are accessed...

/admin/events/event/add/
/admin/events/event/{id of newly created element}/

If you look at the error your getting, the URL that is' choking on is '/admin/events/event/None/'. Note how where the id should be there is the value of 'None'? It means that when a new record is created it probably isn't having a value set for 'event' (the pk).

If you were to check your SQL database you'd probably see the event column was null.

Steve Losh just posted the code (as I was typing) on how to solve this so I'll end my answer here.

T. Stone
Thanks for responding T. I noticed that, but what puzzled me was that it added the record correctly. But now that you explain it, all makes sense. A NULL value in MySQL on an autoincrement key works...I thought django would pull the LAST_INSERT_ID (can you link from a comment? http://dev.mysql.com/doc/refman/5.0/en/getting-unique-id.html). I hope it isn't calculating the highest id and incrementing it and sending the value to MySQL. That can fail sometimes.
joedevon