【发布时间】:2011-03-13 08:39:23
【问题描述】:
我有一个页面,其中显示了登录用户可以用来编辑其个人资料的表单。
当用户第一次通过 GET 请求加载相应视图时,表单应显示用户现有配置文件记录的值。
因为我想对用于表单字段的标记进行精细控制,所以我想只检索字段值,并手动编写必要的输入元素标记,将检索到的字段值插入为输入元素' 'value' 属性(而不是让 django 渲染整个输入元素)。
到目前为止,我一直在尝试在模板中使用 {{ form.myfield.data }} 之类的指令来访问字段数据,但这会返回“无”,而不是我预期的配置文件详细信息。
如果用户刚刚发布了一个有效的表单,那么表单字段确实包含预期的个人资料详细信息。
我希望有人可以帮助我理解我在这里做错了什么:
这是我的看法:
@login_required
def edit(request):
# get logged-in user's profile
obj=Profile.objects.get(user=request.user)
if request.method == 'POST': # If the form has been submitted...
form = ProfileForm(request.POST, request.FILES, instance=obj)
if form.is_valid(): # All validation rules pass
form.save()
request.flash['success'] = "Your profile has been updated." # Puts a string to the flash scope
else:
request.flash['error'] = 'Please correct the problems below and try again' # Puts a string to the flash scope
else:
# if no form was submitted
# derive the form data from the logged-in users existing profile
form = ProfileForm(instance=obj)
return render_to_response('app_profile/edit.html',
{
'form': form,
'user': request.user,
'ancestor_urls': ['app_profile.views.edit',],
},context_instance=RequestContext(request)
)
这是相应模板的摘录。此输入元素处理名为“display_name”的字段。
<input type="text"
class="textInput large {% if form.display_name.errors %}error{% endif %}"
maxlength="50"
size="35"
value="{{ form.display_name.data }}"
id="id_display_name"
name="display_name">
【问题讨论】:
标签: django forms django-forms