I have a question about Django-Admin. Every item in my Django admin has got the "EngagementManager" field, which contains the name of the person. When you log in Django, your username is the same as the field, which I mentioned previously.
I need to implement the feature that login user could change/edit only items when the field "EngagementManager" will match the login user. Can someone please provide me the piece of code and some little guide where to put it, please?
Django Admin is not meant for that purpose
Django Admin should only be used when the user has complete access to everything in the database. What they can edit can be restricted, but generally what they can see should not be.
It’s not intended to allow much in terms of only allowing access to certain bits of data. It is recommended that you build a custom frontend for this purpose, where it is easy to do such restrictions.
Such restriction is easy in views
and templates
. Use request.user
.
I am on my phone right now, but if you want, I can post some sample code which does this. Just comment below.
These are samples from an updateprofile
method which I have.
The core concept here is that the only data being sent to the form is that of the user of the account which is currently logged in. You would want to implement such functionality.
views.py checking for the correct user
@login_required(login_url='/login')
def update_profile(request):
if request.method == 'POST':
user_form = UserForm(request.POST, instance=request.user)
if user_form.is_valid():
user_form.save()
return redirect('/accounts/{}'.format(request.user.username), request.user.username)
else:
print("Something broke")
else:
user_form = UserForm(instance=request.user) #grabbing the data from that specific user, making sure that is all that is passed.
return render(request, 'profile_update.html', {
'user_form': user_form,
})
In the template, the if statement checks to see whether the user of the page is the owner of the logged in account (and checks that they are looed into their account) and if so, shows them the information.
template code for checking for the correct user
{% if page_username == user.username and user.is_authenticated %}
<p>Whatever content you wanted to show to the user who owned the page and was logged in.</p>
{% else %}
<p>Whatever you want to say to users who are not authorized to view the data on the page, if anything.</p>
{% endif %}