0

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
3

1 Answer 1

2

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}}
Sign up to request clarification or add additional context in comments.

3 Comments

getting error : 'RelatedManager' object has no attribute 'user'
@NikulPanchal Sorry forgot to replace foreignkey with onetoone in my answer. Check updates please.
You are genius :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.