#How to show User FirstName LastName (UserName)
73 messages · Page 1 of 1 (latest)
Override dunder repr method in your model: python class YourModel(models.Model): first_name = models.CharField(max_length=16) last_name = models.CharField(max_length=16) ... def __repr__(self): return f"{self.first_name} {self.last_name}"
You can manipulate the __str__ function, for example:
In your User model:
class User(models.Model):
first_name = models.CharField(max_length=100)
last_name = models.CharField(max_length=100)
username = models.CharField(max_length=100)
def __str__(self):
return f"{self.first_name} {self.last_name} ({self.username})"
repr is used for objects internal representation, str is used for human readable format
These not true answer.
Do you know if repr show in the admin panel?
Yes, Admin uses repr to show the objects
What you mean?
My bad, Admin uses str for display
No problem xD
For exampla
class pool(models.Model)
question = models.CharField(max_length=100)
creator = models.ForeignKey(User, on_delete=models.CASCADE)
How to show user name format?
A few special cases to note about list_display:
If the field is a ForeignKey, Django will display the __str__() of the related object.
ManyToManyField fields aren’t supported, because that would entail executing a separate SQL statement for each row in the table. If you want to do this nonetheless, give your model a custom method, and add that method’s name to list_display. (See below for more on custom methods in list_display.)
If the field is a BooleanField, Django will display a pretty “yes”, “no”, or “unknown” icon instead of True, False, or None.
If the string given is a method of the model, ModelAdmin or a callable, Django will HTML-escape the output by default. To escape user input and allow your own unescaped tags, use format_html().
Check your project. Look history of any model You will see format.
Fyi
Python's dunder repr is supposed to be the unambiguous representation of an object, dunder string is the sort of display property of an object
Django utilizes practically only the dunder str method
You want to show User model information outsite class of Model user?
Yes, I just checked. I was under the impression that since repr is internal representation of an object, Admin uses that. But I was wrong.
yes
in Admin Display List
You can create a custom modeladmin and create a new method which returns the formatted string of the user's name.
You could also override the model's dunder str method, that'll require you to override your user model (which is something you should practically ALWAYS do, anything else is going to be annoying later on)
This section of the docs might be helpful
https://docs.djangoproject.com/en/5.0/ref/contrib/admin/#django.contrib.admin.ModelAdmin.list_display
In fact, where Django offers, the first name and last name are kept. I map user information in the model. When I show it in admin, only username appears. I don't understand what specific model to create for this?
A custom user model and swap out the default one
Changing away from it later on in production can be very annoying
I've looked here before. A guide that explains nothing. (For my problem.)
^ thats for a custom user model
I can't really get much into code as im not on a pc right now, but i'll try regardless, just give me time xD
Why am I creating a custom user model? Oh patience!
Listen!
Open one project .
Edit something in your app.
Check history.
You will see (username) First name, Last name
Now... Why am I crating custom... ?
easy devweb, slow down
we are trying to help
🙂
Ahh why
During the lifecycle of development and the runtime you'll build more and more things that relate to the user model
As time goes on you will probably find something about the default user model you want to change
Now you'll have to swap out an existing user model for your new custom one
That means migrating EVERY SINGLE relation to your old model, possibly dropping constraints to make that possible, recreating a lot of constraints and then finally deleting the default user model from the database
If you swap out the user model at the beginning of a project that entire ordeal gets a whole lot easier as django's migration system does most of the heavy lifting for you
It'd be better if you explain what you're seeing in admin panel, and what is your expectation.
Plus, Django allows creation of User model in it's first migration only. So, if you choose to define a custom user from start, you'd save yourself a lot of trouble. However, Django's inbuilt user model is better suited for most of things you'd want to implement.
Ok, thnks for info. But no answer for this title. Think it. You have some models. And using foreginkey. But you want to show fields in admin display list. What is your way?
Include those fields in the modeladmin's list_display list
You can refer to foreignkey objects using a double underscore
from django.contrib import admin
from .models import User
class UserAdmin(admin.ModelAdmin):
list_display = ('full_name', 'username')
def full_name(self, obj):
return f"{obj.first_name} {obj.last_name}"
full_name.short_description = 'Full Name' # Sets the column header
admin.site.register(User, UserAdmin)
# This is a snippet from Django Documentation
# Considering your model has a creator field which is user ForeignKey
class PoolAdmin(admin.ModelAdmin):
list_display = ["upper_case_name"]
@admin.display(description="Creator")
def upper_case_name(self, obj):
return f"{obj.creator.first_name} {obj.creator.last_name}".upper()
admin.site.register(Pool, PoolAdmin)
``` Is this what you're looking for?
So if i've got a foreignkey from my user model which points to lets say a house, and the field is called "house", and every house has an address my list_display would include "house__name" for displaying the house name besides the user
I want to show "user_first_name user_last_name (username)" format from info default user model or custom user model. Used foreginkey but only show username. IN EVERY APPS. NOT ANY USER PROFILE MODEL.
Do you only want to show that in the django admin for now?
Yes.
Not worked. Until only username.
Then you can take exactly what RB sent. A custom modeladmin with a method which returns the appropriate string. (Thats also in the docs that i've sent you)
In any case i'd suggest doing the official django tutorial, it covers stuff like this
https://docs.djangoproject.com/en/5.0/intro/tutorial01/
and mine?
list_display = ('full_name', 'username') ????????????????????????????
My model has not these fields.
Make sure you restarted your webserver when you do changes (or make sure runserver is live reloading)
I think you're confusing us. In your admin panel you'd have a User model (Django's inbuilt) and Pool model. Now, do you want to see the creator fields (first_name, last_name and username) for Pool objects or for User objects? Cause if it's latter, you need to extend UserAdmin from BaseUserAdmin and do what I did earlier. If it's for Pool model, PoolAdmin should work with some tweaks based your actual code.
oh, you can't
I cant send...
this solution look like my question answwer. But not worked.
Bruh, you need to tell us for which model do you want to see those fields?
List display are broken?
User or Pool?
Pool
Come on CHAT #856567261900832812
Of course
writeeeeeeeeeeeeee
In your list_display add "upper_case_name"
return f'{self.first_name} {self.last_name} ({self.username})'
class YourModelAdmin(admin.ModelAdmin):
list_display = ('your_field', 'username', 'first_name', 'last_name')
def username(self, obj):
return obj.user.username
def first_name(self, obj):
return obj.user.first_name
def last_name(self, obj):
return obj.user.last_name
admin.site.register(YourModel, YourModelAdmin)
DONE!
Solution:
@admin.register(YourAppsModel)
class YourAppsModelAdmin(admin.ModelAdmin):
readonly_fields = ('creator', 'create_at')
list_display = ["YourAppsModelField", "myCreatorFormat",]
def myCreatorFormat(self, obj):
return f'{obj.creator.first_name} {obj.creator.last_name} ({obj.creator.username})'