如何在Django中更新用户配置文件

yv5phkfx  于 2023-06-25  发布在  Go
关注(0)|答案(4)|浏览(130)

我想让我的学生在登录后更新他的个人资料,但我似乎无法正确地编写个人资料更新代码。这是我的代码:

class User(AbstractUser):
    pass


class Student(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True)
    name = models.CharField(max_length=30, null=True, blank=True, default=None)
    surname = models.CharField(max_length=50, null=True, blank=True, default=None)
<form method="POST" action="{% url 'profile_edit' %}" class="" >
    {% csrf_token %}
    {{ form.as_p }}
    <button type="submit">Save</button>q
</form>
def profile_edit(request):
    user = request.student
    form = StudentForm(request.POST or None, initial={'name': user.name,
                                                      'surname': user.surname})
    if request.method == 'POST':
        if form.is_valid():
            user.student.name = request.POST['name']
            user.student.surname = request.POST['surname']

            user.save()
            return HttpResponseRedirect('index')

    context = {
        "form": form
    }

    return render(request, "registration/profile_edit.html", context)
ubbxdtey

ubbxdtey1#

错误'AnonymousUser' object has no attribute 'name'表示当前用户未通过身份验证。您可以使用login_required装饰器使您的视图仅对经过身份验证的用户可用:

@login_required
def profile_edit(request):
    pass

用户模型也没有name属性,你需要访问用户的student属性来获取它:

form = StudentForm(request.POST or None, initial={'name': user.student.name,
                                                  'surname': user.student.surname})
aamkag61

aamkag612#

我更喜欢这个变通方法,你仍然需要login_required装饰器。
在您的www.example.com中models.py添加

User.student = proberty(lambda p: Student.objects.get_or_create(user = p)[0])

然后在您的www.example.com中views.py您可以执行以下操作:

student = request.user.student
if request.method != 'POST':       
    form = StudentForm(instance=student)

else:
    form = StudentForm(request.POST, instance=student)
56lgkhnf

56lgkhnf3#

这是这个问题的完美答案。只需粘贴您的views.py文件,在那里您已经处理了您的更新配置文件。

def handleUpdate(request, id):
if request.method == "POST":
    username=request.POST['username']
    email=request.POST['email']
    fname=request.POST['fname']
    lname=request.POST['lname']

    if len(username)<8:
        messages.error(request, "Your username must not be under 8 characters")
        return redirect('home')

    if len(username)>10:
        messages.error(request, "Your username must not be more than 10 characters")
        return redirect('home')

    myuser=User.objects.get(pk=id)
    myuser.first_name=fname 
    myuser.last_name=lname
    myuser.email=email
    myuser.username=username
    myuser.save()
    messages.success(request, "Your account has been updated successfully")
    return redirect('home')

记得吗

  1. email、fname和lname是表单字段的名称。请确保输入表单域名称。
  2. return redirect('home')在www.example.com中定义urls.py为views.home。在运行它之前,请确保已将其替换为视图。
  • ——————————————-
    在www.example.com中的URL urls.py
path(r'user/updateProfile/<int:id>', views.handleUpdate, name="handleUpdate")
  • ——————————————-
    表单的部分:
action="/user/updateProfile/{{request.user.id}}" method="POST"

记住:user.id仅在用户登录时工作

o0lyfsai

o0lyfsai4#

要处理这种情况,可以覆盖UsersForm类中的clean_username方法,并自定义验证逻辑以满足您的需求。下面是一个示例,说明如何修改表单以显示自定义错误消息而不是默认验证错误:

def clean_username(self):
        username = self.cleaned_data['username']
        existval = User.objects.filter(username=username)
        if self.instance:
            existval = existval.exclude(pk=self.instance.pk)
        if existval.exists():
            raise forms.ValidationError("This username is already taken !!")
        return username

相关问题