【问题标题】:Why I get empty form? How to automatically create Iniline models?为什么我得到空表格?如何自动创建 Iniline 模型?
【发布时间】:2019-04-02 17:10:32
【问题描述】:

一页上有2 forms。

有 2 个模型:1.Product。 2.SpeciallyPrice。 SpeciallyPrice 通过 FK 链接到 Product。同时SpeciallyPrice是Product中的内联模型。

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 进行检查时,我会在视图中看到此表单

<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>

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

【问题讨论】:

  • 我想你想在 Django 提供的 JS 中使用 inlineformset_factory。试试这个教程 (medium.com/@adandan01/…),这是一个很好的起点。
  • @HenryM 谢谢。这似乎很容易。只是不太了解它“使用 Django 提供的 JS”。也许,为此我需要创建一个新问题,如果我不明白?或者我能以某种方式与您联系?
  • @HenryM 这不起作用(
  • @HenryM 这可能是由于使用JS添加的新字段具有相同的ID。当我在视图中查看表单时,它会显示发送请求时留空的最后两个字段?
  • @HenryM 是的,就是这样。我用ID解决了这个问题。真的来了最后两个用 JS 字段创建的空字段。如何让所有领域都来,请告诉我?

标签: javascript python jquery django


【解决方案1】:

回答这一点cmets:“真的来了最后两个用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 使用正确的名称。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-15
    • 2012-03-12
    • 2014-01-22
    • 1970-01-01
    相关资源
    最近更新 更多