Поля ввода не отображаются - Django inlineformsets

Я использую встроенный набор форм, чтобы пользователь мог загружать несколько изображений, а также я мог получать связанную информацию вместе, например, ингредиент, количество и единицу измерения.

Раньше это работало, но мои поля ввода исчезли — заголовки все еще отображаются, но я не могу ввести текстовые поля, поэтому форма не будет правильно сохранена.

введите описание изображения здесь

Вот мой forms.py

Это мой models.py

Это соответствующий раздел моего шаблона:

class ImageForm(forms.ModelForm):

    class Meta:
        model = Image
        fields = '__all__'

class VariantIngredientForm(forms.ModelForm):

    class Meta:
        model = VariantIngredient
        fields = '__all__'
        widgets = {
            'ingredient': forms.TextInput(
                attrs={
                    'class': 'form-control'
                    }
                ),
            'quantity': forms.NumberInput(
                attrs={
                    'class': 'form-control'
                    }
                ),
            'unit': forms.MultipleChoiceField(
                choices = UNIT_CHOICES
                ),
        }
class Image(models.Model):
    recipe = models.ForeignKey(
        Recipe, on_delete=models.CASCADE, null=True
        )
    image = models.ImageField(blank=True, upload_to='images')

    def __str__(self):
        return self.recipe.title if self.recipe else "No Recipe"
    
