models.py:
afterEach
views.py:
class User(models.Model):
sex_choices=(('M', 'Male'), ('F', 'Female'))
category_choices=(('S', 'Student'),('T', 'Teacher'),('G', 'Guardian'))
qual_choices = (('a', 'Secondary'),('b', 'Senior Secondary'),('c', 'Undergraduate'),('d', 'Postgraduate'))
area_choices = (('CS', 'Computer Science'),('Maths', 'Mathematics'),('Phy', 'Physics'),('Chem','Chemistry'),('Bio', 'Biology'))
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=30)
age = models.PositiveSmallIntegerField()
sex = models.CharField(max_length=1, choices=sex_choices)
contact = models.CharField(max_length=10)
email = models.EmailField(unique=True)
category = models.CharField(max_length=1, choices=category_choices)
qualification = models.CharField(max_length=1, choices=qual_choices)
area = models.CharField(max_length=5, choices=area_choices, null=True)
current_institution = models.CharField(max_length=30)
about = models.TextField(null=True)
password = models.CharField(max_length=20)
urls.py:
class UserDetailView(DetailView):
model = User
def get_context_data(self, **kwargs):
context = super(UserDetailView, self).get_context_data(**kwargs)
return context
模板/ profile.html:
urlpatterns = [
url(r'^profile/(?P<slug>[-\w]+)/$', views.UserDetailView.as_view(), name='profile')]
我只想显示当前用户的详细信息,即显示类User的对象的字段。我无法弄清楚如何创建相同的视图。请帮忙。
答案 0 :(得分:0)
在UserDetailView
中,您需要致电get_object()
以获取特定对象:
class UserDetailView(DetailView):
model = User
def get_context_data(self, **kwargs):
context = super(UserDetailView, self).get_context_data(**kwargs)
user = super(UserDetailView, self).get_object()
context['user'] = user
return context
注意强>
在您的网址中,您使用了
slug
作为用户/个人资料标识符。除非我错了,否则你的模型不是PK领域。 Django的DetailView
需要一个代表模型PK的值。例如。如果你的模型有字段UUID
作为PK,则url应该有一个有效的uuid,以便Django可以获取该对象。如果slug
已用作命名组,(DetailView
使用pk
作为默认值),则需要将视图中的pk_url_kwarg
设置为slug
} {iepk_url_kwarg = 'slug'
。
参考文献: