为什么我在views.py中的查询给了我一个TypeError?

时间:2014-11-16 22:14:40

标签: django django-queryset

访问用户评论页面时出现以下错误:

TypeError at /reviews/ben/
show_reviews() got an unexpected keyword argument 'username'

但是,当我在django控制台中运行相同的查询(即; b = UserReview.objects.all,print b)时,所有内容都会打印出来,我可以看到所有已发布的评论。我不确定我是否在我的show_reviews()方法中犯了一个简单的错误,或者问题是否比这更深入。这是我的代码。

models.py

class UserReview(models.Model):
    name= models.ForeignKey(User, related_name='usersbeingreviewed', null=True, blank=True)
    author = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='reviewauthors')
    pub_date=models.DateTimeField(auto_now_add=True)
    stars = models.IntegerField(max_length=5)
    comment = models.CharField(max_length=100)

    def __str__(self):
        return u'%s %s %s %s %s' % (self.name, self.author, self.pub_date, self.stars, self.comment)

urls.py

urlpatterns = patterns('',

    url(r"^reviewseller/(?P<test>\w+)/$", get_review),
    url(r"^reviews/(?P<username>\w+)/$", show_reviews))

views.py

def get_review(request, test):
    if request.method == 'POST':
        p = UserReviewForm(request.POST)
        testname = User.objects.get(username=test)
        if p.is_valid():
            reviewform=p.save(commit=False)
            reviewform.name=testname
            reviewform.author=request.user
            reviewform.save()
            return HttpResponseRedirect('/thanks/')

def show_reviews(request):
    latest_reviews = UserReview.objects.all()
    context1 = {'latest_reviews': latest_reviews}
    return render(request, 'reviews.html', context1)

forms.py

class UserReviewForm(ModelForm):
     class Meta:
         model = UserReview
         fields = ['stars', 'comment']
         widgets = {
         'comment': Textarea,
         'stars': RadioSelect(choices=[
             (1, 'Very poor'),
             (2, 'Poor'),
             (3, 'Satisfactory'),
             (4, 'Great'),
             (5, 'Excellent')
             ])
         }

我之前遇到的另一个问题是ReviewSeller表单保存了用户名字符串而不是用户实例,所以我不知道这些是否是相关问题?

1 个答案:

答案 0 :(得分:1)

根据配置的网址:

url(r"^reviews/(?P<username>\w+)/$", show_reviews)

您正在从网址抓取username。你的观点应该把它作为一个论点:

def show_reviews(request, username):
    ...