【发布时间】:2016-06-26 10:31:50
【问题描述】:
我的模板生成的 URL 是:/user/username 例如:/user/tainawilkins
<a href="user/{{ user.userprofile.slug }}"
style="color:rgba(0,0,200,1.00)">{{ user.username }} {{ user.first_name }} {{ user.last_name }}</a>
它调用了这个视图:
def user(request, user_name_slug):
context_dict = {}
try:
# Can we find a city name slug with the given name?
# If we can't, the .get() method raises a DoesNotExist exception.
# So the .get() method returns one model instance or raises an exception.
user = User.objects.select_related('UserProfile').get(slug=user_name_slug)
context_dict['user_username'] = user.username
context_dict['user_firstname'] = user.first_name
context_dict['user_secondname'] = user.second_name
context_dict['user'] = user
except User.DoesNotExist:
pass
# Go render the response and return it to the client.
return render(request, 'user.html', context_dict)
User 模型是 django 内置模型,这是 UserProfile:
# this is model for user
class UserProfile(models.Model):
user = models.OneToOneField(User)
profilepic = models.ImageField(blank=True)
city = models.ForeignKey(City)
slug = models.SlugField(unique=True)
def save(self, *args, **kwargs):
self.slug = slugify(self.user.username)
super(UserProfile, self).save(*args, **kwargs)
def __unicode__(self):
return self.user.username
@property
def avg_rating(User):
return UserProfile.userrating_set.all().aggregate(Avg('rating'))['rating__avg']
我的主要问题是views.py 中的这一行,我无法让它工作。我想通过指定 UserProfile 的 slug 来拉用户(一对一的关系):
user = User.objects.select_related('UserProfile').get(slug=user_name_slug)
我收到此错误:
/user/tainawilkins 处的 FieldError 无法将关键字“slug”解析为 场地。选项有:date_joined、email、first_name、groups、hobby、id、 is_active, is_staff, is_superuser, 语言, last_login, last_name, 登录,密码,registrationprofile,user_permissions,用户名, 用户资料,用户评分
【问题讨论】:
标签: django django-models django-views