基于Django模型的联系表单不显示在模板上

时间:2017-04-03 08:10:09

标签: django-models django-forms django-templates

我一直在试图找出联系表格未显示在“contact.html”模板上的原因。我正在使用Django 1.10和Python 2.7。我需要一些指导。

models.py

from __future__ import unicode_literals
from django.db import models

class ContactForm(models.Model):
    name = models.CharField(max_length=15)
    email = models.EmailField(blank=True)
    message = models.TextField()
    pub_date = models.DateTimeField(auto_now=True)

    def __unicode__(self):
        return self.name

forms.py

from django import forms
from django.forms import ModelForm
from .models import ContactForm

class ContactForm(ModelForm):
    class Meta:
        model = ContactForm
        fields = ['name', 'email', 'message']

views.py

from django.shortcuts import render, render_to_response
from .forms import ContactForm, ReportItemForm, RegisterItemForm
from django.template.loader import get_template
from .models import ReportItem, RegisterItem, ContactForm

def contact(request):
    if request.method == "POST":
        form = ContactForm(request.POST)
        if form.is_valid():
            message = 'success'
            form.save()
        else:
            message = 'fail'
        return render(request, 'returnApp/contact.html', {'form': form},)
    else:
        return render(request, 'returnApp/contact.html', {'form': ContactForm()},)

urls.py

from django.conf.urls import url
from . import views

app_name = 'returnApp'
urlpatterns = [
    url(r'^$', views.index, name='index'),
    url(r'^contact/', views.contact, name='contact'),
]

contact.html

<div class="col-sm-6 col-sm-offset-3"> 
    {% if message %}
    {% endif %}
        <form role="form" action="" method="POST">
            {% csrf_token %}
            {{ form.as_p }}
                <button type="submit" class="btn btn-success">Submit</button>
        </form>
</div>

输出

 <div class="col-sm-6 col-sm-offset-3"> 

            <form role="form" action="" method="POST">
                <input type='hidden' name='csrfmiddlewaretoken' value='FpQ06fHpZTpMmweGuFlGd0I4euP6KEFU9lWhu7fRUdeKIWtobdG6ngTJUGUKWb9Q' />

                <button type="submit" class="btn btn-success">Submit</button>
            </form>
    </div>

1 个答案:

答案 0 :(得分:0)

发现问题。我在models.py和forms.py中给出了同名的联系表单,这让Django感到困惑。 以这种方式更改了表单类定义

forms.py

class ContactFormForm(ModelForm):
在views.py中

from .forms import ContactFormForm