Home > OS >  Django get_absolute_url calling same URL as current page
Django get_absolute_url calling same URL as current page

Time:12-21

I am trying to add a " New Review" link to a page on my Django site that will take you to a 'uuid:pk/new_review/' page that houses a form to submit a URL for a specific post. I am currently facing issues where the link is redirecting to the same page, and I think the issue is stemming from my use of get_absolute_url(), which I am still having trouble getting my head around.

urls.py

urlpatterns = [
    path('<uuid:pk>/', ListingDetailView.as_view(), name = 'listing_detail'),
    path('<uuid:pk>/new_review/', NewReview.as_view(), name = 'new_review'),
]

views.py

class ListingDetailView(LoginRequiredMixin, DetailView):
    
    model = Listing
    template_name = 'listing/listing_detail.html'
    context_object_name = 'listing_detail'
    login_url = 'account_login'

class NewReview(LoginRequiredMixin, CreateView):

    model = Review
    template_name = 'listing/new_review.html'
    fields = ['review']
    context_object_name = 'new_review'

    def form_valid(self, form):
        form.instance.user = self.request.user
        form.instance.listing_id = get_object_or_404(Listing, pk = self.kwargs['pk'])
        return super().form_valid(form)

models.py

class Review(models.Model):

    listing_id = models.ForeignKey(
        Listing,
        on_delete=models.CASCADE,
        related_name='reviews',
    )

    user = models.ForeignKey(
        get_user_model(),
        on_delete=models.CASCADE,
    )

    review = models.TextField(max_length=5000)

    def __str__(self):
        return self.listing_id

    def get_absolute_url(self):
        return reverse('listing_detail', args=[str(self.listing_id)])

listing_detail.html

...
    <p><a href="{{ new_review.get_absolute_url }}">  New Review</a></p2>
...

CodePudding user response:

The issue is not get_absolute_url itself: that will return an empty string, since there is no new_review in the context.

You should work with:

<a href="{% url 'new_review' pk=listing_detail.pk %}">  New Review</a>
  • Related