如何制作允许用户编辑自己个人资料的功能?
views.py
@login_required
def edit_user(request):
if '_auth_user_id' in request.session:
userId = request.session['_auth_user_id']
userDetails = User.objects.get(pk=userId)
if request.method == 'POST':
form = UserProfileForm(request.POST, request.FILES)
userDetails.first_name = request.POST['firstname']
userDetails.last_name = request.POST['lastname']
userDetails.email = request.POST['email']
userDetails.zip = request.POST['zip']
if form.is_valid():
userDetails.save()
return HttpResponseRedirect('/edit_user/')
else:
form = UserProfileForm()
variables = RequestContext(request, {'form': form})
return render_to_response('edit_user.html',variables,)
forms.py
class UserProfileForm(forms.Form):
email = forms.EmailField(label='Email', max_length=254)
firstname = forms.CharField(label='First Name', max_length=20)
lastname = forms.CharField(label='Last Name', max_length=20)
zip = forms.CharField(label='Zipcode', max_length=5)
edit_user.html
<form class="form-signin" action="/edit_user/" method="post" enctype="multipart/form-data">{% csrf_token %}
{% csrf_token %}
{{ form.as_p }}
<button type="submit" class="btn btn-info"> Save Edits</button>
</form>
它不会显示字段,显示为空白: http://gyazo.com/48ee38b22434aae418cfe61accb00bd8.png
答案 0 :(得分:0)
在login(request, user)
之后,您可以在会话中从_auth_user_id
访问用户信息
request.session[_auth_user_id]
。所以你可以创建一个像编辑个人资料
def edit_profile(request):
template_var = {}
if '_auth_user_id' in request.session:
userId = request.session['_auth_user_id']
new_profile_user = Profile.objects.get(user_id=userId)
userDetails = User.objects.get(pk=userId)
if request.method == 'POST':
userDetails.first_name = request.POST['first_name']
userDetails.email = request.POST['email']
userDetails.save()
template_var['new_profile_user']=new_profile_user
return render_to_response('edit_user.html',template_var,)
现在,在您的模板中,请执行{{new_profile_user.first_name}}
答案 1 :(得分:0)
我的代码:
def profile_edit(request, template_name='profile_edit.html'):
if request.method == 'POST':
form = ProfileForm(data=request.POST, instance=request.user)
if form.is_valid():
user_profile = form.save(commit=False)
user_profile.save()
return redirect('index')
else:
form = ProfileForm(instance=request.user)
return render(request, template_name,{'form': form})