get Profile filed data

I want to get the Service name of all my users in function.
I have

class Profile(models.Model):
    image    = models.ImageField(default='default.jpg', upload_to='profile_pics')
    user     = models.OneToOneField(User, on_delete=models.CASCADE)
    Service  = models.CharField(max_length=30 ,default='Guest')
    def __str__(self):
        return self.user.username+' '

And In my I have this function

def dashboardView(request):
    My_staff =[]
    Non_valid =[]
    Head_service = str(request.user.groups.all()[0])

    for Usr_Name in User.objects.all(): 
        User_Group =Usr_Name.groups.all()[0]
        if User_Group == "Guest":
            pk_prf = str(
            Profile_service = Profile.objects.filter(user_id=pk_prf)
            if  Profile_service.Service == Head_service:
                Non_valid += [Usr_Name]
            elif User_Group == Head_service:
                My_staff += [Usr_Name]

    context = {
        'title': 'Edit Profile',
        'Non_valid': Non_valid
    return render(request, 'user/dashboard.html', context)

the problem that I can’t fetch the user service in Profile model and add it to Non_valid list.
in the page it gives me this error

'Group' object has no attribute 'Service'

Many thanks in advance

We’re probably going to need more information here.

Posting the complete error is usually more helpful than just posting one line. We can’t tell what line is generating this error or what file should be looked at to answer your question.

1 Like

The only place I see - in this bit of code at least - that could be generating this error is this:

Profile_service is generated using a filter, when what you really want is a get. filter returns a queryset, so you would need to take the first value from that, either using first() or just [0] - that would give you an instance of a Profile - assuming that that filter actually matches a record that is!

Using get instead of filter is probably better though - that will return an object, though will fail if the key you specify does not exist, so you’d need to handle that.

Also, you have some very strange naming conventions here - these would likely get picked up in code review at a company.

Classnames should be like ClassName
Method names should be like method_name
Variable names should be lower case: service not Service, head_service not Head_service

The code will run with the unusual conventions, but it makes things harder to read, as most coders will, for example, look at a reference to Service and initially assume it’s a class/model …

1 Like

Many thanks for all of you, I fixed the error by:

        if str(User_Group) == 'Guest':
            pk_prf = str(
            Profile_service = Profile.objects.get(user_id__exact=pk_prf)
            if str(Profile_service.Service) == str(Head_service):
                Non_valid += [Usr_Name]
        elif User_Group == Head_service:
            My_staff += [Usr_Name]
1 Like