'Why would object.pk be None in get_success_url in CreateView?
I have a CreateView to which after creation I'd like the user to be directed to the DetailView for that newly created instance.
class ModelCreateView(LoginRequiredMixin, CreateView):
model = Model
template_name = 'models/model-create-template.html'
In my get_success_url method, I use self.object.pk, but it is None.
def get_success_url(self):
return f'/model/{self.object.pk}'
class ModelCreateView(LoginRequiredMixin, CreateView):
model = Model
template_name = 'models/model-create-template.html'
def form_valid(self, form):
form.instance.user = self.request.user
return super().form_valid(form)
def get_success_url(self):
return f'/model/{self.object.pk}'
Model for reproduction:
class Model(models.Model):
id = models.IntegerField(primary_key=True)
Using this model with the code above will reproduce that self.object.pk or self.object.id is None within get_success_url.
I can see that I reach a successful save() since my post_save signals are firing, and form_valid() is called as well, since I update the user in this method.
When I look in my debugger at self.object, all of the other fields are populated, by id and pk are both None. Looking at the instance in admin, I can confirm these are actually being set correctly, but for some reason at the time of calling get_success_url I don't have access to this data.
Is the instance in self.object actually the created instance, or is it just representing the fields submitted by the CreateView form? If its the former, how could I access the instance in get_success_url?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
