Skip to main content
 首页 » 编程设计

python之如何在 django (Horizon Dashboard) 中使用 POST 从表单获取数据

2025年05月04日8thcjp

我是使用 django 进行开发的新手,我正在尝试修改 Openstack Horizo​​n Dashboard 应用程序(基于 django 应用程序)。

我实现了一个功能,现在我正在尝试创建一个表单,但我在请求时遇到了一些问题。

在我的代码中,我使用了 POST 方法

首先,我想在同一个 View 中显示表单上的内容,我正在这样做。

from django import http 
from django.utils.translation import ugettext_lazy as _ 
from django.views.generic import TemplateView 
from django import forms 
 
 
class TesteForm(forms.Form): 
    name = forms.CharField() 
 
class IndexView(TemplateView): 
    template_name = 'visualizations/validar/index.html' 
 
    def get_context_data(request): 
        if request.POST: 
            form = TesteForm(request.POST) 
            if form.is_valid(): 
                instance = form.save() 
        else : 
            form = TesteForm() 
        return {'form':form} 
 
class IndexView2(TemplateView): 
    template_name = 'visualizations/validar/index.html' 
 
    def get_context_data(request): 
        text = None 
        if request.POST: 
        form = TesteForm(request.POST) 
            if form.is_valid(): 
                text = form.cleaned_data['name'] 
    else: 
        form = TesteForm() 
        return {'text':text,'form':form}    

我的urls.py文件是这样的

from django.conf.urls.defaults import patterns, url 
from .views import IndexView 
from .views import IndexView2 
 
urlpatterns = patterns('', 
    url(r'^$',IndexView.as_view(), name='index'), 
    url(r'teste/',IndexView2.as_view()), 
) 

我的模板是这样的

{% block main %} 
<form action="teste/" method="POST">{% csrf_token %}{{ form.as_p }} 
<input type="submit" name="OK"/> 
</form> 
<p>{{ texto }}</p> 
{% endblock %} 

我在 django 的文档上搜索了这个,但是 django 的例子并不清楚,django 的应用程序只是使用方法,Horizo​​n Dashboard 使用类(在我上面的代码中如何)

当我执行此操作时,会出现一条错误消息。

这条消息说:

AttributeError at /visualizations/validar/ 
'IndexView' object has no attribute 'POST' 
Request Method: GET 
Request URL:    http://127.0.0.1:8000/visualizations/validar/ 
Django Version: 1.4.5 
Exception Type: AttributeError 
Exception Value:'IndexView' object has no attribute 'POST' 
Exception Location: 
 /home/labsc/Documentos/horizon/openstack_dashboard/dashboards/visualizations/validar/views.py in get_context_data, line 14 
Python Executable:  /home/labsc/Documentos/horizon/.venv/bin/python   
Python Version: 2.7.3 

我搜索了这个错误,但什么也没找到。

如果有人能帮助我,我很感激

请您参考如下方法:

您的签名有误:

def get_context_data(request) 

应该是

def get_context_data(self, **kwargs): 
    request = self.request 

检查 get_context_data和关于 dynamic filtering 的词

因为您的第一个参数是 self 对象,在本例中是 request,所以您收到了错误。