Django UpdateView: Object To Update Has No Values
I'd like to update an object with generic view updateview. The problem arises when I edit an object. Instead of reaching a prefilled form, I reach a blank form. My template for thi
Solution 1:
I think your UpdateView
is not returning the right object for your template. Have you tried this:
class HabitUpdate(UpdateView):
model = Habit
form_class = HabitForm
template_name = 'habits/update_habit.html'
success_url = reverse_lazy('display_habits')
def get_initial(self):
initial = super(HabitUpdate, self).get_initial()
print('initial data', initial)
# retrieve current object
habit_object = self.get_object()
initial['field1'] = habit_object.field1
initial['field2'] = habit_object.field2
....
....
return initial
def get_object(self, *args, **kwargs):
habit = get_object_or_404(Habit, pk=self.kwargs['pk'])
return habit
And you only need this in your forms.py
file:
class HabitForm(forms.ModelForm):
class Meta:
model = Habit
fields = ( 'title', 'trigger', 'existingroutine', 'targetbehavior', 'image')
Post a Comment for "Django UpdateView: Object To Update Has No Values"