1
votes

I have two models: User (pre-defined by Django) and UserProfile that are connected through a foreign key.

class UserProfile(models.Model):
    user = models.OneToOneField(User, related_name="connect")
    location = models.CharField(max_length=20, choices=LOCATION_CHOICES)
    gender = models.CharField(max_length=20, choices=GENDER_CHOICES)

The User model contains fields such as username, first_name, last_name, and password.

In my view, I want to find a UserProfile object using the username field which is located in the User Object. To filter/get a UserProfile object with the username field, I need to "travel" through the Foreign Key to access the User Model.

However, I got several errors in trying to do this. Does anyone know how I can do this?

This is what I have so far:

def edit(request):
    #the line below is where I am facing troubles. 
    #The error I'm getting is SyntaxError: keyword can't be an expression
    user = UserProfile.objects.filter(user.username=request.user.username)

    form1 = UserEditForm()
    form2 = UserProfileEditForm()
    c = RequestContext(request, {
        'action': 'update/',
        'button': 'Update', 
        'form1': form1,
        'form2': form2,
        })
    return render_to_response('registration/user_profile.html', c)

Does anyone know how to solve this? Thanks!

1
by the way, you don't actually use user.. is that intentional? - Hamish
yes, i use it later on in the template - goelv
Ok, just not in your example above? - Hamish

1 Answers

4
votes

Use double underscores (__) to traverse relationships. E.g.:

user = UserProfile.objects.filter(user__username=request.user.username)

However, in your case, you don't need to do this. request.user is a User object, so to get their UserProfile just do:

user = request.user.get_profile()

or even:

UserProfile.objects.get(user=request.user)

Note that your first example should return a QuerySet with 1 result, whereas the second returns a single object. In other words:

request.user.get_profile() == 
    UserProfile.objects.filter(user__username=request.user.username)[0]