Nessi
Nessi

Reputation: 286

How to call the correct view method in Django?

I have a project with these files and folders:

...
old
project
new
common
manage.py
...

I access the "old" using http://127.0.0.1:8000/old and there are views, form urls, etc files inside this folder. all works fine.

I have similar files inside "new" folder as well. It also runs well: http://127.0.0.1:8000/old

However I run into problems when I have a method inside view ("method1") and I declare it inside urls. However it searches for the method1 inside folder "old" not in "new".

$.post('{% url "method1" %}

inside urls I have

path('method/', views.method1, name='method1'),

I have no idea why this js searches for method1 inside "old". When I declare method1 inside old folder, it works fine.

What am I missing here?

Update

It works without js, this method is fine, but inside js code it fails I put the js code here:

{% block domready %}
  $('a.cost').click(function(e){
    e.preventDefault();
    $.post('{% url "method1" %}',
      {
        action: $(this).data('action')
      },
      function(data){
        //...
      }
    );
  });
{% endblock %}

Upvotes: 0

Views: 64

Answers (1)

Andrzej Długosz
Andrzej Długosz

Reputation: 336

I think you have problem in your other 'urls.py' it is probably located in the 'project' directory.

You need to have both your apps in the main urlpatterns of your project:

urlpatterns = [
    path('old/', include('old.urls')),
    path('new/', include('new.urls'))
]

If you are trying to use different folders to store different things then sorry, but default django router works with applications, so you have one directory per application. So for 'old' application you do everything inside 'old' folder and if you want to make another application - you need to make one.

If you add a namespace to your urls for the app new, then you need to prefix all the names when you reverse the url:

{% url "new:method1" %}

Upvotes: 1

Related Questions