Nicolás Curti Nicolás Curti - 5 months ago 11
Python Question

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

I have created a custom model in models.py

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 admin.py, 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
admin.site.unregister(User)
admin.site.register(User, 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

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 }}
Comments