显示表单内容而不是表单对象名称

时间:2015-01-04 02:37:41

标签: python django forms

我是Django的新手,我正在尝试在模板中创建一个表单。我想我已经完成了这个但是我错过了一件。这就是我目前看到的:

enter image description here

我认为我错过了我的表单类中应该显示选项的内容。

forms.py

from django import forms

class TestForm(forms.Form):
    one = forms.ChoiceField(choices=('HDFS', 'HDFS'), widget=forms.RadioSelect())
    two = forms.ChoiceField(choices=('HIVE', 'HIVE'), widget=forms.RadioSelect())
    three = forms.ChoiceField(choices=('BOTH', 'Both of HDFS and HIVE'), widget=forms.RadioSelect())
    beatle = [one, two, three]
    event_textarea = forms.Textarea(attrs={'rows': '8', 'class': 'form-control', 'placeholder': 'Events...', 'id': 'event_textarea'})

views.py

def home(request):
    if request == 'POST':
        # create a form instane and populate it with data from the request
        form = TestForm(request.POST)
        if form.is_valid():
            # process the data in form.cleaned_data as required
            form.cleaned_data()
            # redirect to a new URL:
            return HttpResponseRedirect('/test/')
    # if a GET (or any other method) we'll create a blank form
    else:
        form = TestForm()
    return render(request, 'home/home_page.html', {'form': form})

模板:

{% extends 'index/index.html' %}

{% load staticfiles %}
{% block head %}
  <script type="text/javascript" src="{{ STATIC_URL }}home/js/home.js" async></script>
  <link href="{{ STATIC_URL }}home/css/home.css" rel="stylesheet">
{% endblock head %}

{% block content %}

  <div>Welcome to Trinity E2E testing</div>

  <form id="test-form" action="/test/" method="post"> {# pass data to /test/ URL #}
    {% csrf_token %}
    {% for radio in form.beatle %}
    <div class="btn btn-default btn-lg">
      {{ radio }}
    </div>
    {% endfor %}
    {{ form.event_textarea }}

    <input id="submit-test" type="submit" class="btn btn-default btn-lg" value="Submit">
  </form>

{% endblock content %}

1 个答案:

答案 0 :(得分:2)

beatle列表包含对类属性的引用,而不是实例属性。

如何使它成为返回实例属性(表单字段)的实例方法:

def beatle(self):
    return [self.one, self.two, self.three]

<强>更新

要正确返回绑定字段:

def beatle(self):
    return [self['one'], self['two'], self['three']]

def beatle(self):
    return [self[name] for name in ['one', 'two', 'three']]