Joe
Joe

Reputation: 239

django: Issue with the url paths

I need little help with how to redirect the link to the right url. I have one object that has 2 categories rents and sales. When the form is submitted I can successfully redirect the user to the right place but that is from the views --- return redirect(category +'/'+ listing_id) ---

Any trick how can I do the same from the HTML? Any help is appreciated!

urls.

path('rents/',rents, name = 'rents'),
path('rents/<int:pk>',RentView.as_view(), name = 'rent'),
path('sales/',sales, name = 'sales'),
path('sales/<int:pk>',SaleView.as_view(), name = 'sale'),

html:

First one has url localhost/dashboard/sales/1 . It should be localhost/sales/1, but I'm not sure how to remove that dashboard. Since the current page is dashboard.

<td class="column3"><a href = "{{contact.category}}/{{ contact.listing_id}}" ><button class='btn-view'>View</button></a></td>

Second case: I have two categories: sales and rents. It seems to work if I leave it like this, but if there is a query from rents it will redirect the URL to sales.

<td class="column3"><a href = "{% url 'sale' contact.listing_id %}" ><button class='btn-view'>View</button></a></td>

Upvotes: 0

Views: 36

Answers (1)

Nahidur Rahman
Nahidur Rahman

Reputation: 815

You are missing the / in href which is the cause of "dashboard" being added in the URL "localhost/dashboard/sales/1". To resolve the issue just add a / like following.

<td class="column3"><a href = "/{{contact.category}}/{{ contact.listing_id}}" ><button class='btn-view'>View</button></a></td>

For the second case you can use if template tag like following.

{% if contact.category == "sales" %}
    <td class="column3"><a href = "{% url 'sale' contact.listing_id %}" ><button class='btn-view'>View</button></a></td>
{% else %}
    <td class="column3"><a href = "{% url 'rent' contact.listing_id %}" ><button class='btn-view'>View</button></a></td>
{% endif %}

Or you can pass the name of URL from view based on category.

<td class="column3"><a href = "{% url url_name contact.listing_id %}" ><button class='btn-view'>View</button></a></td>

Ensure that you pass "url_name" in the context from view function/method.

Upvotes: 1

Related Questions