Hey folks,
-- Question for you all. Appreciate any insight you can give. So I have a class-based view (UpdateView) and a ModelForm. I want the form to pre-populate with data from a model instance. I've googled around a lot, couldn't find a plug n' play solution. I have a partial solution but it feels really hacky. It's also getting to the point where it's not working so well. I figure there must be a more djangoistic way to get this done. Here's the view from views.py. selected_task is from a hidden input where I'm storing the ID. I think there's probably a better way to do that too, but this was working for me.
class ModifyTaskView(LoginRequiredMixin, generic.UpdateView):
"""
Update an existing task.
"""
form_class=ModifyTaskForm
template_name = 'tracktasks/modifytask.html'
def form_valid(self, form):
form.instance.user = self.request.user
if form.instance.is_timed:
# convert from seconds to minutes
form.instance.total_time *=60
form.instance.remaining_time = form.instance.total_time
return super(ModifyTaskView, self).form_valid(form)
def get_initial(self):
initial = super(ModifyTaskView, self).get_initial()
task = Task.objects.get(pk=self.request.POST['selected_task'])
initial['name'] = task.name
initial['date_type'] = task.date_type
initial['is_timed'] = task.is_timed
initial['date'] = task.date
initial['total_time'] = task.total_time
initial['recurring'] = task.recurring
return initial
def get_object(self):
print(self.request.POST)
obj = Task.objects.get(pk=self.request.POST['selected_task'])
return obj;
def get_success_url(self):
return reverse_lazy('tracktasks:index')
Here's the form from forms.py, with the leading function being my current solution and the source of much headache, very nowhere going.
def display_field_values(fields, kwargs):
for field in fields:
widget = fields[field].widget
field_type = widget.__class__.__name__
initial_value = kwargs['initial'][field]
if any(item in field_type for item in ["TimeInput", "TextInput"]):
widget.attrs['value'] = initial_value
elif field_type == "CheckboxInput":
if fields[field].widget.check_test(initial_value):
widget.attrs['checked'] = ''
elif field_type == "Select":
print(field_type)
for choice in widget.choices:
if initial_value in choice:
print(choice)
print(initial_value)
# print(widget.render_option(selected_choices=initial_value, option_value=choice[0], option_label=choice[1]))
elif field_type == "SelectDateWidget":
print(widget.data)
class ModifyTaskForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(ModifyTaskForm, self).__init__(*args, **kwargs)
display_field_values(self.fields, kwargs)
class Meta:
model = Task
fields = ['id','name', 'date_type', 'date',
'is_timed', 'total_time', 'recurring']
widgets = {
'date': forms.SelectDateWidget(),
'total_time': forms.TimeInput(),
}
help_texts = {
'total_time': ('minutes.'),
}
So yeah, any insight, guidance or free advice would be a huge help. Someday I hope to return the favor by helping somebody else out. Just one person though. Don't want to go overboard.
Thanks again!
Ben
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/632817b1-4574-4131-9492-65c45ea1a5ae%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.
No comments:
Post a Comment