[Django]-No URL to redirect to. Either provide a url or define a get_absolute_url method on the Model

25👍

The best way to do this is to add a method get_success_url on the create view and use that to redirect back to the detail view. In the create view you have the object after it is saved, like so

class LawyerReviewCreate(CreateView):
    def get_success_url(self):
        return reverse('lawyer_detail', kwargs={'lawyer_slug': self.object.lawyer_slug})

This will then automatically send the user back to the detail view if the form is valid.

Also, make sure your kwargs is using the correct key, it would appear that you are using review_slug in some cases and lawyer_slug in other cases

7👍

We can follow Django’s suggestion and add a “get_absolute_url” to our model. It sets a canonical URL for an object so even if the structure of your URLs changes in the future, the reference to the specific object
is the same. In short, you should add a get_absolute_url() method to
each model you write.

def get_absolute_url(self): # new
    return reverse('lawyer_detail', args=[str(self.id)])

This should solve your problem

Leave a comment