0

I know such questions exist gallore in SO. But none satisfies my problem. My code however works in localhost in my PC but not in online server. The site is here. You can go to the English tab and click a news headline to see the ajax request. It is a simple ajax request from the template to the view.py file through a URL defined in the urls.py file. The url (i.e. show_recommendation) is defined in the following way :

from django.contrib import admin
#from django.urls import path
from django.conf.urls import url
from khobor import views

urlpatterns = [
    url(r'^$', views.home, name='home'),
    url(r'^admin/', admin.site.urls),
    url(r'^find_feed/', views.find_feed, name="find_feed"),
    url(r'^show_articles/', views.show_articles, name="show_articles"),
    url(r'^clear_cookie/', views.clear_cookie, name="clear_cookie"),
    url(r'^show_recommendation', views.show_recommendation, name="show_recommendation"),
    ]

JavaScript code in template is as follows:

       $.ajax({

                    url:"/show_recommendation/",
                    method:"POST",
                    dataType: 'JSON',
                   data:{
                      id_found:id_found,
                      csrfmiddlewaretoken: '{{ csrf_token }}'

                    },
                    success:function (data) {

                        //data=$.parseJSON(data);

                        alert(data);
                        if(window.console){

                            console.log(" response data =  ");
                            console.log(data);
                        }



                         if($.isArray(data)){


                        for(i=0; i<data.length; i++){

                            var id_found=data[i][0];

                            if(window.console){

                                console.log(" id found = "+id_found+" id found result = "+jQuery.inArray(id_found, ids_all));

                            }
                            if(jQuery.inArray(id_found, ids_all) ==-1){





                                ids_all.push(id_found);
                                new_ids.push(id_found);

                            if(window.console){

                                console.log(" id pushed = "+id_found);

                            }



                            //$("#recommendations").append('<li>'+data[i][0]+' ... '+data[i][1]+'</li>');
                            $("#recommendations").append('<li class="article_indiv  inline_block">' +
                                '<span class="top_image inline_block"  data-id="'+data[i][0]+'" ><img src="'+data[i][4]+'" alt="image"/>'+
                                '</span>' +
                                '<a class="link" data-id="'+data[i][0]+'" target="_blank"  href="'+data[i][2]+'" >'+data[i][3]+'</a>' +
                                 '</li>');

                             $(".top_image").imagefill();

                           /* $(".top_image").each(function(){

                                $elem = $(this);
                                var data_id =$elem.attr('data-id');
                                if(jQuery.inArray(data_id, new_ids) !=-1){

                                    $elem.imagefill();

                                }

                            });*/

                            }
                         } // end of for loop

                        Cookies.set('ids_all', ids_all);
                         }


                }


            });

In view.py I have :

def show_recommendation(request):

    # recommendations=['item1','item2']
    # json_list=json.dumps(recommendations)

    if request.method=="POST" and request.is_ajax():
        #print("u see this response ? ");
        #return HttpResponse("this is the response ")
        id_found = request.POST['id_found'];
        news_found=news.objects.get(id=id_found)
        content_found=news_found.content


        all_news = news.objects.exclude(id=id_found).order_by('-id').all()
        myList=[]


        for news_indiv in all_news:
            content=news_indiv.content
            id=news_indiv.id
            headline=news_indiv.headline
            url=news_indiv.url
            image=news_indiv.image
            result_similarity=cosine_sim(content,content_found)
            myList.append([id, result_similarity,url,headline,image])


        # myList = [3, 2, 5, 6, 1, 0, -5, 6, -7]
        # myList = [[12, .45633], [13, .245633], [14, .3323], [15, .8756]]

        result = quickSort(myList)
        total_rows = len(result)
        resultList=[]
        resultList.append(result[total_rows-1])
        resultList.append(result[total_rows-2])
        resultList.append(result[total_rows-3])
        #print("resultList === ")
        #print(resultList)

        json_list = json.dumps(resultList)

        #if(json_list is None):
        #   json_list="0";


        print ("before HttpResponse ")
        return HttpResponse(json_list)
        #return HttpResponse("dfdfdfdf")
        #return json_list

In my online server, I get the following error though it works pretty fine in my localhost on my PC :

Internal Server Error: /show_recommendation/

Traceback (most recent call last):

  File "/usr/lib64/python3.6/site-packages/django/core/handlers
/exception.py", line 35, in inner

    response = get_response(request)

  File "/usr/lib64/python3.6/site-packages/django/core/handlers/base.py", 

line 139, in _get_response

    "returned None instead." % (callback.__module__, view_name)

ValueError: The view khobor.views.show_recommendation didn't return an 

HttpResponse object. It returned None instead.

[03/Jun/2018 21:00:44] "POST /show_recommendation/ HTTP/1.1" 500 54424

How to remove the error now ?

Istiaque Ahmed
  • 6,072
  • 24
  • 75
  • 141
  • Not only when you post on `show_recommendation(request):` you got error, but when access the view with GET method, there's no Http Response. think when the `request.method != 'POST'`, what's the response – Lemayzeur Jun 03 '18 at 21:23
  • @Lemayzeur, wrong files were uploaded in online server. See now online. – Istiaque Ahmed Jun 03 '18 at 21:27
  • @Lemayzeur, I hit the url (http://amarkhobor.ml:8000/show_recommendation/) in web browser and got the error again. – Istiaque Ahmed Jun 03 '18 at 21:29
  • You don't have any condition for handling 'GET' requests. – Moses Koledoye Jun 03 '18 at 21:52
  • @MosesKoledoye, ajax is making a `POST` request there. Why should I handle a `GET` request there ? Just for suppressing errors in `GET` request, I can handle that. But still it does not solve the error in ajax POST request . – Istiaque Ahmed Jun 03 '18 at 22:15
  • Yes, I understand, but clicking the link you shared will not trigger a POST request for us. And hardly anyway to replicate an ajax with csrf and all. – Moses Koledoye Jun 03 '18 at 22:26
  • @MosesKoledoye, why won't it trigger any POST request ? The JS code defines the `method` as `POST`, right ? – Istiaque Ahmed Jun 03 '18 at 22:31
  • The ajax POST request runs **asynchronously** from your page. Not by clicking on the url. – Moses Koledoye Jun 03 '18 at 22:33
  • @MosesKoledoye, to my surprise, it works now. The server did not act on the newly edited files instantly, rather it took much time to recognize that a few files were updated- can it be any reason ? – Istiaque Ahmed Jun 03 '18 at 22:33
  • `.pyc` files probably https://stackoverflow.com/questions/5149832/where-are-the-pyc-files – Moses Koledoye Jun 03 '18 at 22:35
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/172360/discussion-between-istiaque-ahmed-and-moses-koledoye). – Istiaque Ahmed Jun 03 '18 at 22:41

1 Answers1

0

The issue is that the server is using .pyc files as pointed out in the comments.

Depending on how you are hosting the site, you will need to restart your Django Server process to trigger updates and recompilation of .pyc files.

For Gunicorn, this post discusses how to autoload on changes. gunicorn autoreload on source change

If you aren't using Gunicorn and post more about your server setup, I'll edit it this to match your use case.

Zev
  • 3,423
  • 1
  • 20
  • 41