Формы Django не отображаются в модале начальной загрузки 4 - PullRequest
0 голосов
/ 22 октября 2018

недавно я пытался перенести приложение из списка задач с начальной загрузки 3 на 4 (точно 4.1.3), но все мои формы исчезли из моих модальных форм (форма для создания и другая для редактирования).Вот мой модал с формой, работающей с Bootstrap 3

enter image description here

, и вот мой модал без формы, отображаемой с Bootstrap 4.

enter image description here

Как мне снова отобразить формы в модалах?Вот мой пример кода для моей формы создания ...

Спасибо за помощь

РЕДАКТИРОВАТЬ: я запустил быстрый проект на Github , где вы можете увидетьпроблема, если вы хотите запустить его

views.py

from django.views import generic
from tasks.forms import CreateTaskForm
from .models import Task

class IndexView(generic.TemplateView):
    template_name = 'tasks/index.html'

    def get_context_data(self, **kwargs):
        context = super(IndexView, self).get_context_data()
        context['task_list'] = Task.objects.all()
        return context
...
...
class TaskCreateView(SuperuserRequiredMixin, generic.FormView):
    template_name = 'tasks/create_task_modal.html'
    form_class = CreateTaskForm
    model = Task

    def get_form_kwargs(self):
        kwargs = super(TaskCreateView, self).get_form_kwargs()
        kwargs['request'] = self.request
        return kwargs

    def form_valid(self, form):
        (status, msg) = form.execute()
        return HttpResponseRedirect(reverse('tasks:index'))

    def form_invalid(self, form):
        return HttpResponseRedirect(reverse('tasks:index'))

forms.py

from django import forms
from tasks.models import Task, Comment
from django.core.validators import MinValueValidator
from multiselectfield import MultiSelectFormField


class CreateTaskForm(forms.Form):
    def __init__(self, *args, **kwargs):
        self.request = kwargs.pop('request')
        super(CreateTaskForm, self).__init__(*args, **kwargs)

    LOCATION_CHOICES = (
        ...
    )

    CRITICITY_CHOICES = (
        ...
    )

    TYPE_CHOICES = (
        ...
    )

    STATUS_CHOICES = (
        ...
    )

    ENVIRONMENT_CHOICES = (
        ...
    )

    PERCENT_CHOICES = (
        ...
    )

    title = forms.CharField(label='Title', max_length=60, required=True)
    criticity = forms.ChoiceField(label='Criticity', choices=CRITICITY_CHOICES, required=True)
    type = forms.ChoiceField(label='Type', choices=TYPE_CHOICES, required=True)
    location = forms.ChoiceField(label='Location', choices=LOCATION_CHOICES, required=True)
    environment = MultiSelectFormField(label='Environment', required=True, choices=ENVIRONMENT_CHOICES)
    description = forms.CharField(label='Description', widget=forms.Textarea, required=True, max_length=5000)
    start_date = forms.DateTimeField(label='Start date', required=True)
    duration = forms.DecimalField(label='Duration (in hours)',
                              validators=[MinValueValidator(0)], required=True)
    status = forms.ChoiceField(label='Status', choices=STATUS_CHOICES, required=True)
    percent_of = forms.ChoiceField(label='Percent complete', choices=PERCENT_CHOICES, required=True)
    send_mail = forms.BooleanField(label='Send mail', required=False)

    def execute(self):
        title = self.cleaned_data['title']
        criticity = self.cleaned_data['criticity']
        type = self.cleaned_data['type']
        location = self.cleaned_data['location']
        environment = self.cleaned_data['environment']
        description = self.cleaned_data['description']
        start_date = self.cleaned_data['start_date']
        duration = self.cleaned_data['duration']
        status = self.cleaned_data['status']
        percent_of = self.cleaned_data['percent_of']
        send_mail = self.cleaned_data['send_mail']

        task = Task(
             title=title, criticity=criticity, type=type, location=location, environment=environment,
        description=description, start_date=start_date, duration=duration, status=status, percent_of=percent_of,
        send_mail=send_mail
    )

    task.save()

    return (True, "Creating task %s ..." % task.title)

urls.py

from django.urls import path, re_path
from . import views

app_name = 'tasks'
urlpatterns = [
    path('', views.IndexView.as_view(), name='index'),
    path('add/', views.TaskCreateView.as_view(), name='task_create'),
    ...
]

index.html

{% extends "tasks/base.html" %}
{% block content %}
<div class="row">
<div class="col-lg-12 col-md-12">
    <div class="card">
        <div class="card-header">
        {% if user.is_superuser %}
            <a class="btn btn-primary pull-right btn-sm" data-toggle="modal" data-target="#CreateTaskModal" href="{% url 'tasks:task_create' %}" >
                <span class="fa fa-pencil-square-o"></span> Add task
            </a>
        {% endif %}
        </div>
        <div class="card-body">
        {% if task_list %}
             <table class="table table-hover table-sm" id="Task-Table" cellspacing="0" width="100%" style="margin-top: -10px;">
             ...
             ... (for loop in order to display all task in the list)
             ...
             </table>
        {% endif %}
        </div>
    </div>
