Я получаю несформированную модальную форму для моей формы редактирования в Django - PullRequest
0 голосов
/ 10 октября 2019

Я новичок в Python и пытаюсь создать свой первый проект, чтобы добавлять / редактировать / удалять клиентов. Я успешно выполнил свой первый шаг, который состоит из списков и ящиков, но когда я прибыл в часть редактирования, я повесил там. Я не знаю, как это исправить.

Итак, кто-нибудь поможет мне решить эту проблему?


Моя форма:

customerform.py

from .Customers import Customer,City, Region
from TARGET.bootstrap_modal_forms.forms import BSModalForm

class CustomerForm(BSModalForm):
    class Meta:
        model = Customer 

Моя модель:

Customers.py
class Customer(models.Model):
    SMALL = 1
    MEDIUM = 2
    BIG = 3
    CUST_SIZE = (
        (SMALL, 'Small Business'),
        (MEDIUM, 'Medium Business'),
        (BIG, 'Larg Business'),
    )
    name = models.CharField(max_length=50)
    description = models.CharField(max_length=100, blank=True)
    account_id = models.CharField(max_length=30, blank=True)
    account_executive_id = models.CharField(max_length=30, blank=True)
    customer_size = models.PositiveSmallIntegerField(choices=CUST_SIZE)
    branches = models.IntegerField(blank=True, null=True)
    country = models.ForeignKey(Country, on_delete=models.SET_NULL, null=True)
    region = models.ForeignKey(Region, on_delete=models.SET_NULL, null=True)
    city = models.ForeignKey(City, on_delete=models.SET_NULL, null=True)
    address = models.CharField(max_length=100, blank=True)
    credit_limit = models.IntegerField(blank=True, null=True)
    payment_term = models.CharField(max_length=30, blank=True)
    libility = models.IntegerField(blank=True, null=True)

    timestamp = models.DateField(auto_now_add=True, auto_now=False)
    def get_absolute_url(self):
        return reverse("contacts", kwargs={"id": self.id})
    def __str__(self):
        return self.name

Мой URL:

url.py

from django.urls import path
from . import views
from django.conf.urls import url

from .views import (customers_view,dashboard_view,leads_view,opportunities_view,product_details_view,channel_details_view)

app_name = "crm"
urlpatterns = [
    path("contacts/", view=product_details_view, name="contacts"),
    path("contacts/create/", views.CustomerCreateView.as_view(), name="create_customer"),
    path("contacts/<int:id>/update/", views.CustomerEditView, name="edit_customer"),

    path("contacts/update/<int:pk>", views.CustomerUpdateView.as_view(), name="update_contact"),
    path("contacts/read/<int:pk>", views.CustomerReadView.as_view(), name="read_contact"),
    path("contacts/delete/<int:pk>", views.CustomerDeleteView.as_view(), name="delete_contact"),

    path("channels/", view=channel_details_view, name="channels"),
    path("channels/create/", views.ChannelCreateView.as_view(), name="create_channel"),
    path("channels/edit/", views.ChannelEditView.as_view(), name="edit_channel"),

    path('customers/', view=customers_view, name='customers'),
    path('dashboard', view=dashboard_view, name="dashboard"),
    path('leads', view=leads_view, name='leads'),
    path("opportunities", view=opportunities_view, name="opportunities"),
    path("ajax/load-cities/", views.load_cities, name="ajax_load_cities"),
    path("ajax/load-regions/", views.load_regions, name="ajax_load_regions"),

]

Мой просмотр

views.py

from django.contrib.auth import get_user_model
from django.contrib.auth.mixins import LoginRequiredMixin
from django.views.generic import TemplateView
from .customers.customerform import CustomerForm
from .customers.channelform import ChannelForm
from django.http import HttpResponse

from .customers.Customers import Customer, City, Region
from .customers.Channels import Channel
from django.shortcuts import render,get_object_or_404

from django.urls import reverse_lazy

from TARGET.bootstrap_modal_forms.generic import (BSModalCreateView,
                                                  BSModalUpdateView,
                                                  BSModalReadView,
                                                  BSModalDeleteView)
from django.template.loader import render_to_string
from django.http import JsonResponse

User = get_user_model()


def load_regions(request):
    country_id = request.GET.get('country')
    regions = Region.objects.filter(country_id=country_id).order_by('name')
    return render(request, 'crm/region_dropdown_list_options.html', {'regions': regions})


