我的Django学习带我到了Forms。我已经能够使用我正在阅读的书中的信息创建一个简单的表单。我还根据我创建的模型创建了一个表单。我遇到的问题是我试图在模板中创建自己的格式,并且由于某种原因标签信息不在formset中。我对使用默认的显示方式感到有点困惑,即{{form}}有这个信息。
我有什么;
adminforms.py
class NewsForm(ModelForm):
class Meta:
model = News_Article
exclude = ('news_datetime_submitted', 'news_yearmonth', )
labels = {
'news_title': _('Enter News Title'),
}
help_texts = {
'news_title': _('Enter a title to give a short description of what the news is.'),
}
error_messages = {
'news_title': {
'max_length': _("News title is too long."),
},
}
view.py
def create(request, dataset):
if dataset not in ['news', 'announcement']:
# change this to the siteadmin page if authenticated and have permissions, otherwise go to home
return HttpResponseRedirect(reverse('pages'))
rDict = {}
# if this is a POST request we need to process the form data
if request.method == 'POST':
# create a form instance and populate it with data from the request:
if dataset == "news":
form = NewsForm(request.POST)
elif dataset == "announcement":
form = AnnouncementForm(request.POST)
# check whether it's valid:
if form.is_valid():
# process the data in form.cleaned_data as required
# ...
# redirect to a new URL:
return HttpResponseRedirect('/home/')
else:
pass
# if a GET (or any other method) we'll create a blank form
else:
announcement = get_announcement()
if not announcement == None:
rDict['announcement'] = announcement
if dataset == "news":
rDict['formset'] = NewsForm()
rDict['branding'] = {'heading': 'Create News Item', 'breadcrumb': 'Create News', 'dataset': 'create/' + dataset + '/'}
elif dataset == "announcement":
rDict['form'] = AnnouncementForm()
rDict['branding'] = {'heading': 'Create Announcement', 'breadcrumb': 'Create Announcement', 'dataset': 'create/' + dataset + '/'}
rDict['sitenav'] = clean_url(request.path, ['"', "'"])
rDict['menu'] = Menu.objects.all().order_by('menu_position')
pdb.set_trace()
return render(request, 'en/public/admin/admin_create.html', rDict)
模板
<form action="/siteadmin/{{ branding.dataset }}" method="post">
{% csrf_token %}
{{ formset.management_form }}
{% for form in formset %}
{% for field in form %}
{{ field.label_tag }} {{ field }}
{% endfor %}
{% endfor %}
<input type="submit" value="Submit" />
</form>
由于某种原因,jut获取表单字段而没有标签信息。注:模板文本我从格式集上的Django文档中获取。
我已经查看了返回的数据并且没有标签信息,但它只适用于{{form}}?有点困惑。
(Pdb) rDict['formset']
<NewsForm bound=False, valid=Unknown, fields=(news_title;news_text;news_active)>
先谢谢你们。
韦恩
答案 0 :(得分:2)
您正在添加一个名为“formset”的上下文变量,它不是一个formset,它是一个表单:rDict['formset'] = NewsForm()
。
因此,当将此上下文变量传递给模板时,使用{% for form in formset %}
进行迭代会产生误导效果,即创建名为form
的变量,该变量实际上是一个表单字段。尝试正确命名(如果你真的想要一个formset,按照描述here创建一个),看看事情是否有意义。