</div>
</div>
{% if user.is_superuser %}
    <div id="CreateTaskModal" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="CreateTaskModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg" role="document">
             <div class="modal-content">
                  {% include 'tasks/create_task_modal.html' %}
             </div>
        </div>
    </div>
{% endif %}
{% endblock %}

create_task_modal.html

{% load widget_tweaks %}
<form role="form" id="task-create-form" name="create-form" method="post" action="{% url 'tasks:task_create' %}">
<div class="modal-header">
    <h5 class="modal-title" id="CreateTaskModalLabel">Create new task</h5><div id="MultiSelectError" style="display: none;color: red">Environment field : you need to check at least one case</div>
    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
        <span aria-hidden="true">&times;</span>
    </button>
</div>
<div class="modal-body">
    {% csrf_token %}
    <div class="row">
        <div class="col-lg-6 col-md-6 col-sm-6 col-xs-6">
            <div class="form-group">
                <label class="control-label" for="{{ form.title.id_for_label }}">Title</label>
                {% render_field form.title class+="form-control" %}
            </div>
        </div>
        <div class="col-lg-6 col-md-6 col-sm-6 col-xs-6">
            <div class="form-group">
                <label class="control-label" for="{{ form.location.id_for_label }}">Location</label>
                {% render_field form.location class+="form-control" %}
            </div>
        </div>
    </div>
    <div class="row">
        <div class="col-lg-4 col-md-4 col-sm-4 col-xs-6">
            <div class="form-group">
                <label class="control-label" for="{{ form.type.id_for_label }}">Type</label>
                {% render_field form.type class+="form-control" %}
            </div>
        </div>
        <div class="col-lg-4 col-md-4 col-sm-4 col-xs-6">
            <div class="form-group">
                <label class="control-label" for="{{ form.criticity.id_for_label }}">Criticity</label>
                {% render_field form.criticity class+="form-control" %}
            </div>
        </div>
        <div class="col-lg-4 col-md-4 col-sm-4 col-xs-12">
            <div class="form-group">
            <label class="control-label" for="{{ form.environment.id_for_label }}">Environment</label>
            <div class="checkbox-group required">
                {% for value, text in form.environment.field.choices %}
                    <div class="ui slider checkbox" style="margin-left: 20px;">
                        <input class="cb_required_env" id="id_environment_{{ forloop.counter0 }}" name="{{ form.environment.name }}"
                               type="checkbox" value="{{ value }}">
                        <label for="id_environment_{{ forloop.counter0 }}">{{ text }}</label>
                    </div>
                {% endfor %}
            </div>
            </div>
        </div>
    </div>
    <div class="row">
        <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
            <div class="form-group">
                <label class="control-label" for="{{ form.description.id_for_label }}">Description</label>
                {% render_field form.description class+="form-control" rows=4 %}
            </div>
        </div>
    </div>
    <div class="row">
        <div class="col-lg-6 col-md-6 col-sm-6 col-xs-6">
            <div class="form-group">
                <label class="control-label" for="{{ form.start_date.id_for_label }}">Start date</label>
                <div id='datetimepicker'>
                    {% render_field form.start_date class+="form-control" %}
                </div>
            </div>
        </div>
        <div class="col-lg-6 col-md-6 col-sm-6 col-xs-6">
            <div class="form-group">
                <label class="control-label" for="{{ form.duration.id_for_label }}">Duration (in hours)</label>
                <div id="duration_field">
                    {% render_field form.duration class+="form-control" %}
                </div>
                <script type="text/javascript">
                    $("input[name='duration']").TouchSpin({
                        initval: 1,
                        min: 0.1,
                        max: 100,
                        step: 0.1,
                        decimals: 2,
                        boostat: 5,
                        maxboostedstep: 10,
                    });
                </script>
            </div>
        </div>
    </div>
    <div class="row">
        <div class="col-lg-6 col-md-6 col-sm-6 col-xs-6">
            <div class="form-group">
                <label class="control-label" for="{{ form.status.id_for_label }}">Status</label>
                {% render_field form.status class+="form-control" %}
            </div>
        </div>
        <div class="col-lg-6 col-md-6 col-sm-6 col-xs-6">
            <div class="form-group">
                <label class="control-label" for="{{ form.percent_of.id_for_label }}">Percent complete</label>
                {% render_field form.percent_of class+="form-control" %}
            </div>
        </div>
    </div>
    <div class="row">
        <div class="col-lg-12">
            <div class="form-group">
                    {% render_field form.send_mail %}
                    <label class="control-label" for="{{ form.send_mail.id_for_label }}">Check here if you want to send an email</label>
            </div>
        </div>
    </div>
</div>
<div class="modal-footer">
    <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
    <button type="submit" class="btn btn-primary" value="deploy" onclick="checkField()">Submit</button>
</div>

...