Как исправить ImportError в Django при попытке импортировать JSON? - PullRequest
0 голосов
/ 16 февраля 2019

У меня есть веб-страница, которая включает 2 цепочки выпадающих списков стран и городов, где на основании выбора первого второго раскрывающегося списка отображаются города, относящиеся к выбранной стране.

проблема в том, что отображается первый выпадающий списокизвлеченные данные из базы данных, но вторая все еще пуста.и система отображает следующую ошибку:

из django.utils импортирует json как simplejson ImportError: невозможно импортировать имя 'json' из моделей 'django.utils'

.py

from django.db import models
    class country(models.Model):
        name = models.CharField(max_length=100)

        def __str__(self):
            return str(self.name)

    class city(models.Model):
        name = models.CharField(max_length=100)
        MouhafazatID = models.ForeignKey(country,on_delete=models.CASCADE)


        def __str__(self):
            return str(self.name)

urls.py

from django.contrib import admin
from django.urls import path, include
from.views import *

urlpatterns = [
    path('admin/', admin.site.urls),
    # path('', home),
    path('', home2),
    path('getdetails/', getdetails),

views.py

from django.shortcuts import render
from django.http import HttpResponse
from testapp.models import *

from django.utils import json as simplejson # i think this is the error?



def home2(request):
    countries = country.objects.all()
    print(countries)
    return render(request, 'home2.html',{'countries': countries})



def getdetails(request):

    #country_name = request.POST['country_name']
    country_name = request.GET['cnt']
    print ("ajax country_name ", country_name)

    result_set = []
    all_cities = []

    answer = str(country_name[1:-1])
    selected_country = country.objects.get(name=answer)
    print ("selected country name ", selected_country)

    all_cities = selected_country.city_set.all()
    for city in all_cities:
        print ("city name", city.name)
        result_set.append({'name': city.name})

    return HttpResponse(simplejson.dumps(result_set), mimetype='application/json', content_type='application/json')

последняя строка делает ошибку, как это исправить?

home2.html

<html>
    <head>
    <script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
    <script type="text/javascript" src="http://yourjavascript.com/7174319415/script.js"></script>
        <script>
            $(document).ready(function(){
                 $('select#selectcountries').change(function () {
                     var optionSelected = $(this).find("option:selected");
                     var valueSelected  = optionSelected.val();
                     var country_name   = optionSelected.text();


                     data = {'cnt' : country_name };
                     ajax('/getdetails',data,function(result){

                            console.log(result);
                            $("#selectcities option").remove();
                            for (var i = result.length - 1; i >= 0; i--) {
                                $("#selectcities").append('<option>'+ result[i].name +'</option>');
                            };


                         });
                 });
            });
        </script>
    </head>

    <body>
        <select name="selectcountries" id="selectcountries">
        {% for item in countries %}
            <option val="{{ item.name }}"> {{ item.name }} </option>    
        {% endfor %}
        </select>   


        <select name ="selectcities" id="selectcities">


        </select>

    </body>
</html>

1 Ответ

0 голосов
/ 16 февраля 2019

Я смог решить эту проблему, изменив

from django.utils import json as simplejson

на

import json as simplejson
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...