Mir Stephen
Mir Stephen

Reputation: 1927

How to access a part of URL address (not full URL) in Django template

How do I get '12' which is the id of teacher model in this path from Django template?

http://localhost:8000/editTeacher/12/

I searched a bit and I know how to get the entire url, but don't know how do I get a part of it.

I also tried using request.get('id') but it didn't work!

My urls.py:

urlpatterns = [
    path('admin/', admin.site.urls),
    path('addTeacher/', addTeacherView, name='add-teacher'),
    path('listTeacher/', listTeacherView, name='list-teacher'),
    path('teacherIndex/<int:my_id>/', teacherIndexView, name='teacher-index'),
    path('deleteTeacher/<int:my_id>/',
         deleteTeacherView, name='delete-teacher-view'),
    path('editTeacher/<int:my_id>/', editTeacherView, name='edit-teacher'),
    path('', homeView, name='home')
]

My views.py:

def editTeacherView(request, my_id):
    my_instance = Teacher.objects.get(id=my_id)
    teacher = TeacherForm(request.POST or None, instance=my_instance)
    if teacher.is_valid():
        teacher.save()
        return redirect('../../listTeacher/')
    context = {
        'editTeacher': teacher
    }
    return render(request, 'teacher/editTeacher.html/', context)

And this one below is the view I will be using in order to grab the id of the teacher from url and delete it from database

def deleteTeacherView(request, my_id):
    try:
        teacher = Teacher.objects.get(id=my_id)
        if request.method == 'POST':
            teacher.delete()
            return redirect('../../listTeacher/')
    except Teacher.DoesNotExist:
        raise Http404
    context = {
        'teacherId': teacher
    }
    return render(request, 'teacher/deleteTeacher.html', context)

this is editTeacher.html page:

<form method='POST'>
    {% csrf_token %}
    {{ editTeacher.as_p }}
    <input type="submit" value="Save">
    <a href="../../deleteTeacher/{{ #grab_id }}/">Delete</a>

</form>

Upvotes: 0

Views: 582

Answers (1)

Alasdair
Alasdair

Reputation: 308849

This kind of logic belongs in the view, not the template. You can pass the my_id to the template context in your view, for example:

def editTeacherView(request, my_id):
    context = {
        ...
        my_id: my_id,
    }
    return render(request, "edit_teacher.html", context}

Then in your template you can do {{ my_id }}

<a href="../../deleteTeacher/{{ my_id }}/">Delete</a>

Note that it's a bad idea to hardcode URLs like this. You can use the {% url %} tag instead:

<a href="{% url 'delete-teacher-view' my_id %}>

If you use a namespace (e.g. app_name = 'teachers'`), then you'll need to include this in the tag:

<a href="{% url 'teachers:delete-teacher-view' my_id %}>

Similarly, in your views you can use the URL name when you redirect instead of hardcoding the URL:

return redirect('list-teacher')

Upvotes: 2

Related Questions