Django:如何创建一个简单的视图来显示模型的当前对象?

时间:2016-12-05 20:58:57

标签: django

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的对象的字段。我无法弄清楚如何创建相同的视图。请帮忙。

1 个答案:

答案 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 } {ie pk_url_kwarg = 'slug'

参考文献: