获取继承的类字段django

时间:2017-06-22 06:04:43

标签: python html django django-models django-templates

我正在为我的django应用程序创建自定义用户和配置文件模型。我已经为用户模型创建了一个用户模型和另一个带有OneToOneField的配置文件模型。 我想在模板中获取配置文件模型字段值,但只有我可以从当前登录用户的视图中获取用户模型的对象。如何在模板中获取配置文件模型字段值?

models.py

class UserSignup(models.Model):
    email = models.CharField(unique=True, max_length=254)
    name = models.CharField(max_length=100)
    password = models.CharField(max_length=1000)
    created_date = datetime.now()

    def __str__(self):
        return self.email

class UserProfile(models.Model):
    user = models.OneToOneField(UserSignup, on_delete=models.CASCADE)
    full_name = models.CharField(max_length=200, null=True)
    #photo = models.ImageField(upload_to="/user/image/", blank=True)
    birth_date = models.DateField(null=True)
    books_wrote = models.TextField(null=True)
    journal_wrote = models.TextField(null=True)
    address = models.TextField(max_length=2000, null=True)

    @receiver(post_save, sender=UserSignup)
    def update_user_profile(sender, instance, created, **kwargs):
        if created:
            UserProfile.objects.create(user=instance)

views.py

def user_profile(request):    
    op = UserSignup.objects.get(id=request.session['uid'])
    #here i want object of profile so i can access fields of profile in template
    return render(request, 'editor_profile.html', {'op': op})

模板

<div class="panel-heading">
            <h3 class="panel-title">{{ op.name }}</h3>
        </div>

                <div class=" col-md-9 col-lg-9 ">
                    <table class="table table-user-information">
                        <tbody>
                        <tr>
                            <td>Full Name:</td>
                            <td>{{ op.full_name }}</td>
                        </tr>

                        </tbody>
                    </table>
                </div>
            </div>
        </div>

    </div>

1 个答案:

答案 0 :(得分:2)

您可以访问OneToOne相关的UserProfile模型字段,例如

{{ op.userprofile.full_name }}
{{ op.userprofile.birth_date }}