Reputation: 393
All my urls in the app "products" redirects to products_list
urls.py
from django.conf.urls import url
from .views import(
product_list,
search,
add_product,
category_single,
manage_product_image,
edit_product,
download_product,
single,
)
app_name = 'products'
urlpatterns = [
url(r'^', product_list, name='product-list'),
url(r'^search/',search, name="search"),
url(r'^add/',add_product,name='add_product'),
url(r'^category/(?P<slug>.*)/$',category_single,name="category"),
url(r'^(?P<slug>.*)/images/',manage_product_image,name="manage_product_image"),
url(r'^(?P<slug>.*)/edit/',edit_product,name="edit_product"),
url(r'^(?P<slug>.*)/download/(?P<filename>.*)$',download_product,name="download_product"),
url(r'^(?P<slug>.*)/$',single,name="single_product"),
]
if i type http://localhost:8000/products
it sends me to the list of products which is perfect ,but typing http://localhost:8000/products/add/
also sends me to the product list which is not perfect it should be to the form to add products.
views.py
def add_product(request):
form = ProductForm(request.POST or None)
if form.is_valid():
product = form.save(commit=False)
product.user = request.user
product.slug = slugify(form.cleaned_data['title'])
product.active = False
product.save()
return HttpResponseRedirect('/products/%s'%(product.slug))
context = {
'form':form,
}
return render(request,"products/edit.html",context)
I have tried to comment all lines of code in the view.py just to render the template still does not come through ,just brings the product list.
Upvotes: 1
Views: 131
Reputation: 417
In your first url(r'^')
, you need to add an end of string anchor ($)
Like this:
urlpatterns = [
url(r'^$', product_list, name='product-list'),
# ... All other urls here.
]
Also why don't you use something like path(r'^add/', add_product, name='add-product')
, where you don't need an end of string anchor ($) like this:
from django.urls import path
from .views import(
product_list,
search,
add_product,
category_single,
manage_product_image,
edit_product,
download_product,
single,
)
app_name = 'products'
urlpatterns = [
path(r'^$', product_list, name='product-list'),
path(r'search/',search, name="search"),
path(r'add/',add_product,name='add_product'),
path(r'category/(?P<slug>.*)/$',category_single,name="category"),
path(r'(?P<slug>.*)/images/',manage_product_image,name="manage_product_image"),
path(r'(?P<slug>.*)/edit/',edit_product,name="edit_product"),
path(r'(?P<slug>.*)/download/(?P<filename>.*)$',download_product,name="download_product"),
path(r'(?P<slug>.*)/$',single,name="single_product"),
]
Upvotes: 1
Reputation: 476503
Your first url(..)
[Django-doc] pattern is a pattern that matches everything. Indeed the regex ^
matches all strings since you only specify the string start anchor.
You should add an end of string anchor ($
) as well:
urlpatterns = [
url(r'^$', product_list, name='product-list'),
# ...
]
Upvotes: 3