Django CreateView object.id in get_succes_url pk(id) is NONE and then after redirecting to another URL it prints out created entry ID
I have a problem that I just can't figure out. After creating a work order I want to redirect to the detail page of that work order. Here is my models.py
class Radni_nalozi(models.Model):
Klijent = models.ForeignKey(Klijenti, on_delete=models.CASCADE)
Pacijent = models.CharField(max_length=100)
Rok_isporuke = models.DateField()
Cijena = models.FloatField(default=0)
Napomene = models.CharField(max_length=400,blank=True)
Zaduzenja = models.CharField(max_length=400,blank=True)
Status = models.CharField(max_length=50, choices=STATUS_CHOICES, default = "OTVOREN")
Aktivan = models.BooleanField(default=True)
def __str__(self):
return f"{self.id} - {self.Klijent}, {self.Pacijent}"
And here is my model form:
class RadniModelForm(BSModalModelForm):
class Meta:
model = Radni_nalozi
fields = ["Klijent","Pacijent","Rok_isporuke","Napomene","Zaduzenja"]
labels = {"Klijent":"Klijent: ", "Pacijent":"Pacijent: ", "Rok_isporuke":"Rok isporuke: ", "Napomene":"Napomene: ","Zaduzenja":"Zaduženja: "}
widgets = {'Rok_isporuke': DatePickerInput(options={
"locale":"en-gb",
})}
I want to create a new work order and I'm using django BSModalCreateView. Here is my views.py:
class RadniCreateView(LoginRequiredMixin,BSModalCreateView):
template_name = 'app/radni_nalozi/dodaj_rn.html'
form_class = RadniModelForm
def get_form(self):
form = super(RadniCreateView,self).get_form() #instantiate using parent
form.fields['Klijent'].queryset = Klijenti.objects.filter(Aktivan=1)
return form
def get_context_data(self, **kwargs):
context = super(BSModalCreateView, self).get_context_data(**kwargs)
context['title'] = 'NOVI RADNI NALOG'
context['gumb'] = 'KREIRAJ'
return context
def get_success_url(self):
print(self.object.pk)
return reverse_lazy('detalji_rn', kwargs={'pk': self.object.pk})
The command print(self.object.pk) returns NONE although the object is created. If I put some other hardcoded value in reverse_lazy function (for example number 13) then my view executes, it redirects to the hardcoded value and prints out command print(self.object.pk) two times, first with value NONE and then with the value of just created entry?
How can I access the pk of the created entry before the view is redirected so I could redirect to a detail page of that created entry (work order)?
Please help! Thanks in advance!
It seems that when get_success_url() is called the object cannot be obtained. I don't see any errors in the code, but I don't understand the usefulness of this line:
context = super(BSModalCreateView, self).get_context_data(**kwargs)
By changing the super() of the context you may be looking for the object in the wrong class. Maybe it works if you change it for this one:
context = super(RadniCreateView, self).get_context_data(**kwargs)