我为自定义用户和视图编写了一个模型,允许我添加新用户,查看他们的个人资料信息以及登录/退出。 但是,在为用户编写视图以更新其个人资料信息时,我发现正在显示的表单要求用户再次填写所有详细信息,即使他们不想更改该特定详细信息。例如,如果用户想要更改他们的姓氏,他们必须再次输入他们的电子邮件,密码,名字等。 有没有办法让我自动填充此表单,用户可以只更改他们需要的内容? 我已在下面附上我的表格和观点代码。非常感谢任何帮助!
views.py
@login_required(login_url='/login/')
def personal(request):
"""
Personal data of the user profile
"""
profile = MyUser.get_full_name #This returns the email address
if request.method == "POST":
form = ProfileForm(request.POST, instance=profile)
if form.is_valid():
form.save()
messages.add_message(request, messages.INFO, _("Your profile information has been updated successfully."))
else:
form = ProfileForm
template = "update_profile.html"
data = { 'section': 'personal', 'form': form, }
return render_to_response(template, data, context_instance=RequestContext(request))
forms.py
class ProfileForm(forms.ModelForm):
"""
Profile Form. Composed by all the Profile model fields.
"""
class Meta:
model = MyUser
exclude = ('is_active', 'is_admin', 'last_login')
实施解决方案后出现错误
Environment:
Request Method: GET
Request URL: http://localhost:8000/friends/update/
Django Version: 1.6.5
Python Version: 2.7.7
Installed Applications:
('django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'friends')
Installed Middleware:
('django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware')
Traceback:
File "D:\Python27\lib\site-packages\django\core\handlers\base.py" in get_response
112. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "D:\Python27\lib\site-packages\django\contrib\auth\decorators.py" in _wrapped_view
22. return view_func(request, *args, **kwargs)
File "D:\Uni\_Project\friend_finder_V2\mysite\friends\views.py" in personal
85. form = ProfileForm(instance=profile)
File "D:\Python27\lib\site-packages\django\forms\models.py" in __init__
315. object_data = model_to_dict(instance, opts.fields, opts.exclude)
File "D:\Python27\lib\site-packages\django\forms\models.py" in model_to_dict
124. opts = instance._meta
Exception Type: AttributeError at /friends/update/
Exception Value: 'function' object has no attribute '_meta'
答案 0 :(得分:0)
你可以使用instance
kwarg在GET上将当前的个人资料传递给你的表格(我看到你已经在POST上传递了它)。此外,在使用POST更改数据库后,请不要忘记执行HTTP重定向。像这样:
form = ProfileForm(request.POST, instance=profile) if request.method == 'POST: if form.is_valid(): form.save() messages.add_message(request, messages.INFO, _("Your profile information has been updated successfully.")) # TODO You need to do a redirect here else: form = ProfileForm(instance=profile)