I've got the same problem as in 'https://stackoverflow.com/a/79063022/22401844', user data doesn't seem to be displayed as planned in the target URL. These are the codes used:
This is the view.py code:
from django.shortcuts import render, HttpResponseRedirect
from django.urls import reverse
from django import forms
# Item list
items = ['earbuds', 'rollerblades', 'camera']
class OrderForm(forms.Form):
product = forms.CharField(label='Product', max_length=50)
def index(request):
return render(request, 'card/card.html', {
'items': items,
})
def order(request):
if request.method == 'POST':
form = OrderForm(request.POST)
if form.is_valid():
product = form.cleaned_data['product']
items.append(product)
return HttpResponseRedirect(reverse('card:carditems'))
else:
return render(request, 'card/order.html', {
'form': form,
})
return render(request, 'card/order.html', {
'form': OrderForm()
})
This is the order.html where the user will fill in his order:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Order</title>
</head>
<body>
<h2>Order Here</h2>
<form action="{% url 'card:carditems' %}" method="post">
{% csrf_token %}
{{form}}
<input type="submit" value="submit">
</form>
</body>
</html>
And this is the card.html code which handle the added orders display:
{% extends 'card/layout0.html'%}
{% load static %}
{% block content %}
<h2>Card Items</h2>
<ul>
{% for item in items %}
<li> {{ item }} </li>
{% endfor %}
</ul>
{% endblock %}
And this is the urls.py code :
from . import views
from django.urls import path
app_name = "card"
urlpatterns = [
path('', views.index, name='carditems'),
path('order/', views.order, name='order')
]
I tried the same solution suggested in my similar previous problem but it didn't work.
The problem is with action attr of your html, you sending request to carditems
. It's a views.index
view. But you need to send request to views.order
view. So just change attr of your actions:
<form action="{% url 'card:order' %}" method="post">
{% csrf_token %}
{{ form }}
<input type="submit" value="Submit">
</form>
Also I would suggest to render form items by form.as_p for better look