【问题标题】:Django Url error: invalid literal for int() with base 10: 'tony'Django Url 错误:int() 以 10 为底的无效文字:'tony'
【发布时间】:2012-05-14 20:43:12
【问题描述】:

我正在创建一个带有用户的小 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")

【问题讨论】:

    标签: python regex django django-views django-urls


    【解决方案1】:
    u = UserProfile.objects.get(user__username=username)
    

    看起来您正在搜索用户的用户名属性。在 django 中,外键由双下划线分隔。

    https://docs.djangoproject.com/en/dev/topics/auth/

    https://docs.djangoproject.com/en/dev/topics/db/queries/

    另外.get() 将抛出DoesNotExist 异常,建议将查询包装在 try: except 块中,这样它不会对用户产生 500。 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)
    

    【讨论】:

      【解决方案2】:

      为了更简洁的代码,请改用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。但这只是一个家务细节。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-01-22
        • 1970-01-01
        • 1970-01-01
        • 2017-05-18
        • 2019-03-16
        • 2021-01-28
        • 1970-01-01
        • 2013-05-14
        相关资源
        最近更新 更多