Reputation: 665
I have started learning Django a few days ago, I'm not sure how I can handle form url.
myproject/urls.py file as follows.
from django.conf.urls import url, include
from django.contrib import admin
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^form/', include('app.urls'))
]
Here is myproject/app/urls.py file.
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.get_name, name = 'get_name'),
url(r'^/your-name/$', views.your_name, name = 'your_name')
]
Here is app/views.py file.
from __future__ import unicode_literals
from django.shortcuts import render
from django.http import HttpResponse, HttpResponseRedirect
from .forms import NameForm
def get_name(request):
if request.method == 'POST':
form = NameForm(request.POST)
if form.is_valid():
return HttpResponseRedirect('/thanks/')
else:
form = NameForm()
return render(request, 'name.html', {'form' : form})
def your_name(request):
return HttpResponse("Hello, world.")
app/forms.py file.
from django import forms
class NameForm(forms.Form):
your_name = forms.CharField(label='Your name', max_length=100)
app/name.html file.
<form action="/your-name/" method="post">
{% csrf_token %}
{{ form }}
<input type="submit" value="Submit" />
</form>
When I click the submit button, exception occurs.
The current path, your-name/, didn't match any of these.
When I click the submit button, http://localhost:8000/your-name/. I think it's wrong. I guess http://localhost:8000/form/your-name/ must appear and Hello, world must be printed on the browser.
But it didn't. I wanna know the reason why?
Upvotes: 1
Views: 271
Reputation: 1155
Make sure, urls are correct.
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.get_name, name = 'get_name'),
url(r'^your-name/', ProductView.as_view()),
url(r'^register/$', RegisterFormView.as_view(), name='register'),
]
After that call url with app name, it will work surely.
<form action="/app_name/your-name/" method="post">
{% csrf_token %}
{{ form }}
<input type="submit" value="Submit" />
</form>
Thank you.
Upvotes: 1