我通过看django教程创建了一个网站。 https://docs.djangoproject.com/en/1.11/intro/
我收到了错误,
AttributeError at /polls/1/
'RadioSelect' object has no attribute 'renderer'
它发生在forms.py的第21行,即init。 我在forms.py中写过
from django import forms
class MyForm(forms.Form):
text = forms.CharField(max_length=100,required=False,label='テキスト')
class VoteForm(forms.Form):
choice = forms.ModelChoiceField(
queryset=None,
label='選択',
widget=forms.RadioSelect,
empty_label=None,
error_messages={
'required':"You didn't select a choice.",
'invalid_choice':"invalid choice.",
},
)
def __init__(self,question,*args,**kwargs):
super().__init__(*args,**kwargs)
self.fields['choice'].queryset = question.choice_set.all()
self.fields['choice'].widget.renderer.inner_html = '{choice_value}{sub_widgets}<br>'
单选按钮的设置写在detail.html中,如
<!DOCTYPE html>
<h1>{{ question.question_text }}</h1>
{% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %}
<form action="{% url 'poll_vote' question.id %}" method="post">
<!--<form action="" method="post">-->
{% csrf_token %}
{% for choice in question.choice_set.all %}
<input type="radio" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}" />
<label for="choice{{ forloop.counter }}">{{ choice.choice_text }}</label><br />
{% endfor %}
<!--{{ form }}-->
<input type="submit" value="Vote" />
</form>
</html>
views.py是
from django.shortcuts import render
from django.utils.html import mark_safe
from .models import Question
from django.http import HttpResponse
from django.shortcuts import Http404
from django.shortcuts import get_object_or_404,redirect
from .models import Choice
from django.views.generic import TemplateView
from django.views.generic import DetailView
from django.views.generic import ListView
from .forms import MyForm
from .forms import VoteForm
# Create your views here.
def index(request):
return render(request,'polls/index.html',{
'questions': Question.objects.all(),
})
def detail(request,pk):
obj = get_object_or_404(Question,pk=pk)
if request.method == "POST":
form = VoteForm(question=obj,data=request.POST)
if form.is_valid():
return redirect('polls:results',pk)
else:
form = VoteForm(question=obj)
return render(request,'templates/polls/detail.html',{
'form':form,
'question': obj,
})
def vote(request,pk):
pass
def results(request,pk):
obj = get_object_or_404(Question,pk=pk)
return render(request,'polls/results.html',{
'question':obj,
})
def form_test(request):
if request.method == "POST":
#request.POST???
form = MyForm(data=request.POST)
if form.is_valid():
pass
else:
form = MyForm()
return render(request,'polls/form.html',{
'form':form,
})
回溯就像
Traceback: File "/Users/XXX/django/django/core/handlers/exception.py" in inner 35. response = get_response(request) File "/Users/XXX/django/django/core/handlers/base.py" in _get_response 130. response = self.process_exception_by_middleware(e, request)
File "/Users/XXX/django/django/core/handlers/base.py" in _get_response 128. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/XXX/djangostudy/polls/views.py" in detail 40. form = VoteForm(question=obj) File "/Users/XXXi/djangostudy/polls/forms.py" in init 21. self.fields['choice'].widget.renderer.inner_html = '{choice_value}{sub_widgets}<br>' Exception Type: AttributeError at /polls/1/ Exception Value: 'RadioSelect' object has no attribute 'renderer'
我不知道如何修复它。我无法理解为什么会发生这种错误。 我应该怎么做才能解决这个问题?
答案 0 :(得分:1)
你会看到我们在这里有什么:
>>> from django import forms
>>> from myapp.models import Vote
>>>
>>> class VoteForm(forms.Form):
... choice = forms.ModelChoiceField(
... queryset=Vote.objects.all(),
... widget=forms.RadioSelect()
... )
...
>>>
>>> f = VoteForm()
>>>
>>> f.fields['choice']
<django.forms.models.ModelChoiceField object at 0xb64ec3ec>
>>>
>>> f.fields['choice'].widget.renderer
Traceback (most recent call last):
File "<console>", line 1, in <module>
AttributeError: 'RadioSelect' object has no attribute 'renderer'
>>>
由于AttributeError: 'RadioSelect' object has no attribute 'renderer'
无效,您获得追溯renderer
:
>>> dir(f.fields['choice'].widget)
['__class__', '__deepcopy__', '__delattr__', '__dict__', '__dir__',
'__doc__', '__eq__', '__format__', '__ge__', '__getattribute__',
'__gt__', '__hash__', '__init__', '__le__', '__lt__', '__module__',
'__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__',
'__setattr__', '__sizeof__', '__slotnames__', '__str__',
'__subclasshook__', '__weakref__', '_format_value', '_render',
'add_id_index', 'allow_multiple_selected', 'attrs', 'build_attrs',
'checked_attribute', 'choices', 'create_option', 'format_value',
'get_context', 'id_for_label', 'input_type', 'is_hidden', 'is_localized',
'is_required', 'media', 'needs_multipart_form', 'optgroups',
'option_inherits_attrs', 'option_template_name', 'options', 'render',
'subwidgets', 'supports_microseconds', 'template_name',
'use_required_attribute', 'value_from_datadict', 'value_omitted_from_data']
>>>
但是我们在这里发现了render
和_render
函数:
>>> f.fields['choice'].widget.render
<bound method Widget.render of <django.forms.widgets.RadioSelect object at 0xb64ec4ac>>
>>>
>>> f.fields['choices'].widget._render
<bound method Widget._render of <django.forms.widgets.RadioSelect object at 0xb64ec4ac>>
>>>
我只是不知道为什么你需要这个功能
.inner_html
,以及期望做什么。
也许有关customizing the form template的文档对您有用。