def load_cities(request):
    region_id = request.GET.get('region')
    cities = City.objects.filter(region_id=region_id).order_by('name')
    return render(request, 'crm/city_dropdown_list_options.html', {'cities': cities})


def save_all(request, form, template_name):
    data = dict()
    if request.method == 'POST':
        if form.is_valid():
            form.save()
            data['form_is_valid'] = True
            customers = Customer.objects.all()
            data['form'] = render_to_string('crm/crm-contacts.html', {'customers': customers})
        else:
            data['form_is_valid'] = False
    context = {
        'form': form
    }
    data['form'] = render_to_string(template_name, context, request=request)
    return JsonResponse(data)


class ChannelCreateView(BSModalCreateView):
    template_name = 'crm/channels/create_channel.html'
    form_class = ChannelForm
    success_message = 'Success: Channel was created.'
    success_url = reverse_lazy('crm:channels')


class CustomerCreateView(BSModalCreateView):
    template_name = 'crm/contacts/create_customer.html'
    form_class = CustomerForm
    success_message = 'Success: Customer was created.'
    success_url = reverse_lazy('crm:contacts')

def CustomerEditView(request,id):
    customer = get_object_or_404(Customer, id=id)
    if request.method == 'POST':
        form = CustomerForm(request.POST, instance=customer)
    else:
        form = CustomerForm(instance=customer)
    return save_all(request, form, 'crm/contacts/edit_customer.html')

class ChannelEditView(BSModalCreateView):
    template_name = 'crm/channels/edit_channel.html'
    form_class = ChannelForm
    success_message = 'Success: Channel was updated.'
    success_url = reverse_lazy('crm:channels')


class CustomerUpdateView(BSModalUpdateView):
    model = Customer
    template_name = 'crm/crm-contacts.html'
    form_class = CustomerForm
    success_message = 'Success: Book was updated.'
    success_url = reverse_lazy('crm:contacts')


class CustomerReadView(BSModalReadView):
    model = Customer
    template_name = 'crm/contacts/crm-contacts.html'

    def get_queryset(self):
        return Customer.objects.all()


class CustomerDeleteView(BSModalDeleteView):
    model = Customer
    template_name = 'crm/contacts/create_customer.html'
    success_message = 'Success: Book was deleted.'
    success_url = reverse_lazy('crm:contacts')


def channel_details_view(request):
    obj = Channel.objects.all()
    context = {
        'object': obj,
    }
    return render(request, "crm/channels/crm-channels.html", context)


def product_details_view(request):
    obj = Customer.objects.all()
    context = {
        'object': obj,
    }
    return render(request, "crm/contacts/crm-contacts.html", context)


class CustomerView(LoginRequiredMixin, TemplateView):
    def get_context_data(self, **kwargs):
        context = super(CustomerView, self, ).get_context_data(**kwargs)
        return context


customers_view = CustomerView.as_view(template_name="crm/crm-customers.html")


class DashBoardView(LoginRequiredMixin, TemplateView):
    def get_context_data(self, **kwargs):
        context = super(DashBoardView, self, ).get_context_data(**kwargs)
        return context


dashboard_view = DashBoardView.as_view(template_name="crm/crm-dashboard.html")


class LeadsView(LoginRequiredMixin, TemplateView):
    def get_context_data(self, **kwargs):
        context = super(LeadsView, self, ).get_context_data(**kwargs)
        return context


leads_view = LeadsView.as_view(template_name="crm/crm-Leads.html")


class OpportunitiesView(LoginRequiredMixin, TemplateView):
    def get_context_data(self, **kwargs):
        context = super(OpportunitiesView, self, ).get_context_data(**kwargs)
        return context


opportunities_view = OpportunitiesView.as_view(template_name="crm/crm-opportunities.html")

Мой клиентский просмотр Html:

Я получаю ошибку, вызванную передачейCustomer.id из этой функции:

      $(function () {
        // Create book buttonc
        $(".edit-customer").modalForm({formURL: "{% url 'crm:edit_customer' Customer.id %}" });

      }); 

Ошибка:

django.urls.exceptions.NoReverseMatch: Reverse for 'edit_customer' with arguments '('',)' not found. 1 pattern(s) tried: ['crm/contacts/(?P<id>[0-9]+)/update/$']
crm-contacts.html

{% extends "auth_base.html" %}
{% load static i18n %}

