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,))
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With