8👍
✅
Don’t do that in the form. Override the save_model
method on your admin subclass – it has access to the request.
class MessageAdmin(admin.ModelAdmin):
def save_model(self, request, obj, form, change):
obj.user = request.user
super(MessageAdmin, self).save(request, obj, form, change)
0👍
Edit: Daniel’s way is better.
In your view:
user = request.user
if user.is_authenticated():
user_id=user.pk # pk means primary key
But you don’t usually deal with the ID. Set the User field to be the object, not the id. Here’s a snippet from something I’m working on at the moment:
def question_submit(request):
u = request.user
if u.is_authenticated():
if q.is_valid():
f=q.save(commit=False)
f.user=u
f.save()
return JsonResponse({'success': True})
- [Django]-Registration Form Unique Email
- [Django]-Dealing with legacy django project in new localized projects
- [Django]-Django REST Framework validation error: 'Enter a valid URL.'
- [Django]-Django SendGrid how to pass unique_args in EmailMultiAlternatives mail object
- [Django]-Pip install confluent-kafka gives error in mac
0👍
to avoid ERROR --- 'super' object has no attribute 'save' To resolve use ---
use this:
def save_model(self, request, obj, form, change):
obj.user = request.user
super(MessageAdmin, self).save_model(request, obj, form, change)
Source:stackexchange.com