У объекта 'ProfileForm' нет атрибута 'user'
Я изучаю Django. У меня есть модель Profile:
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 has no attribute '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'
Когда вы делаете get из таблицы Profile current = Profile.objects.get(user=profile.user.username), вы сравниваете user (экземпляр 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)