{% block content %}

                    <div class="container-fluid">

                        <!-- start page title -->
                        <div class="row">
                            <div class="col-12">
                                <div class="page-title-box">
                                    <div class="page-title-right">
                                        <ol class="breadcrumb m-0">
                                            <li class="breadcrumb-item"><a href="javascript: void(0);">TARGET</a></li>
                                            <li class="breadcrumb-item"><a href="javascript: void(0);">CRM</a></li>
                                            <li class="breadcrumb-item active">Contacts</li>
                                        </ol>
                                    </div>
                                    <h4 class="page-title">Contacts</h4>
                                </div>
                            </div>
                        </div>
                        <!-- end page title -->

                        <div class="row">
                            <div class="col-xl-12">
                                <div class="card">
                                    <div class="card-body">
                                        <div class="row mb-2">
                                            <div class="col-sm-4">
                                                <form class="form-inline">
                                                    <div class="form-group mb-2">
                                                        <label for="inputPassword2" class="sr-only">Search</label>
                                                        <input type="search" class="form-control" id="inputPassword2" placeholder="Search...">
                                                    </div>
                                                </form>
                                            </div>
                                            <div class="col-sm-8">
                                                <div class="text-sm-right">
                                                    <button type="button" class="btn btn-success waves-effect waves-light mb-2 mr-1"><i class="mdi mdi-settings"></i></button>
                                                    <div class="modal fade" tabindex="-1" role="dialog" id="modal">
                                                      <div class="modal-dialog modal-xl" role="document">
                                                        <div class="modal-content">
                                                        </div>
                                                      </div>
                                                    </div>

                                                    <!-- Create book button -->
                                                    <button class="create-customer btn btn-danger waves-effect waves-light mb-2" type="button" name="button" data-overlayColor="#38414a"><i class="mdi mdi-plus-circle mr-1"></i>  Add Customer</button>                                                    <!-- Create book button -->
                                                </div><!-- end col-->
                                            </div>
                                        </div>

                                        <div class="table-responsive">
                                            <table class="table table-centered table-hover mb-0">
                                                <thead>
                                                    <tr>
                                                        <th>Name</th>
                                                        <th>Description</th>
                                                        <th>Account</th>
                                                        <th>Account Executive</th>
                                                        <th>Country</th>
                                                        <th>City</th>
                                                        <th style="width: 82px;">Action</th>
                                                    </tr>
                                                </thead>
                                                <tbody>
                                                {% for Customer in object %}
                                                    <tr>
                                                            <td class="table-user">
                                                                <img src="/static/images/users/user-4.jpg" alt="table-user" class="mr-2 rounded-circle">
                                                                <a href="javascript:void(0);" class="edit-customer text-body font-weight-semibold" data-value="{% url 'crm:edit_customer' Customer.id %}">{{ Customer.name}}</a>
                                                            </td>
                                                            <td>
                                                                {{ Customer.description }}
                                                            </td>
                                                            <td>
                                                                {{ Customer.account_id }}
                                                            </td>
                                                            <td>
                                                                {{ Customer.account_executive_id }}
                                                            </td>
                                                            <td>
                                                                {{ Customer.country }}
                                                            </td>
                                                            <td>
                                                                {{ Customer.city }}
                                                            </td>

                                                            <td>
                                                                <a href="javascript:void(0);" class="edit-customer action-icon" data-value="{% url 'crm:edit_customer' Customer.id %}"> <i class="mdi mdi-square-edit-outline"></i></a>
                                                                <a href="javascript:void(0);" class="create-customer action-icon"> <i class="mdi mdi-delete"></i></a>
                                                            </td>

                                                    </tr>
                                                {% empty %}
                                                  <tr>
                                                    <td colspan="7" class="text-center bg-warning">No book</td>
                                                  </tr>
                                                {% endfor %}

                                                </tbody>
                                            </table>
                                        </div>

                                        <ul class="pagination pagination-rounded justify-content-end mb-0 mt-2">
                                            <li class="page-item">
                                                <a class="page-link" href="javascript: void(0);" aria-label="Previous">
                                                    <span aria-hidden="true">«</span>
                                                    <span class="sr-only">Previous</span>
                                                </a>
                                            </li>
                                            <li class="page-item active"><a class="page-link" href="javascript: void(0);">1</a></li>
                                            <li class="page-item"><a class="page-link" href="javascript: void(0);">2</a></li>
                                            <li class="page-item"><a class="page-link" href="javascript: void(0);">3</a></li>
                                            <li class="page-item"><a class="page-link" href="javascript: void(0);">4</a></li>
                                            <li class="page-item"><a class="page-link" href="javascript: void(0);">5</a></li>
                                            <li class="page-item">
                                                <a class="page-link" href="javascript: void(0);" aria-label="Next">
                                                    <span aria-hidden="true">»</span>
                                                    <span class="sr-only">Next</span>
                                                </a>
                                            </li>
                                        </ul>

                                    </div> <!-- end card-body-->
                                </div> <!-- end card-->
                            </div> <!-- end col -->

                        </div>
                        <!-- end row -->

                    </div> <!-- container -->

