Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
259 views
in Technique[技术] by (71.8m points)

Django: TypeError: 'Model' object is not iterable while implementing Ajax and Json

I am trying to implement CRUD using Ajax and Json following this tutorial.

My URL:

from django.urls import path
from . import views

urlpatterns = [
path('dossier_create/', views.dossier_create, name="dossier_create"),
]

My Views:

def dossier_create(request):
    if request.method == 'POST':
        dossier_form = DossierForm(request.POST)
        activity_form = ActivityForm(request.POST)
    else:
        dossier_form = DossierForm()
        activity_form = ActivityForm()
    return save_dossier_form(request, dossier_form, activity_form, 'sbprofile/dossier/partial_dossier_create.html')

def save_dossier_form(request, dossier_form, activity_form, template_name):
    data = dict()
    if request.method == 'POST':
        if dossier_form.is_valid() and activity_form.is_valid():
            dossier_form = dossier_form.save(commit=False)
            dossier_form.added_by = request.user
            dossier_form.added_date = timezone.now()
            dossier_form.save()
            dossier = get_object_or_404(Dossier, id=dossier_form.id)

            activity_form = activity_form.save(commit=False)
            activity_form.dossier = dossier
            activity_form.added_by = request.user
            activity_form.added_date = timezone.now()
            activity_form.save()
            data['form_is_valid'] = True
            dossiers = Dossier.objects.all()
            data['html_dossier_list'] = render_to_string('sbprofile/dossier/partial_dossier_list.html', {
                'dossiers': dossiers
            })
        else:
            data['form_is_valid'] = False
    context = {'dossier_form': dossier_form, 'activity_form': activity_form}
    data['html_form'] = render_to_string(template_name, context, request=request)
    return JsonResponse(data)

My Templates: partial_dossier_create.html

{% load widget_tweaks %}

<form method="post" action="{% url 'dossier_create' %}" class="js-dossier-create-form">
    {% csrf_token %}
    <div class="modal-header">
        <h4 class="modal-title">Create a Dossier</h4>
    </div>
    <div class="modal-body">
        {% include 'sbprofile/dossier/partial_dossier_form.html' %}
    </div>
    <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        <button type="submit" class="btn btn-primary">Create Dossier</button>
    </div>
</form>

partial_dossier_form.html

{% load widget_tweaks %}

{% for field in dossier_form %}
<div class="form-group{% if field.errors %} has-error{% endif %}">
    <label for="{{ field.id_for_label }}">{{ field.label }}</label>
    {% render_field field class="form-control" %}
    {% for error in field.errors %}
    <p class="help-block">{{ error }}</p>
    {% endfor %}
</div>
{% endfor %}
{% for field in activity_form %}
<div class="form-group{% if field.errors %} has-error{% endif %}">
    <label for="{{ field.id_for_label }}">{{ field.label }}</label>
    {% render_field field class="form-control" %}
    {% for error in field.errors %}
    <p class="help-block">{{ error }}</p>
    {% endfor %}
</div>
{% endfor %}

partial_dossier_list.html

{% for dossier in dossiers %}
<tr>
    <td>
        <a href="" type="button" class="update-book btn btn-sm btn-info">
            {{ dossier.id }}
        </a>
    </td>
    <td>{{ dossier.name }}</td>
    {% for group in user.groups.all %}
    {% if group.name == 'admin' %}
    <td class="text-center">
        <a href="{% url 'dossier_update' dossier.id %}" type="button" class="update-dossier btn btn-sm btn-primary">
            <i class="far fa-edit"></i>
        </a>
    </td>
    <td class="text-center">
        <a href="" type="button" class="delete-dossier btn btn-sm btn-danger">
            <i class="fas fa-trash"></i>
        </a>
    </td>
    {% endif %}
    {% endfor %}
</tr>
{% endfor %}

My JS:

// Create dossier
$(".js-dossier-create").click(loadForm);
$("#modal-dossier").on("submit", ".js-dossier-create-form", saveForm);

var loadForm = function () {
    var btn = $(this);
    $.ajax({
        url: btn.attr("data-url"),
        type: 'get',
        dataType: 'json',
        beforeSend: function () {
            $("#modal-dossier").modal("show");
        },
        success: function (data) {
            $("#modal-dossier .modal-content").html(data.html_form);
        }
    });
};

