如何允许用户在Django中编辑其个人资料?

时间:2020-07-14 16:10:43

标签: python django django-models django-forms django-users

我在models.py中有一个这样的模型:

class UserProfile(models.Model):
    user = models.OneToOneField(User, on_delete=models.DO_NOTHING)
    phone_number = models.CharField(max_length=50, default='')
    Birthday = models.CharField(max_length=50, default='')
    city = models.CharField(max_length=50, default='')
    school = models.CharField(max_length=100, default='')
    course = models.CharField(max_length=50, default='')

我想允许我的用户进行编辑,所以我在views.py中做了如下功能:

    if request.method == 'POST':
        profil = UserProfile.objects.get(user=request.user)
        profil.phone_number = models.CharField(max_length=50, default='')
        profil.Birthday = models.CharField(max_length=50, default='')
        profil.city = models.CharField(max_length=50, default='')
        profil.school = models.CharField(max_length=100, default='')
        profil.course = models.CharField(max_length=50, default='')
        
        profil.save()
        
        return redirect('profile')  
 
    return render(request, 'edit_profile.html')

我的模板是:

<form action="." method="post">
        {% csrf_token %}    
        Phone Number:
        <input type="text" name="phone_number" value="{{  profil.phone_number }}" /><br />
        Birthday:
        <input type="text" name="Birthday" value="{{  profil.Birthday }}" /><br />
    
        city:
        <input type="text" name="city" value="{{  profil.city }}" /><br />
        school:
        <input type="text" name="school" value="{{  profil.school }}" /><br />
    
        course:
        <input type="text" name="course" value="{{  profil.course }}" /><br />
       
        <input type="submit" value="Save Changes" name="save" />
        <input type="reset" value="Cancel" name="cancel" />
        <br/>
    </form>

我不知道为什么,但是填写表格后出现错误,提示找不到页面。如果我检查现有的用户配置文件,则没有任何更新。请帮助。

2 个答案:

答案 0 :(得分:1)

您有一个错误

profil = UserProfile.objects.get(user=request.user)
profil.phone_number = models.CharField(max_length=50, default='')

您得到一个UserProfile对象,然后尝试保存一个对象str,而不是将phone_number保存到models.CharField中。 使用ModelForm来满足您的需求。

class UserProfileForm(forms.ModelForm):
    class Meta:
        model = UserProfile
        fields = '__all__'

然后在您的视图中可以使用:

userprofile_form = UserProfileForm(request.POST if request.POST else None, instance = UserProfile.objects.get(user=request.user))
if request.method == 'POST':
    if form.is_valid():
        form.save()     
        return redirect('profile')  

return render(request, 'edit_profile.html', context={'userprofile_form': userprofile_form)

并在html中使用:

<form action="." method="post">
    {% csrf_token %}    
    Phone Number: {{ userprofile_form.phone_number }}
    Birthday: {{ userprofile_form.Birthday }}
    city: {{ userprofile_form.city }}
    school: {{ userprofile_form.school }}
    course: {{ userprofile_form.course }}           
    <input type="submit" value="Save Changes" name="save" />
    <input type="reset" value="Cancel" name="cancel" />
    <br/>
</form>

或者只是

 <form action="." method="post">
     {% csrf_token %}    
     {{ userprofile_form }}           
     <input type="submit" value="Save Changes" name="save" />
     <input type="reset" value="Cancel" name="cancel" />
     <br/>
 </form>

如果您要使用上传文件,请不要忘记将文件放入表格中,您可以这样做 UserProfileForm(request.POST, request.FILES, instance = UserProfile.objects.get(user=request.user)) 在html中,您需要放置<form enctype="multipart/form-data" method="post" action="...">

答案 1 :(得分:1)

重现这些步骤,您可能需要进行一些修改:

1。创建一个UserEditForm

forms.py

from .models import UserProfile
from django.forms import ModelForm

class UserEditForm(ModelForm):
    class Meta:
        model = UserProfile
        fields = '__all__' # or ['phone_number', 'Birthday', 'city', 'only_fields_you_want_to_edit']

2。创建视图:

在views.py

from django.shortcuts import render, HttpResponseRedirect, get_object_or_404
from django.urls import reverse
from django.forms.models import model_to_dict
from .models import UserProfile
from .forms import UserEditForm

def userEdit(request, user_id):
    user = get_object_or_404(Question, pk=user_id)
    if request.method == "GET":
        form = UserEditForm(initial=model_to_dict(user))
        return render(request, 'yourapp/useredit_form.html', {'form':form)
    elif request.method == "POST":
        form = UserEditForm(request.POST, instance=user)
        if form.is_valid():
             form.save()
             return HttpResponseRedirect(reverse('user_profile', kwargs={'uid':user.id}))
        else:
             return HttpResponseRedirect(reverse('some_fail_loc'))

3。创建模板

在yourapp / useredit_form.html

<form method="POST">
    {% csrf_token %}
    {{form}}
    <button type="submit">Submit</button>
</form>

4。设置网址:

在urls.py

urlpatterns += [
    path('edit_user/<int:user_id>/', views.userEdit, name='user_edit'),
]

现在尝试访问yourapp.com/edit_user/1。你已准备好出发。 :D