Eric Kim
Eric Kim

Reputation: 2698

Django - UpdateView form does not save

My code for using forms inside CBV(UpdateView) won't save to DB when clicking Submit button. I don't see what's wrong.

views.py

class BHA_UpdateView(UpdateView):
    template_name = 'bha_test.html'
    context_object_name = 'bha'
    model = BHA_List
    success_url = reverse_lazy('well_list')
    pk_url_kwarg = 'pk_alt'
    form_class = BHA_overall_Form

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        api = get_well_api(self.request)
        context['single_well_bha_list'] = BHA_List.objects.filter(well=api)
        return context

    def form_valid(self, form):
        self.object = form.save()
        return super().form_valid(form)

models.py

class WellInfo(models.Model):
    api = models.CharField(max_length=100, primary_key=True)
    well_name = models.CharField(max_length=100)
    status = models.CharField(max_length=100)

class BHA_List(models.Model):
    well = models.ForeignKey(WellInfo, 'CASCADE', related_name='bha_list')
    bha_number = models.CharField(max_length=100)

class BHA_overall(models.Model):
    bha_number = models.ForeignKey(BHA_List, 'CASCADE', related_name='bha_overall')
    drill_str_name = models.CharField(max_length=111)
    depth_in = models.CharField(max_length=111)

bha_test.html

<form method="POST">
  {% csrf_token %}
  {{ form.as_p }}
  <input type="submit" class='btn btn-primary' value="Submit">
</form>

forms.py

from django import forms
from contextual.models import BHA_overall

class BHA_overall_Form(forms.ModelForm):
    class Meta():
        model = BHA_overall
        fields = '__all__'

So there is a model = BHA_List, and there is another form that is related to the model by a foreign key. The form fields will be displayed to the users, and upon clicking a submit button, it should save the user input to DB, but it doesn't. What's wrong?

Upvotes: 1

Views: 1704

Answers (1)

Omar Gonzalez
Omar Gonzalez

Reputation: 1147

Your ModelForm model doesn't match your UpdateView Model

You are declaring your ModelForm with:

model = BHA_Overall

Your UpdateView has:

model = BHA_List

Do remember that UpdateViews execute a queryset with model= so they can assign a Model instance to the ModelForm, most likely there is not match as they are different models.

Also, if you are not doing extra validations or modifyng the ModelForm.instance you don't need to override form_valid method in the UpdateView.

Upvotes: 3

Related Questions