Reputation: 13
I've got this UpdateView I'm using to update my channels:
class ChannelUpdate(UpdateView, ProgramContextMixin):
model = ChannelCategory
form_class = ChannelForm
template_name = 'app/templates/channel/form.html'
def dispatch(self, request, *args, **kwargs):
return super(ChannelUpdate, self).dispatch(request, *args, **kwargs)
def get_success_url(self):
return reverse('channel_index', args=[self.get_program_id()])
def get_context_data(self, **kwargs):
context = super(ChannelUpdate, self).get_context_data(**kwargs)
context.update({
'is_new': False,
})
return context
def form_valid(self, form):
channel = Channel.objects.get(id=self.kwargs['pk'])
channel_codes = ChannelCodes.objects.filter(channel_id=channel.pk)
if 'is_channel_enabled' in form.changed_data:
for channel_code in channel_codes:
channel_code.is_active = channel.is_channel_enabled
channel_code.save()
return super(ChannelUpdate, self).form_valid(form)
So when I edit a Channel, I have a checkbox, which changes my bool value for my model field is_channel_enabled
to either True or False. If I do so, I trigger my if-statement in the def form_valid
method which then loops through all my channel_codes and sets their bool field is_active
to the same value as the bool field is_channel_enabled
from my Channel.
But my problem right now is: Lets say I uncheck the box and after I save my form, the bool still is True
even though I've unchecked the box and it should be False, but if I then edit my Channel again and check the box, the bool changes to False
, so that every time I check the box, the exact opposite happens: box checked = False, box unchecked = True.
But this also only happens when I do the update. If I create the channel the default value of True is correct, only when I start editing it, the wrong value gets saved. Does someone know where my problem is? Am I using form_valid wrong?
Thanks for any help!
Upvotes: 1
Views: 57
Reputation: 11665
You are not updating the latest value. you can chage the form valid method like below
def form_valid(self, form):
# channel = Channel.objects.get(id=self.kwargs['pk'])
channel_codes = ChannelCodes.objects.filter(channel_id=self.kwargs['pk'])
if 'is_channel_enabled' in form.changed_data:
for channel_code in channel_codes:
channel_code.is_active = form.cleaned_data.get('is_channel_enabled')
channel_code.save()
return super(ChannelUpdate, self).form_valid(form)
It will work.
Upvotes: 1