首页 > 解决方案 > 如何从表单中获取数据?

问题描述

如何从表单 ( ProductCreateForm) 中获取数据?

如果我写form = self.get_form(),那么我只会得到一个表单模板,其中选择了一些数据,而另一些则没有(特别选择)。

如果我写form = ProductCreateForm(request.POST),那么我会收到一条错误消息,指出未找到请求。也许这是因为我在 get_context_data() 中设置了请求并__init__forms.py.

我在forms.py.

我有以下观点

class ProductsCreate(CreateView):
    model = Product
    form_class = ProductCreateForm
    http_method_names = ['get', 'post']

    def get_initial(self):
        initial = super(ProductsCreate, self).get_initial()
        initial['request'] = self.request

        return initial
​
    def get_context_data(self, *args, **kwargs):
        ctx=super(ProductsCreate, self).get_context_data(*args, **kwargs)
        ctx['special_form'] = SpeciallyPriceForm()

        return ctx
​
    def get(self, request, *args, **kwargs):
        self.object = None

        if kwargs.get('slug'):
            category = Category.objects.filter(slug=kwargs.get('slug')).first()
            self.initial.update({'category': category})

        return self.render_to_response(self.get_context_data())

    def post(self, request, *args, **kwargs):
        self.object = None
        form = ProductCreateForm(request.POST)     #What here?
        special_form = SpeciallyPriceForm(self.request.POST)
​
        if form.is_valid() and special_form.is_valid():
            return self.form_valid(form)
        else:
            return self.form_invalid(form)

形式

class ProductCreateForm(forms.ModelForm):
    #....
​
    def __init__(self, *args, **kwargs):
        self.request = kwargs.pop('initial').get('request')
        super(ProductCreateForm, self).__init__(*args, **kwargs)
        #...
        user = self.request.user
        provider = Provider.objects.filter(user=user.id).last()
        self.fields['category'] = ModelMultipleChoiceField(queryset=provider.category.all())
        #...

   def clean(self):
        cleaned_data = super(ProductCreateForm, self).clean()
        cd_category = cleaned_data.get('category')
        #...
​
​
class SpeciallyPriceForm(forms.ModelForm):
    class Meta:
        model = SpeciallyPrice
        fields = ['adittional_specially_price', 'adittional_specially_number']

标签: pythondjangopython-3.xdjango-modelsdjango-forms

解决方案


1.尝试以这种方式传递请求

def get_initial(self):
    """
    Returns the initial data to use for forms on this view.
    """
     initial = super(ProductsCreate, self).get_initial()

    initial['request'] = self.request

   return initial

然后在 forms.py

    def __init__(self):
         kwargs.pop('initial').get('request')
  1. 你确定这完全有效吗?在您的表单中初始化时,我没有看到 super() 调用,所以您应该得到一个错误?

  2. 您是否仅对正确获得的其余数据的类别字段有问题?

  3. Where do you pass it kwargs.pop('request') ??

  4. You can print and check what is in self.request.POST


推荐阅读