edit_profile
更新用户数据。否则得到表格
用户和显示的数据。 问题:/ profile / edit中的AttributeError'AnonymousUser'对象没有 属性'_meta'
我认为可能是 # Handles the get request - if no post info is submitted then get the form and display it on the edit profile page.
else:
form = UserChangeForm(instance=request.user)
args = {'form': form}
return render(request, 'accounts/profile_edit.html', args)
视图中的这一行
view.py edit_profile
不确定是什么。这是def edit_profile(request):
# Handle post request - if the user submits a form change form details and pass the intance user
if request.method == 'POST':
form = UserChangeForm(request.POST, intance=request.user)
if form.is_valid():
form.save()
return redirect('accounts/profile')
# Handles the get request - if no post info is submitted then get the form and display it on the edit profile page.
else:
form = UserChangeForm(instance=request.user)
args = {'form': form}
return render(request, 'accounts/profile_edit.html', args)
{% extends 'base.html' %}
{% block head %}
<title>Profile</title>
{% endblock %}
{% block body %}
<div class="container">
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Save Changes</button>
</form>
</div>
{% endblock %}
profile_edit.html
{{1}}
答案 0 :(得分:0)
您无法更新AnnonymousUser
(即为未登录用户设置的特殊用户类)。您的问题的一个解决方案是通过使用login_required
装饰器修饰您的视图,禁止未经过身份验证的用户查看此页面。
答案 1 :(得分:0)
您收到错误,因为没有用户登录。 您可以使用try方法。
在您的代码中使用if user.is_authenticated
if user.is_authenticated():
if request.method == 'POST':
form = UserChangeForm(request.POST, intance=request.user)
if form.is_valid():
form.save()
return redirect('accounts/profile')
# Handles the get request - if no post info is submitted then get the form and display it on the edit profile page.
else:
form = UserChangeForm(instance=request.user)
args = {'form': form}
return render(request, 'accounts/profile_edit.html', args)
else:
raise PermissionDenied