Home > Software engineering >  Django, how to create a path: <model_id>/<model_id>/template
Django, how to create a path: <model_id>/<model_id>/template

Time:10-23

The background to this question, is because I am trying to a find a way to build a 2 sided interface with 2 different user types.

  1. Users type 1 will be able to define certain actions to be performed by Users type 2
  2. Users type 2 will have access to the tasks provided by user type 1.However, all users type 2 will not have access to all the tasks. User Type 2 A might have different actions than User Type 2 B.

By setting up a path <model_id>/<model_id>/template, I thought it would be a good way to provide clarity in the url path and also filter access to data.

Taking the example of a Model called Project, when looking to link to a single pk_id, I normally do something like this:

#views.py
def show_project(request, project_id):
    projects = Project.objects.get(pk=project_id)
    return render(request, 'main/show_project.html',{'projects':projects}) 

#url.py
path('show_project/<project_id>',views.show_project,name="show-project"),

#template.py (referrer)
<a  href="{% url 'show-project' project.id %}">{{project}}</a>

Doing this allows me to obvioulsy filter what I want to show based on the ID of the model.

I thought I could do something similar by adding another layer <model_id>/<model_id>/template.

To stick to the example above: <user_id>/<project_id>/template.

So I came up with the following, which visibly does not work.

views

def function(request, user_id, project_id):
    user = User.objects.get(pk=user_id)
    project = Project.objects.get(pk=project_id)
    return render(request, 'main/test_url.html',{'project':projects, 'users':user}) 

url

path('<user_id>/<project_id>/test_url',views.test_url,name="test-url"),

template (referrer)

<a  href="{% url 'test-url' user.id project.id %}">See Test URL</a>

CodePudding user response:

1.The first mistake is passing projects to the 'project':projects dictionary. Should be project('project':project).

def function(request, user_id, project_id):
    user = User.objects.get(pk=user_id)
    project = Project.objects.get(pk=project_id)

    return render(request, 'main/cart_page.html',{'project':project, 'users':user})
  1. No trailing slash in path. Instead of a function, you pass a template to views, but you need a view function. It should be like this:

urls.py

urlpatterns = [
    path('<user_id>/<project_id>/test_url/', views.function, name="test-url"),
]
  1. In the template, instead of user.id, there should be users.id (the call goes by the keys of the dictionary that you passed and you have it users).

templates

<p>{{ project }}</p>
<p>{{ users }}</p>

<a href="{% url 'test-url' users.id project.id %}">Refresh the page</a>

address: http://localhost:8000/1/1/test_url/

  • Related