django 在form_valid方法中使用来自get_context_data的数据

wqnecbli  于 2023-11-20  发布在  Go
关注(0)|答案(3)|浏览(100)

如何在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)

字符串

kpbpu008

kpbpu0081#

您可以在模板中将其作为隐藏输入:

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

字符串
然后在方法中:

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

lbsnaicq

lbsnaicq2#

使用Django 3.2进行测试。

def form_valid(self, form, **kwargs):
    context = self.get_context_data(**kwargs)
    _email = context['email']

字符串

4xy9mtcn

4xy9mtcn3#

你可以这样做:

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)

字符串
但你也可以这样做:

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)


此外,如果使用ProductModelForm,则可以在form_valid上使用:用途:

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有很多方法可以做到这一点:)
评论来自MagicHat
我喜欢带有“form.instance.user.email“的版本
但是如果你真的想调用get_context_data:

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

相关问题