I am using django update view for my model/records
editing stuff like below
class EditProductView(LoginRequiredMixin, UpdateView):
model = Product
def get_template_names(self):
return ['website/product/edit_product.html']
def get_success_url(self):
return reverse('product_details', args=[self.kwargs['pk']])
def get_context_data(self, **kwargs):
publisher = Publisher.objects.get(product__id=self.kwargs['pk'])
context = super(EditProductView, self).get_context_data(**kwargs)
context.update(
{
'publisher':publisher,
}
)
return context
edit_product = EditProductView.as_view()
So what all i want/trying to do is alter(add some data, edit already submitted data according to website functionality) the POST
data before submitting to form,
So i know that UpdateView
has some method def def post(self, request, *args, **kwargs):
, but i dont know exactly how to use it
Suppose below is the request.POST data i am getting
<QueryDict: {u'product_name': [u'Biscuit'], u'product_price': [u'1000'], u'product_tag': [u'']}>
So now i want to alter the above QueryDict
and if the value of product_tag
was empty i need assign some default one and submit with latest querdict
Also i know that Querydict is mutable, but because of sure i need to edit the POST data, before submitting/saving to database
, i need to make that querydict as dict, then edit it, and convert back to querdict
So after all whats my question is
POST
data in UpdateView
before submitting/saving to databasepost
method heplful?The QueryDict
is mutable after you create its .copy()
. See the docs.
Update Example:
class SomeUpdateView(UpdateView):
def post(self, request, **kwargs):
request.POST = request.POST.copy()
request.POST['some_key'] = 'some_value'
return super(SomeUpdateView, self).post(request, **kwargs)
Here is much broader discussion about the topic.
Furthermore, shouldn't this be done in ModelForm
subclass? You're certainly aware you can set custom form as a form_class
in UpdateView
. Such a logic usually needs unit tests and it's much easier to unit test logic which sits in the form.