2

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.

8
  • 1
    Render method you are sending events which is not defined. Also form =EventForm is unused. Commented Aug 20, 2017 at 16:41
  • Just to reinforce Vikash's point, you need to pass form to the template's context (in render) so it is available in the template. If you were using a class-based view this would be done automatically by specifying the form class. Commented Aug 20, 2017 at 16:46
  • 1
    Ah that makes sense. So my render function should be render(request, 'index.html', {'form': form})? Commented Aug 20, 2017 at 16:58
  • you don't define the events why your code is work without errors? Commented Aug 20, 2017 at 16:59
  • @LukePhillip try it. Commented Aug 20, 2017 at 17:00

1 Answer 1

2

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})
Sign up to request clarification or add additional context in comments.

4 Comments

I changed my render to the above, but the form still doesn't show on the template. Your answer makes great sense though, I thought that would end up being be the main problem.
that's exactly why I was avoiding posting the answer. I feared there might be multiple issues.
Nevermind, I realized I had recently inserted a typo in index.html. When I fixed that, the form showed on the template!
Great. I was just going to suggest you to try this: docs.djangoproject.com/en/1.11/topics/forms/#more-on-fields

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.