Reputation: 1673
i am new here in django python
, I am learning 2 table relations, primary key foreign key scenario, for that i am using existing django user
model and create another model userprofile
, I want to list data of user and profile, so for that i have created rest api, when i do run api http://127.0.0.1:8000/api/v1/users/
, it gives me this error : 'User' object has no attribute 'user'.
here i have added my whole code, can anyone please look my code and help me to resolve this issue ?
models.py
from django.db import models
from django.contrib.auth.models import User
from django.contrib.auth import get_user_model
class Songs(models.Model):
# song title
title = models.CharField(max_length=255, null=False)
# name of artist or group/band
artist = models.CharField(max_length=255, null=False)
def __str__(self):
return "{} - {}".format(self.title, self.artist)
class UserProfile(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
title = models.CharField(max_length=255, null=False)
dob = models.CharField(max_length=255, null=False)
address = models.CharField(max_length=255, null=False)
country = models.CharField(max_length=255, null=False)
city = models.CharField(max_length=255, null=False)
zip = models.CharField(max_length=255, null=False)
photo = models.CharField(max_length=255, null=False)
def __str__(self):
return "{} - {}".format(self.title, self.dob, self.address, self.country, self.city, self.zip, self.photo,
self.user)
serializers.py
from rest_framework import serializers
from .models import Songs
from .models import UserProfile
from django.contrib.auth.models import User
class SongsSerializer(serializers.ModelSerializer):
class Meta:
model = Songs
fields = ("title", "artist")
class UserProfileSerializer(serializers.ModelSerializer):
class Meta:
model = UserProfile
fields = ('user', 'title', 'dob', 'address', 'country', 'city', 'zip', 'photo')
class UserSerializer(serializers.ModelSerializer):
user = UserProfileSerializer(required=True)
class Meta:
model = User
fields = ('url', 'email', 'first_name', 'last_name', 'password', 'user')
extra_kwargs = {'password': {'write_only': True}}
views.py
import rest_framework.generics
from rest_framework import generics
from .models import Songs
from .serializers import SongsSerializer
from .serializers import UserSerializer
from django.contrib.auth.models import User
from rest_framework import viewsets
class ListSongsView(generics.ListAPIView):
"""
Provides a get method handler.
"""
queryset = Songs.objects.all()
serializer_class = SongsSerializer
class UserViewSet(viewsets.ModelViewSet): #generics.ListAPIView, generics.RetrieveAPIView
# viewsets.ModelViewSet
queryset = User.objects.all()
#print(queryset.count());
#exit()
serializer_class = UserSerializer
Upvotes: 0
Views: 1323
Reputation: 47354
First of all, I think you need to use a OneToOneField
for the User
- UserProfile
relation. Otherwise, one user may have multiple profiles, which is not common practice.
Now regarding the problem, the User
model doesn't have a user
attribute. You need to use related_name
to get access to the reverse related object.
To fix this problem, you can refactor your code to this:
class UserProfile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, related_name="user_profile")
class UserSerializer(serializers.ModelSerializer):
user_profile = UserProfileSerializer(required=True) # rename this field
class Meta:
model = User
fields = ('url', 'email', 'first_name', 'last_name', 'password', 'user_profile')
extra_kwargs = {'password': {'write_only': True}}
Upvotes: 2