0

I have a "project" model that has a "status" field. The status can be active, paused, or complete. I want to be able to update the field via form on the project detail view.

I have read a few solutions to this problem but, as a newbie, I haven't been able to get this to work. When I submit the form I get an http 405 error and the instance is not updated.

the model:

class Project(models.Model):
    title = models.CharField(max_length= 200)
    description = tinymce_models.HTMLField()
    status = models.CharField(max_length=20, choices=PROJECT_CHOICES, default="active")
    date = models.DateTimeField(auto_now_add=True, null=True)
    created_by = models.ForeignKey(CustomUser, editable=False, null=True, blank=True, on_delete=models.RESTRICT)

    objects = ProjectManager()

    def __str__(self):
        return self.title

    def get_absolute_url(self):
        return reverse('company_project:project_detail', args=[str(self.id)])

the view

class CompanyProjectsDetailView(DetailBreadcrumbMixin, FormMixin, DetailView):
    model = Project
    id = Project.objects.only('id')
    template_name = 'company_accounts/project_detail.html'
    context_object_name = 'project'
    form_class = ProjectStatusForm

    notescount = Project.objects.annotate(num_notes=Count('notes'))
    documentscount = Project.objects.annotate(num_documents=Count('project_documents'))
    todoscount = Project.objects.annotate(num_documents=Count('todo_group'))

    def form_valid(self, form):
        project = get_object_or_404(Project, id=self.kwargs.get('pk'))
        theform = form.save(commit=False)
        theform.project = project
        form.save()
        return super(CompanyProjectsDetailView, self).form_valid(form)

the form

class ProjectStatusForm(forms.ModelForm):
    class Meta:
        model = Project
        fields = ['status']
        labels = {'status': 'project status'}

        widgets = {
            'status': forms.Select(attrs={'id':'PROJECT_CHOICES'}),
        }

On the page I use this code to add the form

 <form action="" method="post">
    {% csrf_token %}
    {{ form.media }}
    {{ form|crispy }}
    </br>
    <input type="submit" value="save">
   </form>
Finn
  • 163
  • 6
  • take a look at this question I asked https://stackoverflow.com/questions/57631396/how-can-i-update-a-model-field-inside-detailview-with-a-button-click – Luis Silva May 20 '22 at 19:27
  • Luis, I took a look at this and it gives me a few ideas. Still haven't gotten it working though. – Finn May 21 '22 at 15:56
  • I believe this [question](https://stackoverflow.com/questions/45659986/django-implementing-a-form-within-a-generic-detailview]) is a little more related to what you are looking for – Luis Silva May 23 '22 at 14:53
  • Thanks Luis. I finally realized I could do it fairly simply with UpdateView. – Finn May 23 '22 at 18:30

0 Answers0