template shows markup and not the page when combining context and forms

Viewed 16

I am fairly new to Django. I am trying to display a dictionary and form on the same page. However, it only vies the Html markup and not the actual page. Here is my code:

home/views.py:

from django.shortcuts import render
from recruit.forms import RecruitForm


articles = [
{
    'author': 'Glenn',
    'title':'title 1',
    'content': 'first content',
    'date_posted': 'January 12'
},
{
    'author': 'batman',
    'title':'title 2',
    'content': 'second content',
    'date_posted': 'January 12'
},
{
    'author': 'batgirl',
    'title':'title 3',
    'content': ' Lorem ipsum dolor sit amet consectetur adipisicing elit. Voluptas ratione 
       eaque nam totam! Labore consectetur nostrum dicta magnam ex expedita facilis  
       illum odit quibusdam vitae?',
    'date_posted': 'January 12'
}
]

# Create your views here.
def index(request):
  form = RecruitForm()
  context = {
    'articles': articles
}
return render(request, 'home/index.html', context, {'form':form})

recruit/forms.py:

 from django import forms
 from phonenumber_field.modelfields import PhoneNumberField
 from .models import Recruit

 class RecruitForm(forms.ModelForm):
    email = forms.EmailField()
    phone = PhoneNumberField()

 class Meta:
    model = Recruit
    fields = ['firstname', 'lastname', 'email', 'phone', 'city', 'contact_preference']
    widgets = {'contact_preference': forms.RadioSelect }

When I don't pass context the entire page renders. The same with form. I know how to validate forms, I just wanted to make this question as generic as possible. So either I can pass form or context but never both. When I do pass both I get my html markup and not document. By markup I mean the actual .html markup so the <!doctype> ... any help is appreciated.

1 Answers

If you pass two objects to the template, you make a dictionary with two entries, so:

def index(request):
    form = RecruitForm()
    return render(request, 'home/index.html', {'form':form, 'articles': articles})

So you do not pass two dictionaries. The fourth parameter of the render(…) function [Django-doc] is the content_type, not some extra context.

Related