var saveForm = function () {
    var form = $(this);
    $.ajax({
        url: form.attr("action"),
        data: form.serialize(),
        type: form.attr("method"),
        dataType: 'json',
        success: function (data) {
            if (data.form_is_valid) {
                $("#dossier-table").html(data.html_dossier_list);
                $("#modal-dossier").modal("hide");
            }
            else {
                $("#modal-dossier .modal-content").html(data.html_form);
            }
        }
    });
    return false;
};

The code above saves the data in the database. But neither does update the table not hide the modal. Instead gives the below error.

[23/Jan/2021 09:56:23] "POST /dossier_create/ HTTP/1.1" 500 144884
Internal Server Error: /dossier_create/
Traceback (most recent call last):
  File "/mnt/d/djangoprojects/bdsbprofile/venv/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner
    response = get_response(request)
  File "/mnt/d/djangoprojects/bdsbprofile/venv/lib/python3.8/site-packages/django/core/handlers/base.py", line 181, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/mnt/d/djangoprojects/bdsbprofile/venv/lib/python3.8/site-packages/django/contrib/auth/decorators.py", line 21, in _wrapped_view
    return view_func(request, *args, **kwargs)
  File "/mnt/d/djangoprojects/bdsbprofile/bdsbprofile/sbprofile/decorators.py", line 22, in wrapper_func
    return view_func(request, *args, **kwargs)
  File "/mnt/d/djangoprojects/bdsbprofile/bdsbprofile/sbprofile/views.py", line 68, in dossier_create
    return save_dossier_form(request, dossier_form, activity_form, 'sbprofile/dossier/partial_dossier_create.html')
  File "/mnt/d/djangoprojects/bdsbprofile/bdsbprofile/sbprofile/views.py", line 94, in save_dossier_form
    data['html_form'] = render_to_string(template_name, context, request=request)
  File "/mnt/d/djangoprojects/bdsbprofile/venv/lib/python3.8/site-packages/django/template/loader.py", line 62, in render_to_string
    return template.render(context, request)
  File "/mnt/d/djangoprojects/bdsbprofile/venv/lib/python3.8/site-packages/django/template/backends/django.py", line 61, in render
    return self.template.render(context)
  File "/mnt/d/djangoprojects/bdsbprofile/venv/lib/python3.8/site-packages/django/template/base.py", line 170, in render
    return self._render(context)
  File "/mnt/d/djangoprojects/bdsbprofile/venv/lib/python3.8/site-packages/django/template/base.py", line 162, in _render
    return self.nodelist.render(context)
  File "/mnt/d/djangoprojects/bdsbprofile/venv/lib/python3.8/site-packages/django/template/base.py", line 938, in render
    bit = node.render_annotated(context)
  File "/mnt/d/djangoprojects/bdsbprofile/venv/lib/python3.8/site-packages/django/template/base.py", line 905, in render_annotated
    return self.render(context)
  File "/mnt/d/djangoprojects/bdsbprofile/venv/lib/python3.8/site-packages/django/template/loader_tags.py", line 192, in render
    return template.render(context)
  File "/mnt/d/djangoprojects/bdsbprofile/venv/lib/python3.8/site-packages/django/template/base.py", line 172, in render
    return self._render(context)
  File "/mnt/d/djangoprojects/bdsbprofile/venv/lib/python3.8/site-packages/django/template/base.py", line 162, in _render
    return self.nodelist.render(context)
  File "/mnt/d/djangoprojects/bdsbprofile/venv/lib/python3.8/site-packages/django/template/base.py", line 938, in render
    bit = node.render_annotated(context)
  File "/mnt/d/djangoprojects/bdsbprofile/venv/lib/python3.8/site-packages/django/template/base.py", line 905, in render_annotated
    return self.render(context)
  File "/mnt/d/djangoprojects/bdsbprofile/venv/lib/python3.8/site-packages/django/template/defaulttags.py", line 167, in render
    values = list(values)
TypeError: 'Dossier' object is not iterable

This line gives the error:

data['html_form'] = render_to_string(template_name, context, request=request)

But says:

TypeError: 'Dossier' object is not iterable

How can I solve this? Any help would be much appreciated.

question from:https://stackoverflow.com/questions/65858089/django-typeerror-model-object-is-not-iterable-while-implementing-ajax-and-js

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...