javascript - 为什么我得到空表格?如何自动创建 Iniline 模型?

标签 javascript python jquery django

一页上有2个表单

有 2 个模型:1. Product。 2. SpeciallyPriceSpeciallyPrice 通过 FK 链接到 Product。同时,SpeciallyPriceProduct中的Inline模型。

SpecialPriceForm 的字段是使用 JS 自动创建的。也就是说,它们可能是第 n 个数。有必要为每个创建的字段创建一条记录。原则上,我猜想怎么做——使用循环来驱动获得的值。但问题是由于某种原因 None 来自 form。请帮助我。

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, request.FILES, initial={'request': request})
        special_form = SpeciallyPriceForm(request.POST)
        print(special_form)           #Template of form, without values.
        if form.is_valid() and special_form.is_valid():
            return self.form_valid(form, special_form)
        else:
            return self.form_invalid(form, special_form)

    def form_valid(self, form, special_form):
        product = form.save(commit=False)
        product.user = self.request.user
        product.save()

        special = special_form.save(commit=False)
        #Here I think, depending on the number of list items, to cycle through it and create the corresponding number of `special` records associated with this` product`. Is the logic correct?
        special.product = product
        special.save()

        for spec_price in special_form.cleaned_data.get('adittional_specially_price'):
            print(spec_price)
            special.adittional_specially_price = spec_price
        for spec_numb in special_form.cleaned_data.get('adittional_specially_number'):
            print(spec_numb)
            special.adittional_specially_number = spec_numb

表单

class SpeciallyPriceForm(forms.ModelForm): 
    class Meta: 
        model = SpeciallyPrice 
        fields = ['adittional_specially_price', 'adittional_specially_number']

    def clean(self):
        cleaned_data = super(SpeciallyPriceForm, self).clean()
        cd_adittional_specially_price = cleaned_data.get('adittional_specially_price')
        print(cd_adittional_specially_price)   #None
        cd_adittional_specially_number = cleaned_data.get('adittional_specially_number')
        print(cd_adittional_specially_number)  #None

模板+js

<html><body>
Special price from {{ special_form.adittional_specially_price }} kg {{ special_form.adittional_specially_number }} usd

    <script>
        (function(){
            var copy = document.querySelector('.field.inline.specially').cloneNode(true);
            document.querySelector('html').addEventListener('input', function(e){
                if(e.target.classList.contains('event') && e.target.tagName == 'INPUT'){
                    var error = 0;
                    for(var evt of document.querySelectorAll('.field.inline.specially input.event')){
                        evt.value = evt.value.replace(/[^\d]/,'');
                        if(!evt.value || +evt.value < 1) error++;
                    }
                    if(!error){
                        var last = document.querySelectorAll('.field.inline.specially');
                        last[last.length-1].insertAdjacentHTML('afterEnd', copy.outerHTML);
                    }
                }
            });
        })();
    </script>
</body></html>

当打印 form 进行检查时,我在 View 中看到了这种形式

<label for="specially" class="subhead">Special price from</label>
<span class="id_specially_price"><input type="text" name="adittional_specially_price" style="width: 165px" class="event" id="id_adittional_specially_price"></span>
<span>kg</span>
<span class="id_specially_number"><input type="text" name="adittional_specially_number" style="width: 100px" class="event" id="id_adittional_specially_number"></span>
<span>usd</span>

我查看了 View - 表单在那里呈现,但只有一个字段,而不是所有内容。而且表单是空的 ..如何解决这个问题?也许 Ajax 应该被连接并且它以某种方式处理请求?还是有更多的 Django 选项?

最佳答案

回答这个评论:“真的来了用 JS 字段创建的最后两个空。如何让所有字段都来,请告诉我?”

在 CBV 中保存内联表单集:

def form_valid(self, form):
    context = self.get_context_data()
    inline_form = context['inline_form']
    if inline_form.is_valid():
        self.object = form.save()
        inline_form.instance = self.object
        inline_form.save()

显然,您必须在 context 中为 inline_form 使用正确的名称。

关于javascript - 为什么我得到空表格?如何自动创建 Iniline 模型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55480204/

相关文章:

javascript - 谷歌授权弹出窗口卡在 chrome 扩展中

javascript - 无法在 Node v6.4.0 中启用尾调用优化

python - “mongorestore”不被识别为内部或外部命令、可操作程序或批处理文件

javascript - jQuery 缓存 XML

jquery - 输入失去焦点后添加 img 和 setTimeout

javascript - 了解 HTML 5 事件拖动

javascript - 在 ko.observableArray 模型绑定(bind)问题中向下移动项目

Javascript 在特定类出现后在 div 中包装多个 p 标签

python - Pandas 中系列的 bool 数据帧及其自身

python - Apache spark 是如何处理 python 多线程问题的?