Django:无法显示表单集和正确的表单

时间:2018-06-20 11:18:16

标签: html django

我正在申请网站。并且有两种模式:Applications和Guest,它们之间有许多连接,因为应用程序可以有2个或更多来宾,而在许多应用程序中可能有1个来宾。

为了制作应用程序,我将formset_factory与delete选项一起使用。问题是-我找不到用于manytomanyfield和formset的代码的良好示例,也无法在模板中绑定它们。我根本无法显示表格。这是代码。

p.s。不要注意西里尔符号

模型

class Guests(models.Model):
unique_number_guest = models.IntegerField(unique=True, primary_key=True, verbose_name='№')
organisation = models.CharField(max_length=100, verbose_name='Организация', null=True)
full_name = models.CharField(max_length=100, verbose_name='ФИО')
position = models.CharField(max_length=100, verbose_name='Должность', blank=True, null=True)
chosen = models.BooleanField(default=False, verbose_name='Выбран')
class Applications(models.Model):
ntc_cabins = (
    ('2-5', '2-5'),
    ('2-10', '2-10'),
    ('2-12', '2-12'),
)
ntc_blocks = (
    ('ЦОК', 'ЦОК'),
    ('БМЗ', 'БМЗ')
)

unique_number_app = models.IntegerField(unique=False, null=True)
visit_date = models.DateField(default=date.today()+timedelta(days=1), verbose_name='Дата:')
visit_time = models.TimeField(default='12:00', verbose_name='Время:')
cabin = models.CharField(max_length=5, verbose_name='Кабинет:', choices=ntc_cabins, default='2-12')
block = models.CharField(max_length=10, verbose_name='Корпус:', choices=ntc_blocks, default='ЦОК')
author = models.CharField(max_length=100, verbose_name='Автор:')
guests = models.ManyToManyField(Guests)

观看次数

def ApplicationFormation(request):
form = ApplicationsForm(request.POST)
form.guest_instanses = GuestsFormSet(request.POST)
if request.method == "POST":
    if form.is_valid():
        applications = Applications()
        applications.cabin = form.cleaned_data['cabin']
        applications.save()
        for person in form.guests_visited:
            guest = Guests()
            guest.full_name = person['full_name']
            guest.organisation = person['organisation']
            guest.position = person['position']
            guest.save()
            applications.guests.add(guest)
        return HttpResponse('good job')
    print(form.errors)
else:
    formset = GuestsFormSet()
print('FORMSET:', formset)
return render(request, 'myprofile/applications_form.html', {'form': form, 'fomset': formset})

表格

class GuestsForm(ModelForm):
organisation = forms.CharField()
full_name = forms.CharField()
position = forms.CharField()
class Meta:
    model = Guests
    exclude = ('unique_number_guest', 'chosen',)
GuestsFormSet = formset_factory(GuestsForm, extra=1, can_delete=True)

class ApplicationsForm(ModelForm):
visit_date = forms.DateField()
visit_time = forms.TimeField()
cabin = forms.CharField()
block = forms.CharField()
guests = GuestsFormSet()


class Meta:
    model = Applications
    exclude = ('unique_number_app', 'author', 'guests', 'ntc_cabin')

和模板

{% extends "base.html" %}
{% load static %}
{% block title %}{% endblock %}
{% block content %}



<h2>Заявка на пропуск</h2>
<hr>
<div class="col-md-4">
    <form action="" method="post" class="">
        {% csrf_token %}
        {{ form.as_p }}


        <h3>Гости</h3>
        <table id="table-guests">
            {{ formset.management_form }}
            {% for form in formset %}
                {% if forloop.first %}
                    <thead>
                    <tr>
                        {% for field in form.visible_fields %}
                            <th>{{ field.label|capfirst }}</th>
                        {% endfor %}
                    </tr>
                    </thead>
                {% endif %}
                <tr class="{% cycle row1 row2 %} formset_row">
                    {% 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 }}
                        </td>
                    {% endfor %}
                </tr>
            {% endfor %}
        </table>
        <input type="submit" value="Сохранить и сформировать заявку"/> <a href="{% url 'applications-list' %}">Назад</a>
    </form>
</div>

<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="{% static 'formset/jquery.formset.js' %}"></script>
<script type="text/javascript">
    $('.formset_row').formset({
        addText: 'добавить',
        deleteText: 'удалить',
        prefix: 'Guests'
    });
</script>

0 个答案:

没有答案