Reputation: 2698
views.py
class BHA_UpdateView(UpdateView):
model = BHA_List
pk_url_kwarg = 'pk_alt'
form_class = BHA_overall_Form
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)
depth_out = models.CharField(max_length=111)
If I display the form fields to users using {{ form.as_p }}
in my template, it will generate a page that looks like this:
How can I override get()
or post()
method to take input from the user, and save the user input, and update a specific model instance?
With my current views.py
, user input from forms
won't save to DB because my form
refers to model = BHA_overall
, where as my model for views.py
is model = BHA_List
. But for some reason I do not want to change my model in views.py
.
If I change my CBV
to CreateView
instead of UpdateView
, it will create a new BHA_overall
instance to DB without any issue. But if I want to UPDATE a specific model instance of BHA_overall
, I first need to get()
a model instance of BHA_overall
, and update the model instance through post()
. But I do not know how to do this. How should I go about this?
Edit:
something like this:
def post():
bha_overall_instance1.bha_number = userinput.bha_number
bha_overall_instance1.drill_str_name = userinput.drill_str_name
bha_overall_instance1.depth_in = userinput.depth_in
Upvotes: 0
Views: 442
Reputation: 360
You can also use just
from django.views import View
and your views.py:
from django.views import View
from django.models import Model1, Model2
class UpdateView(View):
model = Model1
template_name = 'update.html'
def post(self, request, id, name , "other-parameters", ..., *kwargs):
obj1 = self.model1.objects.get_or_404(id=id) # this just example you can past any parameters that you want
if obj1:
obj1.name = name # updating name of obj1
obj1.save() # savin updated object
obj2 = Model2.objects.get_or_404(id=request.POST.get('id') # you must to pass name='some-id' in your template at input tag
if obj2:
obj2.some_field = some_parameter
obj2.save()
return redirect('index/') # you must choose only url that exists
I wait your feedback
Upvotes: 1