I created a form for creating a new item in Django. The app should be redirected to item_new
but it's not working. This below error occurs.
Page not found http://127.0.0.1.8000/item/new
show.html
<form
action="{% url 'item_new' %}"
method="POST"
enctype="multipart/form-data"
>
{% csrf_token %}
<div class="formItem">
<label>Name</label>
<input type="name" name="name" />
</div>
<div class="formBtn">
<input type="submit" class="btn btnPrimary" value="Submit" />
</div>
</form>
urls.py
urlpatterns = [
path('item/<slug:slug>/', views.item_detail, name='item_detail'),
path('item/new/', views.item_new, name='item_new'),
]
views.py
def item_detail(request, slug):
item = get_object_or_404(Item, slug=slug)
return render(request, 'item/show.html', {'item': item})
def item_new(request):
return redirect('home')
In your urls.py
file, change the order of lines. Like this:
urlpatterns = [
path('item/new/', views.item_new, name='item_new'),
path('item/<slug:slug>/', views.item_detail, name='item_detail'),
]
The order of urls, does matter. In your current situation, requests made to http://127.0.0.1.8000/item/new
will be sent to item_detail
view function instead of item_new
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.