I am creating a little Django app with Users and I have created my own UserProfile model.. But I have some issues with my urls(atleast I think). I think the regular expressions I have used are wrong. Check it out:
the error I get:
ValueError at /usr/tony/
invalid literal for int() with base 10: 'tony'
My url:
url(r'^usr/(?P<username>\w+)/$', 'photocomp.apps.users.views.Userprofile'),
My view:
from django.shortcuts import render_to_response, get_object_or_404
from django.template import RequestContext
from django.contrib import auth
from django.http import HttpResponseRedirect
from photocomp.apps.users.models import UserProfile
def Userprofile(request, username):
rc = context_instance=RequestContext(request)
u = UserProfile.objects.get(user=username)
return render_to_response("users/UserProfile.html",{'user':u},rc)
here is my model:
from django.db import models
from django.contrib.auth.models import User
class UserProfile(models.Model):
user = models.ForeignKey(User, unique=True)
first_name = models.CharField(max_length="30", blank=True)
last_name = models.CharField(max_length="30", blank=True)
email = models.EmailField(blank=True)
country = models.CharField(blank=True,max_length="30")
date_of_birth = models.DateField(null=True)
avatar = models.ImageField(null=True, upload_to="/avatar")
It looks like you are searching for the username attribute of user. Foreign keys are spanned in django by double underscores.
https://docs.djangoproject.com/en/dev/topics/auth/
https://docs.djangoproject.com/en/dev/topics/db/queries/
Also
.get()will throw aDoesNotExistexception it is advisable to wrap the query in try: except block so that it doesn’t 500 on the user.https://docs.djangoproject.com/en/1.2/ref/exceptions/#objectdoesnotexist-and-doesnotexist