我有两个模型:User
和UserProfile
第一个包含username
,first_name
等字段。第二个包含Django管理员的所有额外字段不提供,但我需要它,如:reputation
。我的问题是,如何从两个模型中获取所有数据?
urls.py
from django.conf.urls import patterns, include, url
from userprofiles.views import UserDetailView
urlpatterns = patterns('',
url(r'^profile/username/(?P<slug>[\w.@+-]+)/$', UserDetailView.as_view()),
)
models.py
class UserProfile(models.Model):
user = models.OneToOneField(User)
reputation = models.IntegerField(default=1, null=True)
views.py
from django.views.generic.detail import DetailView
# from .models import UserProfile (This contains custom fields)
from django.contrib.auth.models import User
class UserDetailView(DetailView):
model = User
slug_field = 'username'
def get_template_names(self):
return 'profile.html'
profile.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Profile</title>
</head>
<body>
<section>
{{user.username}}<br>
{{userprofile.reputation}}<br>
</section>
</body>
</html>
此时我访问http://localhost:8000/profile/username/MY_USERNAME/
答案 0 :(得分:1)