python - 如何从表单中获取数据?
问题描述
如何从表单 ( 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']
解决方案
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')
你确定这完全有效吗?在您的表单中初始化时,我没有看到 super() 调用,所以您应该得到一个错误?
您是否仅对正确获得的其余数据的类别字段有问题?
Where do you pass it kwargs.pop('request') ??
You can print and check what is in self.request.POST
推荐阅读
- javascript - 如何在 React 的 Firebase 推送通知中添加自定义按钮?
- shaka - 更改 Shaka 播放器区域设置
- android - 如何使用 Navigation Drawer Activity Google 模板将图标添加到工具栏?
- typescript - 如何在 TypeScript 中导入和导出命名空间、接口和类型?从索引文件?
- python - 阅读域中的所有电子邮件
- python - 无法将数据从 HTML 表单保存到数据库 Django
- php - Symfony - 设置空字符串而不是null
- r - 如果最大值超过特定限制,则将列除以 1000
- c++ - 在 C++ 中,最大 std::streamsize 总是等于 std::string max_size()?
- javascript - 有没有办法在 Typescript 中获取未初始化变量的类型?