0
我目前使用的是Django all-auth,它有一個/ accounts/profile頁面,我想用創建/填充更新用戶信息的表單。使用OneToOne字段和用戶模型創建User Profile頁面
我有一個老師字段,它擴展了使用OneToOne字段的用戶模型。
models.py
class Teacher(models.Model):
user = models.OneToOneField(User, on_delete=models.PROTECT, related_name='Teacher')
bio = models.TextField(max_length=500, blank=True)
availability = models.BooleanField(default=False)
teacher_logo = models.FileField()
這個老師模型是我希望用戶在/帳號/更新個人資料的內容。
forms.py
class UserForm(forms.ModelForm):
class Meta:
model = User
fields = ('first_name', 'last_name', 'email')
class TeacherForm(forms.ModelForm):
class Meta:
model = Teacher
fields = ('availability', 'bio','teacher_logo')
views.py
@login_required
@transaction.atomic
def update_profile(request):
if request.method == 'POST':
user_form = UserForm(request.POST, instance=request.user)
teacher_form = TeacherForm(request.POST, instance=request.user.teacher)
if user_form.is_valid() and teacher_form.is_valid():
user_form.save()
teacher_form.save()
messages.success(request, _('Your profile was successfully updated!'))
return redirect('users:index')
else:
messages.error(request, _('Please correct the error below.'))
else:
user_form = UserForm(instance=request.user)
teacher_form = TeacherForm(instance=request.user.teacher)
return render(request, 'accounts/profile.html', {
'user_form': user_form,
'teacher_form': teacher_form
})
模板用戶/ profile.html
<form method="post">
{% csrf_token %}
{{ user_form.as_p }}
{{ teacher_form.as_p }}
<button type="submit">Save changes</button>
</form>
urls.py
url(r'^profile/$', views.update_profile, name='Update-Profile')
我可以使用更新的觀點,但後來我需要在URL,這似乎是這樣做的一個不正確的方法來指定;另外,用戶將能夠編輯其他配置文件。
當我運行上述內容時,我得到一個抱怨,'用戶'對象沒有屬性'老師'。
當我刪除.teacher
從TeacherForm(instance=request.user.teacher)
它加載頁面的形式,但是當我更新,它仍然給了我同樣的抱怨
EDIT(在views.py兩地刪除):models.py額外
@receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
if created:
Teacher.objects.create(user=instance)
@receiver(post_save, sender=User)
def save_user_profile(sender, instance, **kwargs):
instance.Teacher.save()
或只是不設置它在所有的,在這種情況下,默認會'teacher'反正。 –
謝謝,我仍然得到:異常值:\t '用戶'對象沒有屬性'老師'異常位置:\t /Users/gr/Desktop/PycharmProjects/DjangoWebsite/accounts/models.py in save_user_profile,第45行(文件沒有第45行) – Roma
您是否創建了'Teacher'實例? –