Why isn't my dynamic formset displaying any fields

北城以北 提交于 2019-12-13 03:38:46

问题


My goal is to define an upload form for cars for users to upload a car with all relevant details, and adding images from the same page.

The Admin form works perfectly, and I just want to emulate it in custom page-- a surprisingly difficult task! I'm using this tutorial, with the fields changed to match my project.

I'm also using the django-dynamic-formset jQuery plugin to provide additional image fields as needed by the user.

I've been stuck on this for a week, and I'm not sure exactly where the issue lays, so I'm going to share lots of code.

class ImagesInline(admin.TabularInline):
    model = Image

@admin.register(Car)
class CarAdmin(admin.ModelAdmin):
    list_display = ('manufacturer', 'car_model', 'model_year', 'mileage', 'status', 'date_added', 'price', 'seller')
    list_filter = ('manufacturer', 'status', 'transmission')
    fieldsets = (
        ('General information', {
            'fields': ('manufacturer', 'car_model',
            'model_year', 'price', 'vin', 'mileage', 'transmission', 'engine_displacement', 
            'forced_induction', 'drivetrain', 'description',)
        }),
       ('Availability', {
            'fields': ('status', 'seller')
        }),
    )
    inlines = [ImagesInline]

This is the CarCreate view

class CarCreate(generic.CreateView):

    model = Car
    # fields = '__all__'
    success_url = reverse_lazy('car-detail.html')

    slug_field = 'id'
    slug_url_kwarg = 'car_create'

    template_name = 'showroom/car_create.html'
    form_class = CarImageForm
    success_url = None

    def get_context_data(self, **kwargs):
        data = super(CarCreate, self).get_context_data(**kwargs)
        if self.request.POST:
            data['images'] = CarImageFormSet(self.request.POST)
        else:
            data['images'] = CarImageFormSet()
        return data

    def form_valid(self, form):
        context = self.get_context_data()
        images = context['images']
        with transaction.atomic():
            form.instance.created_by = self.request.user
            self.object = form.save()
            if images.is_valid():
                titles.instance = self.object
                titles.save()
        return super(CarCreate, self).form_valid(form)

    def get_success_url(self):
        return reverse_lazy('showroom:car_detail', kwargs={'id': self.object.id})

Template car_create.html

{% extends "base.html" %}

{% load crispy_forms_tags %}
{% block content %}
<div class="container">
    <div class="card">
        <div class="card-header"></div>
            <h2>Upload a car</h2>
        </div>
    <div class="card-body">
        {% crispy form %}
    </div>
</div>
{% endblock content %}

custom_layout_object.py

from crispy_forms.layout import LayoutObject, TEMPLATE_PACK
from django.shortcuts import render
from django.template.loader import render_to_string 

class Formset(LayoutObject):
    template = "showroom/formset.html"

    def __init__(self, formset_name_in_context, template=None):
        self.formset_name_in_context = formset_name_in_context
        self.fields = []
        if template:
            self.template = template

    def render(self, form, form_style, context, template_pack=TEMPLATE_PACK):
        formset = context[self.formset_name_in_context]
        return render_to_string(self.teplate, {'formset': formset})

formset.html

{% load crispy_forms_tags %}

{% extends base.html %}

{{ formset.management_form|crispy }}

    {% for form in formset.forms %}
        <tr class="{% cycle 'row1' 'row2' %} formset_row-{{ formset.prefix}}">
            {% for field in form.visible_fields %}
                <td>
                    {# Include the hidden fields in the form #}
                    {% if forloop.first %}
                        {% for hidden in form.hidden_fields %}
                            {{ hidden }}
                        {% endfor %}
                    {% endif %}
                    {{ field.errors.as_ul }}
                    {{ field|as_crispy_field}}
                </td>
            {% endfor %}
        </tr>
    {% endfor %}

{% block javascript %}
    <script src="{% static '/js/django-dynamic-formset/jquery.formset.js' %}"></script>
    <script type="text/javascript">
        $('.formset_row-{{ formset.prefix }}').formset({
            addtext: 'add another',
            deleteText: 'remove',
            prefix: '{{ formset.prefix }}',
        });
    </script>
{% endblock %}

Despite all this, the creation form looks like this:

When it should look like this

There aren't any errors in the console terminal.

来源:https://stackoverflow.com/questions/58408771/why-isnt-my-dynamic-formset-displaying-any-fields

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!