Luke Phillip
Luke Phillip

Reputation: 23

Django form fields not loading in template

I can't seem to get a model form to load in my template.

models.py

from django.db import models

class Event(models.Model):
    name = models.CharField(max_length=60)
    start_datetime = models.DateTimeField()
    end_datetime = models.DateTimeField()
    description = models.TextField()

forms.py

from django import forms
from .models import Event

class EventForm(forms.ModelForm):
    class Meta:
        model = Event
        fields = ['name']

views.py

from django.shortcuts import render
from .forms import EventForm

def index(request):
    if request.method == 'POST':
        form = EventForm(request.POST)
        if form.is_valid():
            form.save()
    else:
        form = EventForm()

    return render(request, 'index.html')

index.html

<form method="POST" action="">
  {% csrf_token %}
  {{ form.as_p }}
</form>
<button type="submit">Save</button>

I can get the form to print to the console on load when adding print(form) in views.py on the GET request, but it doesn't load in the template.

Upvotes: 2

Views: 2023

Answers (1)

Vikash Singh
Vikash Singh

Reputation: 14011

Good examples on different ways to use forms : https://docs.djangoproject.com/en/1.11/topics/forms/#the-view

For index.html to render it is expecting form variable. So Render method call should be like this:

render(request, 'index.html', {'form': form})

Upvotes: 2

Related Questions