[英]'ProfileForm' object has no attribute 'user'
我正在學習 Django。 我有一個 model 配置文件:
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
city = models.CharField(max_length=60)
country = models.CharField(max_length=60)
skillstolearn = models.TextField()
skillstoteach = models.TextField()
description = models.TextField()
def __str__(self):
return self.user.username
和一個表格 ProfileForm:
class ProfileForm(ModelForm):
class Meta:
model = Profile
fields = ['user', 'city', 'country', 'skillstolearn', 'skillstoteach', 'description']
我正在嘗試使用下面的視圖...
def profileupdate(request):
profile = ProfileForm(request.POST)
current = Profile.objects.get(user=profile.user.username)
print(current)
if profile.is_valid():
print('is valid')
else:
print('is not valid')
return redirect('/thecode/userpage')
...確定用戶是否已經存在,因為我想使用相同的表單來創建和更新。
我收到錯誤消息“'ProfileForm' object 沒有屬性'user'”。
如何獲得已在表單中發送的用戶的結果?
更新:以下是我收到的錯誤消息
Internal Server Error: /thecode/profileupdate/
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner
response = get_response(request)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/core/handlers/base.py", line 181, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Users/phershbe/Desktop/socialnetwork/theproject/thecode/views.py", line 45, in profileupdate
current = Profile.objects.get(user_id=profile.user.id)
AttributeError: 'ProfileForm' object has no attribute 'user'
當您從配置文件的表中獲取current = Profile.objects.get(user=profile.user.username)
時,您正在將user
(用戶的實例)與username
(字符串)進行比較。 所以你需要選擇一個需要的變體來做這件事:
1)
current = Profile.objects.get(user=profile.user)
current = Profile.objects.get(user__username=profile.user.username)
current = Profile.objects.get(user_id=profile.user.id)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.