0

我正在使用用户创建一个小 Django 应用程序,并且我创建了自己的 UserProfile 模型。但是我的网址有一些问题(至少我认为)。我认为我使用的正则表达式是错误的。一探究竟:

我得到的错误:

ValueError at /usr/tony/

invalid literal for int() with base 10: 'tony'

我的网址:

url(r'^usr/(?P<username>\w+)/$', 'photocomp.apps.users.views.Userprofile'),

我的观点:

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)

这是我的模型:

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")
4

2 回答 2

3
u = UserProfile.objects.get(user__username=username)

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 a DoesNotExist exception 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

def Userprofile(request, username):
    rc = context_instance=RequestContext(request)
    try:
      u = UserProfile.objects.get(user__username=username)
    except UserProfile.DoesNotExist:
      # maybe render an error page?? or an error message at least to the user
      # that the account doesn't exist for that username?
    return render_to_response("users/UserProfile.html",{'user':u},rc)
于 2012-05-05T16:10:26.263 回答
1

要获得更简洁的代码,请改用get_object_or 404

from django.shortcuts import get_object_or_404

def Userprofile(request):
    u = get_object_or_404(UserProfile, pk=1)

另外,为了清楚起见,我建议不要给您的视图和类使用相同的名称。我会把这个函数称为类似的东西profile_detail。但这只是一个家务细节。

于 2012-05-05T17:32:44.417 回答