我希望让我的学生在登录后更新自己的个人资料,但我似乎无法正确编写个人资料更新代码。这是我的代码:
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.icon)
.setContentTitle(titleDisplay)
.setContentText(contentDisplay)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);

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>
&#13;
答案 0 :(得分:1)
错误'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})
答案 1 :(得分:1)
我更喜欢这种解决方法,你仍然需要login_required装饰器。
在models.py中添加
User.student = proberty(lambda p: Student.objects.get_or_create(user = p)[0])
然后在views.py中,您可以执行以下操作:
student = request.user.student
if request.method != 'POST':
form = StudentForm(instance=student)
else:
form = StudentForm(request.POST, instance=student)
答案 2 :(得分:0)
这是这个问题的完美答案。只需粘贴您处理过更新配置文件的 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')
在 urls.py 中定义为 views.home
。确保在运行之前已将其替换为您的视图。
path(r'user/updateProfile/<int:id>', views.handleUpdate, name="handleUpdate")
action="/user/updateProfile/{{request.user.id}}" method="POST"
请记住:user.id
仅在用户登录时有效