'Django edit the owner of Object
When an object is called via URL, I want to change the owner(user) of the object. The owner in my case is a ForeignKey.
I tried it with something like this, which of course doesn't work
def ChangeField(request, title_id):
user_title = Field.objects.filter(id=title_id,
user=request.user)
if user_title:
user_title.user = 'Admin'
user_title.save()
else:
return redirect('https://example.com')
return HttpResponseRedirect('/another')
When the user of object ID 11 for example calls the URL /11, I want to change the owner of object 11 to the superuser, I mey case the superuser is called 'Admin'
Models File
class Field(models.Model):
user = models.ForeignKey(
settings.AUTH_USER_MODEL,
default=None,
null=True,
on_delete=models.CASCADE,
)
....
Solution 1:[1]
You can use get instead of filter and set superuser as
from django.core.exceptions import ObjectDoesNotExist
from django.contrib.auth.models import User
def ChangeField(request, title_id):
try:
user_title = Field.objects.get(id=title_id,
user=request.user)
superuser = User.objects.get(is_superuser=True) # I assumed here one superuser you can get which superuser with your own condition here
user_title.user = superuser
user_title.save()
return HttpResponseRedirect('/another') # return response after successful
except ObjectDoesNotExist:
return redirect('https://example.com') # return response if object does not exists
Solution 2:[2]
Try user_title.user = request.user
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | user8193706 |
| Solution 2 | Donald Duck |
