1

再一次,我有一個小問題可以在django中完成。但至少你們幫助我更好地理解事情。在Django中,我無法保存我的模型的新內容

這是我的觀點:

def editUserprofile(request): 
rc = context_instance=RequestContext(request) 
u=request.user 
if request.method=='POST': 
    form = UserProfileEdit(request.POST, request.FILES) 
    if form.is_valid(): 
     u = UserProfile.objects.get(user=u) 
     u.avatar = request.FILES['avatar'] 
     u.first_name = form.cleaned_data['first_name'] 
     u.last_name = form.cleaned_data['last_name'] 
     u.email = form.cleaned_data['email'] 
     u.country = form.cleaned_data['country'] 
     u.date_of_birth = form.cleaned_data['date_of_birth'] 
     u.save() 
     return HttpResponseRedirect("/editprofile") 

else: 
    u = UserProfile.objects.get(user=u) 
    form = UserProfileEdit() 
return render_to_response('users/editprofile.html', 
         {'form':form, 'u':u}, 
         rc) 

沒有錯誤,但我的模型並未修改。這裏是我的模板太:

<form method="POST" action="."> 
    {% csrf_token %} 

    {% if u.avatar %} 
     <img src="{{ MEDIA_URL }}{{ u.avatar }}" height="80px" /> 
    {% else %} 
     <p>You have no avatar</p> 
    {% endif %} 
     <p>Change Avatar: {{form.avatar}}</p> 
    <br /> 
    {% if u.first_name %} 
     <p>First Name: {{u.first_name}}</p> 
    {% else %} 
     <p>First Name: No first name added </p> 
    {% endif %} 
     <p>Modify:{{form.first_name}}</p> 
    <br /> 
    {% if u.last_name %} 
     <p>Last Name: {{u.last_name}}</p> 
    {% else %} 
     <p>Last Name: No last name added </p> 
    {% endif %} 
     <p>Modify:{{form.last_name}}</p> 
    <br /> 
    {% if u.email %} 
     <p>Email: {{ u.email }}</p> 
    {% else %} 
     <p>Email: No email added</p> 
    {% endif %} 
    <p>Modify:{{ form.email }}</p> 
    <br /> 

    {% if u.date_of_birth %} 
     <p>Date of birth: {{ u.date_of_birth }} 
    {% else %} 
     <p>Date of birth: No birthday added </p> 
    {% endif %} 
    <p>Modify:{{form.date_of_birth}}</p> 
    <br /> 

    {% if u.country %} 
     <p>Country: {{ u.country }}</p> 
    {% else %} 
     <p>Country: No Country added</p> 
    {% endif %} 
    <p>Modify:{{form.country}}</p> 
    <br /> 

    <input type="submit" value="Save Changes"> 
</form> 

希望你能幫助我的傢伙..!

+1

'form.is_valid()'是真的嗎? –

+0

不...感謝:D發佈它作爲答案 –

回答

2

form.is_valid()您的表單驗證是否正確?

相關問題