Hi, I’m trying to refactor a FBV to a CBV. The view is similar to updating a comment on a blog, but I also need to be able to update a many to many field at the same time, which is just a checkbox. I’ve managed to get it into a CBV but without the checkbox. I’m assuming that Createview is not practical as I’m accessing two models at once. How is this addressed in django? here is what I have so far using a CreateView at the moment, Please excuse the naming, it’s a little confusing but “update” refers to giving an update to a project in a meeting, it’s not a django reference:
class UpdateView(CreateView):
model = Update
form_class = ProjectUpdateForm
template_name = 'project_portal/project_update.html'
success_url = reverse_lazy('project-update')
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['project'] = Project.objects.get(slug=self.kwargs['slug'])
return context
def form_valid(self, form):
project = Project.objects.get(slug=self.kwargs['slug'])
form.instance.project_id = project.id
return super(UpdateView, self).form_valid(form)
And Here is the form I am using, the task complete is what I need to be able to update:
class ProjectUpdateForm(forms.ModelForm):
"""
Form used for adding Updates to Projects.
"""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.helper = FormHelper()
self.helper.form_method = 'POST'
self.helper.add_input(
Submit(
'Update',
'Update',
css_class='btn-primary'
)
)
task_complete = forms.BooleanField(initial=False, required=False, label='Task Complete')
class Meta:
model = Update
fields = [
'category',
'update',
]
What is the best way to do this?