{% endblock %}


{% block extra_javascript %}
    <script src="{% static 'js/jquery.bootstrap.modal.forms.js' %}"></script>
    <!-- You can alternatively load the minified version -->
    <script src="{% static 'js/jquery.bootstrap.modal.forms.min.js' %}"></script>

    <script type="text/javascript">
      $(function () {
        // Create book button
        $(".create-customer").modalForm({formURL: "{% url 'crm:create_customer' %}"});
      });
      $(function () {
        // Create book buttonc
        $(".edit-customer").modalForm({formURL: "{% url 'crm:edit_customer' Customer.id %}" });

      });

    </script>

{% endblock %}

Мой клиент Редактировать Html:

Я сделал тест поПередав id как 1, изменив функцию в приведенном выше HTML-коде списка клиентов следующим образом:

      $(function () {
        // Create book buttonc
        $(".edit-customer").modalForm({formURL: "{% url 'crm:edit_customer' 1 %}" });

      });  

После того, как я это сделал, выскочила форма редактирования, но с не сформированными полями и макетом, подобным этому:

Неформатированная страница

edit_customer.html

{% load widget_tweaks %}
{% load crispy_forms_tags %}

<form method="post" data-url="{% url 'crm:edit_customer' form.instance.id %}" class="update-form">
    {% csrf_token %}
        <div class="modal-header">
        <h5 class="modal-title" >Update Customer</h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
        <span aria-hidden="true">&times;</span>
        </button>
        </div>
        <div class="modal-body">
            <table>
                <div class="{% if form.non_field_errors %}invalid{% endif %} mb-2">
                  {% if form.non_field_errors %}
                    {{ error }}
                    {% endif %}
                </div>

                <div class="form-row">
                      <div class="form-group col-md-6 mb-0">
                          {{ form.name }}
                                <div class="{% if form.name.errors %} invalid{% endif %}">
                                    {% if error in form.name.errors %}
                                        <p class="help-block">{{ error }}</p>
                                        {% endif %}
                                </div>
                        </div>
                      <div class="form-group col-md-3 mb-0">
                          {{ form.customer_size }}
                            <div class="{% if form.customer_size.errors %} invalid{% endif %}">
                                {% if error in form.customer_size.errors %}
                                    <p class="help-block">{{ error }}</p>
                                    {% endif %}
                            </div>
                      </div>
                      <div class="form-group col-md-3 mb-0">
                          {{ form.account_id }}
                      </div>
                </div>

                <div class="form-row">
                      <div class="form-group col-md-3 mb-0">
                          {{ form.account_executive_id }}
                      </div>
                      <div class="form-group col-md-2 mb-0">
                          {{ form.branches }}
                      </div>
                      <div class="form-group col-md-2 mb-0">
                          {{ form.credit_limit }}
                      </div>
                      <div class="form-group col-md-3 mb-0">
                          {{ form.payment_term }}</div>
                      <div class="form-group col-md-2 mb-0">
                          {{ form.libility }}
                      </div>
                </div>
                <div class="form-row">
                      <div class="form-group col-md-2 mb-0">
                           {{ form.country }}

                      </div>
                      <div class="form-group col-md-2 mb-0">
                           {{ form.region }}

                      </div>
                      <div class="form-group col-md-2 mb-0">

                           {{ form.city }}
                      </div>
                      <div class="form-group col-md-6 mb-0">
                          {{ form.address }}
                      </div>
                </div>

                <div class="form-row">
                      <div class="form-group col-md-12 mb-0">
                            <label for="description" class="control-label">Customer Info</label>
                            <textarea class="form-control" name="description" id="description" placeholder="Write something about your customer"></textarea>

                      </div>
                </div>
            </table>
        </div>
        <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
        <button type="submit" class="btn btn-primary">edit book</button>
        </div>
</form>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...