[Solved]-Django success url using kwargs


form_valid should return a HttpResponseRedirect https://github.com/django/django/blob/master/django/views/generic/edit.py#L57 which in your case, you never do. I dont know if you have any code after #save, but take a look at the comments I made in your code

class CalcUpdate(SuccessMessageMixin, UpdateView):
    model = Calc
    template_name = 'calc/cru_template.html'
    form_class = CalcForm

    def archive_calc(self, object_id):
        model_a = Calc.objects.get(id = object_id)
        model_b = Calc()

        for field in model_a._meta.fields:
            setattr(model_b, field.name, getattr(model_a, field.name))
        model_b.pk = None

        return self.get_success_url(idnumber = model_b.pk) # you never return this value

    def form_valid(self, form):
        if self.object.checked == True:
            object_id = self.object.id
            return HttpResponseRedirect(self.archive_calc(object_id)) # you never return a `HttpResponse`
        #save  -- If this is where you are saving... you can store the value from archive and return it after saving

    def get_success_url(self, **kwargs):         
        if  kwargs != None:
            return reverse_lazy('detail', kwargs = {'pk': kwargs['idnumber']})
            return reverse_lazy('detail', args = (self.object.id,))

Also you don’t need to manually copy the fields, just do (assuming there are no unique constraints because if there were, your version would fail too):

    def archive_calc(self, object_id):
        c = self.model.objects.get(id = object_id)
        c.pk = None

        return self.get_success_url(idnumber = c.pk)


After playing around with @Ngenator’s answer and various other posts on here I have the following working code. However its not very nice to look at 🙁

def get_success_url(self):
    if self.pknumber != None:
        return reverse_lazy('pstdetail', args = (self.pknumber,))
        return reverse_lazy('pstdetail', args = (self.object.id,))

I have this self.pknumber = model_b.pk in the necessary place within the view and self.pknumber = None else where to enable the if statement to build the required url. Hope this helps anyone and feel free to point out any errors/improvements.




You cannot pass parameters in get_success_url(self) method. You can only refer to self parameter. For example self.kwargs['pk'].

Leave a comment