How to make the user in a model default to the current user

0 votes

I want to do this so I can hide it in the admin view mainly but also because when I save an instance I don't want to be filling it every time

I have the following:

from django.contrib.auth.models import User

class ClientDetails(models.Model):
    created_by = models.ForeignKey(User)
    ...

How do I make created_by default to the currently logged in user?

Jun 12, 2020 in Python by kartik
• 37,520 points
4,065 views

1 answer to this question.

0 votes

Hello @kartik,

You have to override get_changeform_initial_data method in your model Admin class in admin.py as follows:

# admin.py

class ClientDetailsAdmin(admin.ModelAdmin):
    def get_changeform_initial_data(self, request):
        get_data = super(ClientDetailsAdmin, self).get_changeform_initial_data(request)
        get_data['created_by'] = request.user.pk
        return get_data

admin.site.register(ClientDetails, ClientDetailsAdmin)

In such way you obtain the most elegant solution since the created_by field is filed up when you create new record.

Hope this works!

answered Jun 12, 2020 by Niroj
• 82,840 points

Related Questions In Python

0 votes
1 answer

How to extend the User model with custom fields in Django?

Hello @kartik, Define an object manager for your ...READ MORE

answered Aug 3, 2020 in Python by Niroj
• 82,840 points
3,176 views
0 votes
1 answer

How to hide a window in the constructor immediately after creation?

You can use QtCore.QTimer class Example(QWidget):     def __init__(self, app):         QWidget.__init__(self)         QTimer.singleShot(0, ...READ MORE

answered Apr 17, 2018 in Python by anonymous
903 views
0 votes
1 answer

How to get the size of a string in Python?

If you are talking about the length ...READ MORE

answered Jun 4, 2018 in Python by aryya
• 7,460 points
1,373 views
0 votes
3 answers

How to get the current time in Python

FOLLOWING WAY TO FIND CURRENT TIME IN ...READ MORE

answered Apr 8, 2019 in Python by rajesh
• 1,270 points
2,074 views
0 votes
3 answers

Python Selenium best tutorials for beginners

Hope this will help you...Python Tutorial READ MORE

answered Feb 11, 2019 in Python by aldrinjohn
• 140 points
3,932 views
0 votes
1 answer
0 votes
1 answer

How to access the user profile in a Django template?

Hello @kartik, In your profile model provide related_name user ...READ MORE

answered Jul 29, 2020 in Python by Niroj
• 82,840 points
6,054 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP