Reputation: 926
I have a feeling I am missing something obvious and syntax related here so I apologize in advance.
I am attempting to update the status of a user when they successfully process a form.
# Models.py
class Account(AbstractBaseUser):
status_list = ( ('R',"RED"), ('B',"BLUE"), ('G',"GREEN"),)
status = models.CharField(max_length=1, choices=status_list, default='R')
value = models.CharField(max_length=30, unique=False, blank=True)
#Forms.py
class Form(forms.ModelForm):
class Meta:
model = Account
fields = ('value', )
# Views.py
def View(request):
if request.POST:
form = Form(request.POST, instance=request.user)
if form.is_valid():
form.initial = {"value": request.POST['value'],}
form.save()
# Here is the issue V
Account.objects.filter(
status=Account.status).update(status='B')
return redirect('status')
I have tried the solutions presented in both of these two posts:
1. Editing model field from Views.py
2. Object has no attribute 'update'
as well as a host of other random and excessively creative combinations.
Does anyone happen to know the proper syntax for this call?
Upvotes: 1
Views: 6250
Reputation: 353
Account.objects.filter()
will return a QuerySet instead of an Account object. You need to use get()
, or filter()[0]
if you know the account exist; if you're not sure whether it exist, you can use get_or_create()
If you want to update that specific account status of current user, what you need to do is:
Step 1: get the account you want to update
# you can get it by searching from Account
account = Account.objects.get(user=request.user)
# or you can can it directly from the request.uer
account = request.user.account
Step 2: Update the field
account.status = 'B' # set it to whatever you want to update
account.save() # you need to use save() because there is no update() in a model object
Upvotes: 6
Reputation: 2823
You need to save the changes to the Account
instance, e.g.
def View(request):
if request.POST:
form = Form(request.POST, instance=request.user)
if form.is_valid():
form.initial = {"value": request.POST['value'],}
form.save()
a = Account.objects.get(user=request.user)
a.update(status='B')
# or
#a.status = 'B'
a.save()
return redirect('status')
and as @MarkLiang pointed out, filter
returns a QuerySet, not a single
instance of Account
.
Upvotes: 1