KyluAce
KyluAce

Reputation: 1000

HTML doesn't see django form (django form doesn't render/display)

I created simple form in django. I tried do it in many different ways check all posibilities but still my HTML code doesn't see this form. Code looks like :

forms.py

from django import forms


class TimeTable(forms.Form):

    title = forms.CharField(max_length=100, required=True)
    time_start = forms.DateTimeField()
    time_end = forms.DateTimeField()

views.py

from home.forms import TimeTable
from django.shortcuts import render


def schedule(request):
    if request.method == 'POST':
        form = TimeTable(request.POST)
        if form.is_valid():
            pass
    else:
        form = TimeTable()
    return render(request, "registration/schedule.html", {'schedule_form': form})

urls.py

from django.contrib import admin
from django.urls import path, include
from django.views.generic.base import TemplateView


urlpatterns = [
    path('admin/', admin.site.urls),
    path('accounts/', include('django.contrib.auth.urls')),
    path('', TemplateView.as_view(template_name='home.html'), name='home'),
    path('accounts/login/', TemplateView.as_view(template_name='registration/login.html'), name='login'),
    path('schedule/', TemplateView.as_view(template_name='registration/schedule.html'), name='schedule'),
]

schedule.html

{% block calendar %}
<div class="calendar_create">
            <form method="post">
                {% csrf_token %}
                {{ form.as_p }}
                <button type="submit">Submit</button>
            </form>
    {% endblock %}
    </div>

HTML only see this <button> mark rest is missing. I tried do it with many tutorials, django documentation and all this stuff doesn't work for me. What I'm doing wrong ?

Upvotes: 0

Views: 65

Answers (1)

Daniel Roseman
Daniel Roseman

Reputation: 600041

You never call your schedule view. Your "schedule/" urlpattern uses an inline TemplateView which renders the template directly. The view that creates the form and adds it to the context is never called at all.

You need to use the view in the url pattern instead:

from myapp import views
...

path('schedule/', views.schedule, name='schedule'),

There is another issue as well: your view sends the form as schedule_form, but your template references form. You need to use the same name in both places:

{{ schedule_form.as_p }}

Upvotes: 1

Related Questions