class VariantIngredient(models.Model):
    recipe = models.ForeignKey(
        Recipe, on_delete=models.CASCADE
        )
    ingredient = models.CharField(max_length=100)
    quantity = models.PositiveIntegerField(default=1)
    unit = models.CharField(max_length=10, choices=unit_choice, default='g')

    def __str__(self):
        return self.recipe.title if self.recipe else "No Recipe"
    <!-- inline form for Images Start-->
        {% with named_formsets.images as formset %}
            {{ formset.management_form|crispy }}
            <script type="text/html" id="images-template">  // id="inlineformsetname-template"
                <tr id="images-__prefix__" class= hide_all> // id="inlineformsetname-__prefix__"
                    {% for fields in formset.empty_form.hidden_fields %}
                        {{ fields }}
                    {% endfor %}
    
                    {% for fields in formset.empty_form.visible_fields %}
                        <td>{{fields}}</td>
                    {% endfor %}
                </tr>
            </script>
    
            <div class="block w-full overflow-auto scrolling-touch relative flex flex-col min-w-0 rounded break-words border bg-white border-1 border-gray-300 mt-4">
                <div class="py-3 px-6 mb-0 bg-gray-200 border-b-1 border-gray-300 text-gray-900 card-header-secondary
                ">
                    <h4 class="text-gray-900 font-bold text-xl mb-2">Add Images</h4>
                </div>
                <table class="w-full max-w-full mb-4 bg-transparent flex-auto p-6">
                    <thead class="text-gray-600">
                        <th>Image <span style="color:red;" class="required">*</span></th>
                        <th>Delete?</th>
                    </thead>
                    <tbody id="item-images">
                        {% for formss in formset %}
                            {{ formss.management_form }}
                            <tr id="images-{{ forloop.counter0 }}" class= hide_all>
                                {{ formss.id }}
                                {% for field in formss.visible_fields %}
                                    <td>
                                        {{field}}
                                        {% for error in field.errors %}
                                            <span style="color: red">{{ error }}</span>
                                        {% endfor %}
                                    </td>
                                {% endfor %}
    
                                {% if formss.instance.pk %}
                                    <td>
                                        <button type="button" class="inline-block align-middle text-center select-none border font-normal whitespace-no-wrap rounded py-1 px-3 leading-normal no-underline bg-red-600 text-white hover:bg-red-700" data-toggle="modal"
                                        data-target="#exampleModal{{formss.instance.pk}}">
                                            Delete
                                        </button>
    
                                        <div class="modal hidden fixed top-0 left-0 w-full h-full outline-none fade" id="exampleModal{{formss.instance.pk}}" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel{{formss.instance.pk}}" aria-hidden="true">
                                            <div class="modal-dialog relative w-auto pointer-events-none max-w-lg my-8 mx-auto px-4 sm:px-0" role="document">
                                            <div class="relative flex flex-col w-full pointer-events-auto bg-white border border-gray-300 rounded-lg">
                                                <div class="flex items-start justify-between p-4 border-b border-gray-300 rounded-t">
                                                <h5 class="mb-0 text-lg leading-normal" id="exampleModalLabel{{formss.instance.pk}}">Are You Sure You Want To Delete This?</h5>
                                                <button type="button" class="absolute top-0 bottom-0 right-0 px-4 py-3" data-dismiss="modal" aria-label="Close">
                                                    <span aria-hidden="true">&times;</span>
                                                </button>
                                                </div>
                                                <div class="relative flex p-4">
                                                    <a href="{% url 'recipes:delete_image' formss.instance.pk %}" type="button" class="inline-block align-middle text-center select-none border font-normal whitespace-no-wrap rounded py-1 px-3 leading-normal no-underline bg-blue-600 text-white hover:bg-blue-600">Yes, Delete</a>
                                                    <button type="button" class="inline-block align-middle text-center select-none border font-normal whitespace-no-wrap rounded py-1 px-3 leading-normal no-underline bg-gray-600 text-white hover:bg-gray-700" data-dismiss="modal">Close</button>
                                                </div>
                                            </div>
                                            </div>
                                        </div>
                                    </td>
                                {% endif %}
                            </tr>
                        {% endfor %}
                    </tbody>
                </table>
                <a href="#" id="add-image-button" class="inline-block align-middle text-center select-none border font-normal whitespace-no-wrap rounded py-1 px-3 leading-normal no-underline bg-gray-600 text-white hover:bg-gray-700 add-images">Add More</a>
            </div>
        {% endwith %}
        <!-- inline form for Images end -->
        <!-- inline form for Variant start -->
        {% with named_formsets.variantingredients as formset %}
            {{ formset.management_form }}
            <script type="text/html" id="variantingredients-template">    // id="inlineformsetname-template"
                // id='inlineformsetname-__prefix__'
                <tr id="variantingredients-__prefix__" class= hide_all>
                    {% for fields in formset.empty_form.hidden_fields %}
                        {{ fields }}
                    {% endfor %}
    
                    {% for fields in formset.empty_form.visible_fields %}
                        <td>{{fields}}</td>
                    {% endfor %}
                </tr>
            </script>
            <div class="block w-full overflow-auto scrolling-touch relative flex flex-col min-w-0 rounded break-words border bg-white border-1 border-gray-300 mt-4">
                <div class="py-3 px-6 mb-0 bg-gray-200 border-b-1 border-gray-300 text-gray-900 card-header-secondary">
                    <h4 class="text-gray-900 font-bold text-xl mb-2">Add Ingredients</h4>
                </div>
                <table class="w-full max-w-full mb-4 bg-transparent py-3 px-6 mb-0 bg-gray-200 border-b-1 border-gray-300 text-gray-900">
                    <thead class="text-gray-600">
                        <th>Ingredient <span style="color: red;" class="required">*</span></th>
                        <th>Quantity <span style="color: red;" class="required">*</span></th>
                        <th>Unit <span style="color: red;" class="required">*</span></th>
                        <th>Delete?</th>
                    </thead>
                    <tbody id="item-variantingredients">
                        {% for formss in formset %}
                            {{ formss.management_form }}
                            <tr id="variantingredients-{{ forloop.counter0 }}" class= hide_all>
                                {{ formss.id }}
                                {% for field in formss.visible_fields %}
                                    <td>
                                        {{field}}
                                        {% for error in field.errors %}
                                            <span style="color: red">{{ error }}</span>
                                        {% endfor %}
                                    </td>
                                    {% endfor %}
                                    {% if formss.instance.pk %}
                                        <td>
                                            <button type="button" class="inline-block align-middle text-center select-none border font-normal whitespace-no-wrap rounded py-1 px-3 leading-normal no-underline bg-red-600 text-white hover:bg-red-700" data-toggle="modal" data-target="#exampleModal{{formss.instance.pk}}">
                                                Delete
                                            </button>
                                            <!-- Modal -->
                                            <div class="modal hidden fixed top-0 left-0 w-full h-full outline-none fade" id="exampleModal{{formss.instance.pk}}" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel{{formss.instance.pk}}" aria-hidden="true">
                                                <div class="modal-dialog relative w-auto pointer-events-none max-w-lg my-8 mx-auto px-4 sm:px-0" role="document">
                                                <div class="relative flex flex-col w-full pointer-events-auto bg-white border border-gray-300 rounded-lg">
                                                    <div class="flex items-start justify-between p-4 border-b border-gray-300 rounded-t">
                                                    <h5 class="mb-0 text-lg leading-normal" id="exampleModalLabel{{formss.instance.pk}}"Are you Sure You Want To Delete This?</h5>
                                                    <button type="button" class="absolute top-0 bottom-0 right-0 px-4 py-3" data-dismiss="modal" aria-type="Close">
                                                        <span aria-hidden="true">&times;</span>
                                                    </button>
                                                    </div>
                                                    <div class="relative flex p-4">
                                                        <a href="{% url 'recipes:delete_variantingredient' formss.instance.pk %}" type="button" class="inline-block align-middle text-center select-none border font-normal whitespace-no-wrap rounded py-1 px-3 leading-normal no-underline bg-blue-600 text-white hover:bg-blue-600">Yes, Delete</a>
                                                        <button type="button" class="inline-block align-middle text-center select-none border font-normal whitespace-no-wrap rounded py-1 px-3 leading-normal no-underline bg-gray-600 text-white hover:bg-gray-700" data-dismiss="modal">Close</button>
                                                    </div>
                                                </div>
                                                </div>
                                            </div>
                                        </td>
                                    {% endif %}
                                </tr>
                            {% endfor %}
                        </tbody>
                    </table>
                    <a href="#" id="add-variantingredient-button" class="inline-block align-middle text-center select-none border font-normal whitespace-no-wrap rounded py-1 px-3 leading-normal no-underline bg-gray-600 text-white hover:bg-gray-700 add-variantingredients">Add More</a>
                </div>
    
                {% endwith %}
                <!-- inline form for Images end -->
    
                <div class="mb-4">
                    <button type="submit" class="inline-block align-middle text-center select-none border font-normal whitespace-no-wrap rounded py-1 px-3 leading-normal no-underline bg-gray-600 text-white hover:bg-gray-700 block w-full">Submit</button>
                </div>
    </form>
    
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
    
        <script>
            $(document).ready(function() {
                // when user clicks add more btn of images
              $('.add-images').click(function(ev) {
                  ev.preventDefault();
                  var count = $('#item-images').children().length;
                  var tmplMarkup = $('#images-template').html();
                  var compiledTmpl = tmplMarkup.replace(/__prefix__/g, count);
                  $('#item-images').append(compiledTmpl);
    
                  // update form count
                  $('#uid_images-TOTAL_FORMS').attr('value', count+1);
              });    
          });
    
          $(document).

ready(function() {
        // when user clicks add more btn of variants 
          $('.add-variantingredients').click(function(ev) {
              ev.preventDefault();
              var count = $('#item-variantingredients').children().length;
              var tmplMarkup = $('#variantingredients-template').html();
              var compiledTmpl = tmplMarkup.replace(/__prefix__/g, count);
              $('#item-variantingredients').append(compiledTmpl);

              // update form count
              $('#id_variants-TOTAL_FORMS').attr('value', count+1);
          });
      });
    </script>

{% endblock content %}
Евфросиния
Вопрос задан15 февраля 2024 г.

1 Ответ

Ваш ответ

Загрузить файл.