Django用户档案匹配查询不存在。

3
我正在使用这个教程http://lightbird.net/dbe/forum2.html制作一个论坛,但是遇到了错误。

当我点击编辑资料时,本应该跳转到该页面,但我收到了以下错误信息(如下图所示):

enter image description here

 DoesNotExist at /forum/profile/1/

 UserProfile matching query does not exist.

 Request Method:    GET
 Request URL:   http://127.0.0.1:8000/forum/profile/1/
 Django Version:    1.4.3
 Exception Type:    DoesNotExist
 Exception Value:   

 UserProfile matching query does not exist.

 Traceback Switch to copy-and-paste view

 C:\djcode\mysite\forum\views.py in profile

         profile = UserProfile.objects.get(user=pk)

我认为这个错误意味着,Django无法接收我的管理员登录。

这是我的fbase.html的一部分。

  <a href="{% url ben:profile user.pk %}">Edit profile</a>

这指向我的URL配置。

  from django.conf.urls import patterns,include,url
  from django.contrib import admin
  from django.conf import settings

  urlpatterns = patterns('forum.views',
                   url(r'^$','main',name='main'),
                   url(r"^forum/(\d+)/$", "forum",name ="forum"),
                   url(r"^thread/(\d+)/$","thread",name = "thread"),
                   url(r"^post/(new_thread|reply)/(\d+)/$", "post",name = "post"),
                   url(r"^reply/(\d+)/$", "reply" , name ="reply"),
                   url(r"^new_thread/(\d+)/$", "new_thread" , name  ="new_thread"),
                   url(r"^profile/(\d+)/$", "profile",name= "profile"),
  )

并进入我的视图函数

  def profile(request, pk):
      """Edit user profile."""
      profile = UserProfile.objects.get(user=pk)
      img = None

      if request.method == "POST":
          pf = ProfileForm(request.POST, request.FILES, instance=profile)
          if pf.is_valid():
              pf.save()
              # resize and save image under same filename
              imfn = pjoin(MEDIA_ROOT, profile.avatar.name)
              im = PImage.open(imfn)
              im.thumbnail((160,160), PImage.ANTIALIAS)
              im.save(imfn, "JPEG")
      else:
          pf = ProfileForm(instance=profile)

      if profile.avatar:
          img = "/media/" + profile.avatar.name
      return render_to_response("forum/profile.html", add_csrf(request, pf=pf, img=img))

这是我的 models.py 文件

  from django.db import models
  from django.contrib.auth.models import User
  from django.contrib import admin
  from string import join
  from mysite.settings import MEDIA_ROOT

  class Forum(models.Model):
      title = models.CharField(max_length=60)
      def __unicode__(self):
          return self.title
      def num_posts(self):
          return sum([t.num_posts() for t in self.thread_set.all()])

      def last_post(self):
          if self.thread_set.count():
              last = None
              for t in self.thread_set.all():
                  l = t.last_post()
                  if l:
                      if not last: last = l
                      elif l.created > last.created: last = l
              return last
  class Thread(models.Model):
      title = models.CharField(max_length=60)
      created = models.DateTimeField(auto_now_add=True)
      creator = models.ForeignKey(User, blank=True, null=True)
      forum = models.ForeignKey(Forum)

      def __unicode__(self):
          return unicode(self.creator) + " - " + self.title
      def num_posts(self):
          return self.post_set.count()

      def num_replies(self):
          return self.post_set.count() - 1

      def last_post(self):
          if self.post_set.count():
              return self.post_set.order_by("created")[0]
  class Post(models.Model):
      title = models.CharField(max_length=60)
      created = models.DateTimeField(auto_now_add=True)
      creator = models.ForeignKey(User, blank=True, null=True)
      thread = models.ForeignKey(Thread)
      body = models.TextField(max_length=10000)

      def __unicode__(self):
          return u"%s - %s - %s" % (self.creator, self.thread, self.title)

      def short(self):
          return u"%s - %s\n%s" % (self.creator, self.title, self.created.strftime("%b %d, %I:%M %p"))
short.allow_tags = True

  ### Admin

  class ForumAdmin(admin.ModelAdmin):
      pass

  class ThreadAdmin(admin.ModelAdmin):
      list_display = ["title", "forum", "creator", "created"]
      list_filter = ["forum", "creator"]

  class PostAdmin(admin.ModelAdmin):
      search_fields = ["title", "creator"]
      list_display = ["title", "thread", "creator", "created"]
  class UserProfile(models.Model):
      avatar = models.ImageField("Profile Pic", upload_to="images/", blank=True, null=True)
      posts = models.IntegerField(default=0)
      user = models.ForeignKey(User, unique=True)

      def __unicode__(self):
          return unicode(self.user)
1个回答

2
您在渲染时忘记了添加 pk 参数:
return render_to_response("forum/profile.html", add_csrf(request, pf=pf, 'profile': profile, img=img))

在HTML中:

<a href="{% url ben:profile profile.id %}">Edit profile</a>

“关键字不能是表达式”('C:\ djcode \ mysite \ forum \ views.py',56,无,'return render_to_response(“forum / profile.html”,add_csrf(request,pf = pf,img = img,'pk'= pk))\ n')我遇到了这个错误,卡西。 - donkeyboy72
好的,我更新了我的答案,将其更改为“个人资料”。还有一件事,如果输出为空,则用户必须进行身份验证以获取ID。 - catherine
"关键字不能是表达式",('C:\djcode\mysite\forum\views.py',56,无,'return render_to_response("forum/profile.html", add_csrf(request, 'profile'=profile, img=img ,pk=pk))\n') - donkeyboy72

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接