我想从json预先填充的模型中进行编辑,并尝试使用上一个函数中的用户数据填充表单行,但是当插入时,例如来自model_from_json的last_name我收到错误"全局名称' last_name'未定义"。否则,如果我将变量表示为字符串' last_name'视图呈现可编辑的填充表单行。那么,请问如何使变量可见?
def model_from_json(request):
path = 'management/test.json'
with open(path,'r+') as json_file:
json_data = json_file.read()
json_dict = json.loads(json_data)
username = json_dict[0]['fields']['username']
first_name = json_dict[0]['fields']['first_name']
last_name = json_dict[0]['fields']['last_name']
date = json_dict[0]['fields']['last_login']
email = json_dict[0]['fields']['email']
form = UserDataForm({
'username':username ,
'last_name':last_name,
'first_name':first_name,
'date':date,
'email':email
})
form.save()
template = 'create.html'
return render_to_response(template, locals(),context_instance=RequestContext(request))
def form_edit(request, id=None, template_name='edit.html'):
if id:
username = get_object_or_404(User, pk=id)
if User.user != request.user:
return HttpResponseForbidden()
else:
username = User(username=request.user)
if request.POST:
form = UserDataForm(request.POST, instance=username)
if form.is_valid():
form.save()
message=messages.add_message(request, messages.SUCCESS,(''))
# If the save was successful, redirect to another page
redirect_url = reverse('index')
return HttpResponseRedirect(redirect_url)
else:
form = UserDataForm({'last_name':last_name})
return render_to_response('edit.html', {
'form': form,
}, context_instance=RequestContext(request))
答案 0 :(得分:2)
将值保留到session
中request.session["username"] = username
答案 1 :(得分:0)
更改您的观点,如:
if request.POST:
....
else:
form = UserDataForm(initial={'last_name':username.last_name})