Reputation: 2698
My UpdateView does not save to local DB upon clicking Submit button.
views.py
class BHA_UpdateView(UpdateView):
template_name = 'bha_test.html'
context_object_name = 'bha'
model = BHA_overall
success_url = reverse_lazy('well_list')
pk_url_kwarg = 'pk_alt'
form_class = BHA_overall_Form
def get_object(self, queryset=None):
pk = self.kwargs.get(self.pk_url_kwarg)
api = get_well_api(self.request)
current_bha = BHA_List.objects.filter(well=api, id=pk)[0]
return current_bha
forms.py
class BHA_overall_Form(forms.ModelForm):
class Meta():
model = BHA_overall
fields = '__all__'
models.py
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>
Someone told me that in UpdateView, the model and the form should refer to the same thing. So I did that, but its still not working. Here is my original question:
How can I modify my code so that my form will save to my DB?
Update:
BHA_List
has a list of BHA objects. Each BHA objects has many child objects, BHA_overall
being one of it.
I have url that looks like this:
re_path(r'^bha/(?P<pk_alt>[-\w]+)$', base_views.BHA_UpdateView.as_view(), name='bha')
Ideally, pk_url_kwarg = 'pk_alt'
should look up objects inside BHA_List
, and navigate to a page where you can update information about that specific object inside BHA_List
. The fields you can update include the fields in BHA_overall
.
So it looks like this:
You can now edit [ BHA 2 ]: # url = .../bha/2
BHA Overall Information -
Drill_str_name: []
Depth_in: []
...
Other Child Model -
other_field: []
other_field: []
I need pk_url_kwarg = 'pk_alt'
to query BHA_List
instances to generate unique url
, and I need BHA_overall_Form
to display input fields where users can edit, and save that user input to DB. What other CBV should I use here then?
Upvotes: 0
Views: 445
Reputation: 47354
Your get_object
method returns BHA_list
object. But your view and form's model is BHA_overall
. So get_object
should also return BHA_overall
instance which you want to update:
def get_object(self, queryset=None):
pk = self.kwargs.get(self.pk_url_kwarg)
api = get_well_api(self.request)
bha_number = BHA_List.objects.filter(well=api, id=pk)[0]
current_bha = BHA_overall.objects.filter(bha_number=bha_number)[0]
return current_bha
Upvotes: 1