Nicolás Curti Nicolás Curti - 1 year ago 63
Python Question

How to display the valueof a newly created custom model field in Django?

I have created a custom model in

class UserProfile(models.Model):
#required by the auth model
user = models.OneToOneField(User, on_delete=models.CASCADE)
NativeLanguage = models.CharField(max_length=100)
LearningLanguage = models.CharField(max_length=100)

And also created an inline in, like this:

class ProfileInline(admin.StackedInline):
model = UserProfile
can_delete = False
verbose_name_plural = 'UserProfile'

# Define a new User admin
class UserAdmin(BaseUserAdmin):
inlines = (ProfileInline, )

# Re-register UserAdmin, UserAdmin)

I can give these two new fields values in the admin app, but when I try to call them in my html, I dont know how to reference them.

<p align="center">Native Language: {{????}}</p>

It must be something simple, but I cant seem to get it.

Answer Source

First of all, model field names should be lowercase underscore separated:

class UserProfile(models.Model):
    user = models.OneToOneField(User, related_name='profile')
    native_language = models.CharField(max_length=100) 

Later anywhere in the template or a view:

{{ user.profile.native_language }}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download