Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't self.object in a CreateView have an id after saving to the database?

Following the comment on the accepted answer on django createview how to get the object that is created, I am attempting to use the id from a user created by a CreateView in its get_success_url method. However, even though it is definitely being saved to MySQL and receiving an id, when I access self.object, it doesn't have an id to use. The model does have an id property. Why wouldn't I be able to access the id? If I'm being led astray by the linked comment, what is the right way to get the id?

Reference code:

models.py

from django.db import models

class User(models.Model):
    id = models.IntegerField(primary_key=True)
    name = models.CharField(max_length=128)
    active = models.BooleanField(blank=True)
    created_date = models.DateTimeField()
    class Meta:
        managed = False
        db_table = 'user'
    def __unicode__(self):
        return self.name

views.py

from django.views.generic import CreateView
from django.core.urlresolvers import reverse
from forms import AddUserForm

class AddUserView(CreateView):
    form_class = AddUserForm
    fields = ['name', 'active'] # id and created_date are auto-filled upon save
    template_name = 'webApp/add_user_form.html'

    def get_success_url(self):
        print self.object # Prints the name of the submitted user
        print self.object.id # Prints None
        return reverse("webApp:user:stepTwo", args=(self.object.id,))
like image 918
ZAD-Man Avatar asked Aug 08 '14 21:08

ZAD-Man


1 Answers

It's blank because the object is not actually receiving an id. That's because the id field should be an AutoField, not IntegerField, so that it is declared as auto-incrementing.

Actually though you should not declare it at all: an primary key AutoField named id is the default, so you should leave it out.

Note you'll need to migrate your database table, or drop and recreate it, after you make this change.

like image 149
Daniel Roseman Avatar answered Nov 12 '22 07:11

Daniel Roseman