我尝试从站点在Django中使用FormView
godjango和formview
但不知道为什么它不起作用。
看我的代码:
#forms.py
from django import forms
from models import Contato
#from django.contrib.auth.forms import UserCreationForm
#class ContatoForm(UserCreationForm):
class ContatoForm(forms.ModelForm):
class Meta:
model = Contato
#views.py
# encoding: utf-8
from django.shortcuts import render_to_response
from django.views.generic import TemplateView, ListView, FormView
#from django.views.generic.edit import FormView
from teste.models import Contato
from teste.forms import ContatoForm
def index(request):
return render_to_response('teste/index.html')
class index2(TemplateView):
template_name = 'teste/index2.html'
class Lista(ListView):
template_name = 'teste/lista.html'
model = Contato
context_object_name = 'nomes'
class Criar(FormView):
template_name = 'teste/formulario.html'
form_class = ContatoForm
success_url = '/'
def form_valid(self, form):
print(self.request.POST['nome'])
return super(Criar, self).form_valid(form)
#urls.py
# encoding: utf-8
from django.conf.urls import patterns, include, url
from django.views.generic import TemplateView
from teste.views import index2
from teste.models import Contato
from teste.forms import ContatoForm
urlpatterns = patterns('',
url(r'^$', TemplateView.as_view(template_name='teste/index.html')),
url(r'^index2/$', index2.as_view()),
url(r'^lista/$', 'teste.views.Lista'),
url(r'^formulario/$', 'teste.views.Criar'),
#url(r'lista_marca/$', 'carros.views.listaMarca', name='lista_marca'),
)
#formulario.html
<html>
<body>
<form method="POST">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Criar" />
</form>
</body>
</html>
在github上查看我的项目
最佳答案
您忘记了as_view()url(r'^formulario/$', Criar.as_view()),