Django - 允许用户编辑配置文件,然后显示更新的配置文件字段

时间:2015-04-29 00:44:07

标签: django-forms

我的表单填充了用户个人资料信息,但是当我点击“保存”时,它实际上并没有更新。

非常感谢有关我需要修改哪个部分的任何线索/提示。

提前致谢!

views.py

def profile_view(request):
    user = request.user
    form = EditProfileForm(initial={'first_name':user.first_name, 'last_name':user.last_name})
    context = {
        "form": form
    }
    return render(request, 'profile.html', context)

def edit_profile(request):

    user = request.user
    form = EditProfileForm(request.POST or None, initial={'first_name':user.first_name, 'last_name':user.last_name})
    if request.method == 'POST':
        if form.is_valid():


            user.first_name = request.POST['first_name']
            user.last_name = request.POST['last_name']

            user.save()
            return HttpResponseRedirect('%s'%(reverse('profile')))

    context = {
        "form": form
    }

    return render(request, "edit_profile.html", context)

forms.py

class EditProfileForm(forms.ModelForm):

    first_name = forms.CharField(label='First Name')
    last_name = forms.CharField(label='Last Name') 

    class Meta:
        model = User
        fields = ['first_name', 'last_name']

edit_profile.html

{% extends "base_site.html" %}

{% block content %}

<h1>Edit Profile</h1>


<form method="POST" action="/accounts/profile/" class="" />
    {% csrf_token %}
    {{ form.as_p }}
    <button type="submit">Save</button>
</form>


{% endblock %}

urls.py

from django.conf.urls import url
from . import views

urlpatterns = [

    url(r'^register/$', 'accounts.views.registration_view', name='auth_register'),
    url(r'^login/$', 'accounts.views.login_view', name='auth_login'),
    url(r'^logout/$', 'accounts.views.logout_view', name='auth_logout'),
    url(r'^profile/$', 'accounts.views.profile_view', name='profile'),
    url(r'^profile/edit/$', 'accounts.views.edit_profile', name='edit_profile'),
]

1 个答案:

答案 0 :(得分:1)

表单中的操作为POST profile_view而非edit_profile,您的表单已自动关闭,因此未正确POST

改变这个:

<form method="POST" action="/accounts/profile/" class="" />

对此:

<form method="POST" action="/accounts/profile/edit" class="" >

甚至更好,请使用django url template tag

<form method="POST" action="{% url 'edit_profile' %}" class="" >