Django表单字段未加载模板

时间:2017-08-20 16:37:00

标签: python django forms

我似乎无法在模板中加载模型表单。

models.py

<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class ValidateRegistration extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return false;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'fname'     => 'required',
            'lname'     => 'required',
            'phone'     => 'required|size:10',
            'email'     => 'required',
            'password'  => 'required'
        ];
    }

    /**
    * Get the error messages for the defined validation rules.
    *
    * @return array
    */
    public function messages()
    {
        return [
            'fname.required' => 'Firstname is mandatoy',
            'lname.required'  => 'Lastname is mandatory',
            'phone.required'  => 'Phone is mandatory',
            'phone.size'  => 'Phone must be 10 digit',
            'email.required'  => 'Email is mandatory',
            'password.required'  => 'Password is mandatory',
        ];
    }
}

forms.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()

views.py

from django import forms
from .models import Event

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

的index.html

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')

在GET请求的views.py中添加print(form)时,我可以让表单在加载时打印到控制台,但它不会加载到模板中。

1 个答案:

答案 0 :(得分:1)

使用表单的不同方法的好例子:https://docs.djangoproject.com/en/1.11/topics/forms/#the-view

要让index.html呈现,它需要form变量。所以Render方法调用应该是这样的:

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