Home > front end >  Use data from get_context_data in form_valid method
Use data from get_context_data in form_valid method

Time:06-28

How can i use value from dictionary context in form_valid?

eg.

def get_context_data(self, **kwargs):
     context_data = super(ProductView, self).get_context_data(**kwargs)
     product_obj = Product.objects.get(id=self.kwargs['pk'])
     user_id = product_obj.user_id
     user_obj = User.objects.get(id=user_id)
     context_data['email'] = user_obj.email
     return context_data

def form_valid(self, form, **kwargs):
    email = context_data['email'] # need use this value
    return super(ProductView, self).form_valid(form)

CodePudding user response:

You can do it in template as hidden input:

<input type="hidden" id="id_email" name="email" value="{{ 'email' }}">

then in method:

def form_valid(self, form, **kwargs):
    email = form.data['email']
    return super(ProductView, self).form_valid(form)

CodePudding user response:

You can do something like this:

def form_valid(self, form, **kwargs):
     context_data = self.get_context_data(form=form, **kwargs)
     email = context_data['email'] # need use this value
     return super(ProductView, self).form_valid(form)

but you can also do:

def form_valid(self, form, **kwargs):
    for email in Product.objects.filter(id=self.kwargs['pk']).values_list('user__email', flat=True)[:1]:
        context_data['email'] = user_obj.email
    return super(ProductView, self).form_valid(form)

Also, if you use ProductModelForm, on form_valid you can use:

def form_valid(self, form, **kwargs):
    if hasattr(form.instance, 'user'):
        context_data['email'] = form.instance.user.email
    return super(ProductView, self).form_valid(form)

django have many ways to do it :)

  • Related