I'm new in Django rest framework, I tried my whole day but can't do it,I want to do full crud operation in my UserProfile Model which have a OneToOne field user, User can only update their own profile and in UserProfile create or update user shouldn't update User[username], How can i achieve it Please Help me
views.py
class Profile(APIView):
def get(self, request, format=None):
try:
_profile = request.user.userprofile
except ObjectDoesNotExist:
_profile = {
"phone": '',
"image": '',
}
finally:
content = {
"first_name": request.user.first_name,
"last_name": request.user.last_name,
'phone': _profile.phone,
'image': _profile.image
}
return Response(content, status=200)
models.py
class UserProfile(models.Model):
user = models.OneToOneField(User, related_name='user_profile', on_delete=models.CASCADE)
phone = models.CharField(max_length=15,default='')
image = models.ImageField(upload_to='profile_image', blank=True)
created_date = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.user.username
Error
AttributeError at /api/
'AnonymousUser' object has no attribute 'first_name'
Request Method: GET
Request URL: http://127.0.0.1:8000/api/
Django Version: 3.0.8
Exception Type: AttributeError
Exception Value:
'AnonymousUser' object has no attribute 'first_name'
Exception Location: C:\Users\Aleem\PycharmProjects\E-Commerce\src\e_commerce_project\api\views.py in get, line 34
Python Executable: E:\OFFICCE WORK\e-commerce\Scripts\python.exe
Python Version: 3.8.2
Python Path:
['C:\\Users\\Aleem\\PycharmProjects\\E-Commerce\\src\\e_commerce_project',
'C:\\Users\\Aleem\\AppData\\Local\\Programs\\Python\\Python38-32\\python38.zip',
'C:\\Users\\Aleem\\AppData\\Local\\Programs\\Python\\Python38-32\\DLLs',
'C:\\Users\\Aleem\\AppData\\Local\\Programs\\Python\\Python38-32\\lib',
'C:\\Users\\Aleem\\AppData\\Local\\Programs\\Python\\Python38-32',
'E:\\OFFICCE WORK\\e-commerce',
'E:\\OFFICCE WORK\\e-commerce\\lib\\site-packages']
Server time: Thu, 23 Jul 2020 09:49:23 +0000