From below Coded project i want to add two numbers and want to print their resultant value. All things goes smoothly but when i try to print the resultant value it make me causes a "MultiValueDictKeyError" errors. I have searched and tried so many ways but failed to resolve the problem.
The project tree look like this
project files tress
views.py
from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt
def home(request):
return render(request, 'base.html')
#csrf_exempt
def add(request):
val1 = int(request.POST['num1'])
val2 = int(request.POST['num2'])
res = val1 + val2
return render(request, "main/index.html", {'add_result': res})
Index.html
{% extends 'base.html' %}
{% block content %}
<h3>This two number adding form</h3>
<form action="{% url 'add' %}" method="POST">
Enter the first here: <input type="text" name="num1" placeholder="First Number"><br>
Enter the second here: <input type="text" name="num2" placeholder="Second Number"><br>
<input type="submit">
</form>
<hr>
<div>
Result : <p>{{ add_result }} </p>
</div>
{% endblock %}
base.html
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0,
minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>ADDTWONUMBER</title>
</head>
<body>
<H4>THIS IS FORM OF ADDING TWO NUMBER</H4>
<li>click here to add two number</li>
<div>
{% block content %} {% endblock %}
</div>
</body>
</html>
urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.home, name = 'home'),
path('main/add' , views.add, name = 'add'),
]
Errors
> MultiValueDictKeyError at /main/add
> 'num1'
> Request Method: GET
> Request URL: http://127.0.0.1:8000/main/add
> Django Version: 3.0.4
> Exception Type: MultiValueDictKeyError
> Exception Value: 'num1'
> Exception Location: /home/hudacse6/Env/lib/python3.7/site-
packages/django/utils/datastructures.py in __getitem__, line 78
> Python Executable: /home/hudacse6/Env/bin/python
> Python Version: 3.7.4
> Python Path:
['/home/hudacse6/pr1_todoapps',
'/usr/lib/python37.zip',
'/usr/lib/python3.7',
'/usr/lib/python3.7/lib-dynload',
'/home/hudacse6/Env/lib/python3.7/site-packages']
> Server time: Wed, 18 Mar 2020 17:09:20 +0000
Error in picture
How to do dealt with this error?
Have you tried with get() method on request.POST ?
val1 = int(request.POST.get('num1', None))
val2 = int(request.POST.get('num2', None))
Related
I recently started learning Django framework and had some problems with variable validation. When I try to output field.errors variable in html file there is no output, although when I pass error variable from create method, it outputs "errors" list (i.e. clean_number method is supposed to work) and when I fix them, list gets smaller (i.e. clean_number method does not work). Please tell me what I am doing wrong. Thanks in advance.
File create.html
<!doctype html>
<html lang="ru">
<head>
<meta charset="UTF-8">
<meta name="viewport>
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Adding a train to the list</title>
<link href="https://getbootstrap.com/docs/5.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-GLhlTQ8iRABdZLl6O3oVMWSktQOp6b7In1Zl3/Jr59b6EGGoI1aFkw7cmDA6j6gD" crossorigin="anonymous">
<style>
.sidenav {
height: 100%;
width: 267px;
position: fixed;
z-index: 1;
top: 0;
left: 0;
background-color: #f2f2f2;
overflow-x: hidden;
padding-top: 50px;
}
.container {
max-width: 900px;
}
</style>
</head>
<body>
<body class="bg-light">
<header class="navbar navbar-dark sticky-top bg-dark flex-md-nowrap p-0 shadow">
<a class="navbar-brand col-md-3 col-lg-2 me-0 px-3 fs-6" href="/">Home page</a>
<button class="navbar-toggler position-absolute d-md-none collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#sidebarMenu" aria-controls="sidebarMenu" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<input class="form-control form-control-dark w-100 rounded-0 border-0" type="text" placeholder="Search" aria-label="Search">
<div class="navbar-nav">
<div class="nav-item text-nowrap">
<a class="nav-link px-3"></a>
</div>
</div>
</header>
<div class="container">
<main>
<div class="row g-5">
<div class="py-5 text-center">
<h2>Add a train</h2>
<p class="lead">On this page, you need to fill in all the fields and follow the instructions.</p>
<form method="post">
<div class="row g-3">
{% csrf_token %}
{% for field in form %}
{{ field }}
<div class="alert alert-danger">
{{ field.errors }}
{% if !field.errors %}
{{ error }}
{% endif %}
</div>
{% endfor %}
<hr class="my-4">
<button class="w-100 btn btn-primary btn-lg" type="submit">Save changes</button>
</div>
</form>
</div>
</div>
</main>
</div>
</body>
</body>
</html>
File forms.py
from .models import Train
from django.forms import ModelForm, NumberInput
from django.core.exceptions import ValidationError
class TrainForm(ModelForm):
class Meta:
model = Train
fields = ["number", "amount_stops"]
widgets = {
"number": NumberInput(attrs={
'class': 'form-control',
'placeholder': 'Enter the train number',
}),
"amount_stops": NumberInput(attrs={
'class': 'form-control',
'placeholder': 'Enter the number of stops'
})
}
def clean_number(self):
number = self.cleaned_data['number']
if number > 100:
raise ValidationError('The number is over 100!')
return number
def clean_amount_stops(self):
amount_stops = self.cleaned_data['amount_stops']
if amount_stops > 100:
raise ValidationError('The amount of stops is over 100!')
return amount_stops
File views.py
from django.shortcuts import render, redirect
from .forms import TrainForm
def create(request):
error = ''
if request.method == 'POST':
form = TrainForm(request.POST)
if form.is_valid():
form.save()
return redirect('/')
else:
error = form.errors
form = TrainForm()
context = {
'form': form,
'error': error
}
return render(request, 'main/create.html', context)
Changed the template, but still nothing has changed.
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<form method="post">
{% csrf_token %}
{% for field in form %}
{{ field }}<p>
{{ field.errors }}<p>
{% endfor %}
<button type="submit">Save</button>
</form>
</body>
</html>
===========================
10/02/23: I tried to re-create the project without using the PyCharm IDE, just using Windows PowerShell, but nothing has changed, as it is not displayed and does not show(. My project creation:
Creating an AppDjango folder
In Terminal PowerShell:
-> cd D:\AppDjango\ - Navigate to Project
-> PS D:\AppDjango> python -m venv virenv
-> PS D:\AppDjango> virenv\Scripts\Activate.ps1
-> (virenv) PS D:\AppDjango> python -m pip install Django
-> (virenv) PS D:\AppDjango> django-admin startproject AppDjango
-> (virenv) PS D:\AppDjango> cd AppDjango
-> (virenv) PS D:\AppDjango\AppDjango> python manage.py runserver
-> (virenv) PS D:\AppDjango\AppDjango> ^C (Ctrl + C) - Finish process
-> (virenv) PS D:\AppDjango\AppDjango> python manage.py startapp MainApp
-> (virenv) PS D:\AppDjango\AppDjango> python manage.py migrate
Next, I changed the configuration of the setting.py file:
import os <- Only added
...
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'MainApp' <- Only added
]
...
TEMPLATES = [
{
...
'DIRS': [os.path.join(BASE_DIR,'templates'),], <- Only changed
...
},
]
I added the table to the models.py file:
from django.db import models
class Train(models.Model):
number = models.IntegerField()
amount_stops = models.IntegerField()
def __str__(self):
return str(self.number)
I created the forms.py file and added the code:
from .models import Train
from django.forms import ModelForm, NumberInput
from django.core.exceptions import ValidationError
class TrainForm(ModelForm):
class Meta:
model = Train
fields = ["number", "amount_stops"]
widgets = {
"number": NumberInput(attrs={
'class': 'form-control',
'placeholder': 'Enter the train number',
}),
"amount_stops": NumberInput(attrs={
'class': 'form-control',
'placeholder': 'Enter the number of stops'
})
}
def clean_number(self):
number = self.cleaned_data['number']
if number > 100:
raise ValidationError('The number is over 100!')
return number
def clean_amount_stops(self):
amount_stops = self.cleaned_data['amount_stops']
if amount_stops > 100:
raise ValidationError('The amount of stops is over 100!')
return amount_stops
I added the code to the views.py file:
from django.shortcuts import render, redirect
from .forms import TrainForm
def create(request):
errors_Main = ''
if request.method == 'POST':
form = TrainForm(request.POST)
if form.is_valid():
form.save()
else:
errors_Main = form.errors
form = TrainForm()
context = {
'form': form,
'errors_Main': errors_Main
}
return render(request, 'MainApp/create.html', context)
I created a new file D:\AppDjango\AppDjango\MainApp\urls.py and added the code:
from django.urls import path
from . import views
urlpatterns = [
path('', views.create, name='create')
]
I also changed the file D:\AppDjango\AppDjango\AppDjango\urls.py (the one that originally generated Django):
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('MainApp.urls'))
]
I created a template file .\MainApp\templates\MainApp\create.html and added code:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<form method="post">
{% csrf_token %}
{% for field in form %}
{{ field }}<p>
{% for error in field.errors %} <- added
{{ error }}
{% endfor %}
{% endfor %}
<button type="submit">Save</button>
</form>
</body>
</html>
Recent changes to the PowerShell Terminal:
-> (virenv) PS D:\AppDjango\AppDjango> python manage.py makemigrations
Migrations for 'MainApp':
MainApp\migrations\0001_initial.py
- Create model Train
-> (virenv) PS D:\AppDjango\AppDjango> python manage.py migrate
Operations to perform:
Apply all migrations: MainApp, admin, auth, contenttypes, sessions
Running migrations:
Applying MainApp.0001_initial... OK
-> (virenv) PS D:\AppDjango\AppDjango> python manage.py runserver
Result: Still does not display errors. Can you please tell me at what stage I screwed up?
Try to use the looping syntax of showing errors so instead of only {{field.errors}} use it as following:
{% for error in field.errors %}
{{ error }}
{% endfor %}
Thank you #Sunderam Dubey for helping. I found the answer to my question. The problem was in the create method, I rewrote it a little differently (code below) and I was able to display the error text:
def create(request):
form = TrainForm()
if request.method == "POST":
form = TrainForm(request.POST)
if form.is_valid():
form.save()
return redirect('/')
return render(request, "main/create.html", {"form": form})
I need help with my code, I'm making a form in django and I can't solve this error.
views.py:
def ferrocarrilFormulario(request):
if request.method =="POST":
miFormulario = ferrocarrilFormulario(request.POST)
print(miFormulario)
if miFormulario.is_valid:
informacion = miFormulario.cleaned_data
ferrocarril = ferrocarril(request.POST["tipo"], request.POST["precio"])
ferrocarril.save()
return render (request, "AppCoder/inicio.html")
Forms.py:
from django import forms
class ferrocarrilFormulario(forms.Form):
tipo= forms.CharField()
precio = forms.IntegerField()
Form HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Agrega un ferrocarril</title>
</head>
<body>
{% if.miFormulario.errors %}
<p style="color: red;"> Datos mal ingresados</p>
{% endif %}
<form action="" method="POST"{% csrf_token %}
<table>
{{ miFormulario.as_tabble }}
</table>
<input type="submit" value="Enviar">
></form>
</body>
</html>
urls.py:
from django.urls import path
from AppCoder import views
urlpatterns = [
path('',views.inicio, name="Inicio"),
path("ferrocarril/", views.ferrocarril, name="ferrocarril"),
path("vias/", views.vias, name="vias"),
path("manodeobra/", views.manodeobra, name="manodeobra"),
path("tables.html/", views.tables, name="tables"),
path("ferrocarrilFormulario/", views.ferrocarrilFormulario, name="ferrocarrilFormulario")
thank you <3
I wanted the form to work after that, but that is not the case.
PS: if I put the request, it generates another error, and in the tutorial it appears without the request.
Thanks again.
I'm fairly new to using the django framework and recently I made a system with it where it submits data to mysql db through a html form. I got it working eventually and everything seemed quite fine, though I noticed a bug where if I refresh the page django stops sending data to mysql, has this ever happened to anyone?
Stuff for reference:
views.py
from django.shortcuts import render
from websiteDB.models import dbInsert
from django.contrib import messages
def insertToDB(request):
if request.method == "POST":
if request.POST.get('uname') and request.POST.get('email') and request.POST.get('message'):
post = dbInsert()
post.uname = request.POST.get('uname')
post.email = request.POST.get('email')
post.message = request.POST.get('message')
post.save()
messages.success(request, "Message sent successfully.")
return render(request, "contact.html")
else:
return render(request, "contact.html")
models.py
from django.db import models
class dbInsert(models.Model):
uname = models.CharField(max_length=100)
email = models.EmailField()
message = models.TextField()
class Meta:
db_table = "contactrequest"
urls.py
"""
websiteDB URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/4.0/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path
from django.views.generic import TemplateView
from . import views
from . import index
urlpatterns = [
#path('admin/', admin.site.urls),
path('homepage', index.page_home, name= 'hpage'),
path('', views.insertToDB),
path('contactpage', index.contact_page, name= 'cpage')
]
contact.html
{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Outfit:wght#200&display=swap" rel="stylesheet">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="{% static 'css/css/styles.css' %}">
<title>Document</title>
</head>
<body style="background-color: rgb(74, 36, 110);">
<script src="{% static 'js/main.js' %}"></script>
<div class="top-nav">
HOME
PRODUCTS
CONTACT
ABOUT
COMMUNITY
</div>
<div class="div-align">
<h2>Contact</h2>
<p>Reach us for questions/concerns through the form below.</p>
</div>
<form class="fontmaker" method="post">
{% csrf_token %}
<label for="Username">Username:</label><br>
<input type="text" id="Username" name="uname" required><br>
<label for="E-mail">E-mail:</label><br>
<input type="text" id="Email" name="email" required>
<label for="Reason" class="margin">Message:</label>
<textarea id="Reason" name="message" rows="10" cols="60" required>Type your reason of contact here.</textarea>
<input type="submit" value="Submit" class="rounded-corners" id="submitBtn">
{% if messages %}
{% for message in messages %}
{{message}}
{% endfor %}
{% endif %}
</form>
</body>
</html>
There are no errors in terminal, and the button click also properly sends a POST req:
Terminal output
I'm also new to posting on stackoverflow, tell me if there's something else to improve on in the future when posting.
index.py
from django.http import HttpResponse
from django.shortcuts import render
def page_home(request):
return render(request, 'index.html')
def contact_page(request):
return render(request, 'contact.html')
Thanks in advance.
If you render the contactpage/ URL, then if you submit the form, you will submit it to the contact view, but that view does not handle the data, nor does it create any entry. You must make sure that you post the form to the insertToDB view. You can do this by giving the view a name:
urlpatterns = [
# …,
path('', views.insertToDB, name='insertToDB'),
# …
]
and then specify the endpoint in the form:
<form class="fontmaker" method="post" action="{% insertToDB %}">
<!-- … -->
</form>
In case of a successful POST request, you should also redirect, for example with:
from django.shortcuts import redirect
def insertToDB(request):
if request.method == 'POST':
if request.POST.get('uname') and request.POST.get('email') and request.POST.get('message'):
post = dbInsert.objects.create(
uname = request.POST['uname'],
email = request.POST['email'],
message = request.POST['message']
)
messages.success(request, 'Message sent successfully.')
return redirect('cpage')
return render(request, 'contact.html')
else:
return render(request, 'contact.html')
I would advise to work with Django forms [Django-doc], for example a modelform [Django-doc] to validate and clean form input and remove a lot of boilerplate code.
I’m trying to write a web app which accepts a website visitor’s input which is a 12 digit “Chuckee Cheese” membership card number and then redacts the first 8 digits and presents the redacted number. I’ve got my template written and the basic logic inside my app’s views.py. The problem now is that after the user enters his or her card number, Django is not processing the user input properly. Like, the redacted number is not being presented and served in the template as intended.
Here is a pic on imgur showing my website running on my dev server now. As you can see in that pic, in the web address bar Django receives the ‘ccEntry’ GET Request with ‘123456789102’ as user input. So I guess that kind of works. But below the two h1 elements (in lime green), Django should show the card number ‘123456789102’ as well as the redacted card number ‘xxxx xxxx 9102’ but instead it’s blank. What is wrong here? As far as I can tell, I believe the problem involves either the first two functions inside my redactors views.py or the way my app’s urls.py is arranged.
Here is my views.py :
from django.shortcuts import render
# Create your views here.
def redactors(request):
return render(request, 'alls/landings.html')
def home(request):
if 'ccEntry' in request.GET:
number = request.GET['ccEntry']
redacted_num = 'xxxx xxxx {}'.format(number[-4:])
return render(request, 'alls/landings.html', {'number':number, 'redacted_num':redacted_num})
else:
return render(request, 'alls/landings.html')
def results(request):
return render(request, 'alls/landings.html')
Here is my app’s urls.py:
from django.urls import path, include
from . import views
urlpatterns = [
path('home', views.home, name='home'),
path('results', views.results, name='results'),
]
Those are the two scripts where I believe the problem is.
For what it is worth, here are some other related configuration files and scripts that are in play:
Lightly abbreviated alls/landings.html template:
{% load static %}
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="description" content="The HTML5 Herald">
<meta name="robots" content="noindex,nofollow" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- Custom -->
<link rel="stylesheet" href="{% static 'css/style.css' %}">
</head>
<body>
{% block content %}
<div class="card-processor">
<h3>Enter your fake Chuckee Cheese Neptune membership card number!</h3>
<form action="{% url 'posts' %}" method="get">
<div>
<label for="password">Enter Card Number:</label>
<input type="text" id="password" name="ccEntry" pattern="[0-9]{12}" maxlength="12"/>
<div class="requirements">Must be a 12 digit number and no letters. </div>
<input type="submit" value="Redact!" class="button"/>
</div>
</form>
<h1>Here is your fake Chuckee Cheese Neptune memnership card number!</h1>
<h3 style="color:lime">This was the original number that you entered:</h3>
<div class="field">{{ number }}</div>
<h3 style="color:lime">Here it is redacted:</h3>
<div class="field">{{ redacted_num }}</div>
<div class="field"><strong>Again? Click here!</strong></div>
</div> <!--- END card-processor -->
<div class="post-content">
{% for post in posts %}
<h1> Blog post title: <em>{{ post.title }}</strong></em>
<h4>Publication Date: {{ post.pub_date_preference }}</h4>
<img src="{{ post.image.url }}" class="authors-pic" style="" />
<!-- Body text should go here : -->
<p>{{ post.body|safe }}</p>
{% endfor %}
{% endblock %}
</body>
</html>
Parent urls.py router:
from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('posts.urls')),
path('', include('redactors.urls')),
path('', include('counters.urls')),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
I believe those are all the relevant files in play. However in case the problem is elsewhere, if you want to see the rest of my source code, here is a static snapshot tagged as v.0.7.0 on my GitHub.
It's also worth noting that I'm not getting a trace back and my server is not crashing so I don't have many leads in terms of searching on Google for other developers resolving similar or related issues.
It seems like the 'form' in landings.html is being submitted to the path with name "posts", But there is no path with this name in your app's urls.py.
Use this <form action="{% url 'home' %}" method="get"> instead of <form action="{% url 'posts' %}" method="get">.
so Im building and simple mooc plataform using Django 2.1 and Im having a problem.
Here you can find my entire project but ill describe all situation above, and here u can find a entire printscreen of django error.
So i have this project called TamerMooc, this project has 2 apps. A core app and a courses app.
This is the /courses/views.py file:
from django.shortcuts import render, get_object_or_404
from .models import Course
def index(request):
courses = Course.objects.all()
template_name = 'courses/index.html'
context = {
'courses':courses
}
return render(request, template_name, context)
def details(request, slug):
course = get_object_or_404(Course, slug=slug)
template_name = 'courses/details.html'
context = {
'course': course
}
return render(request, template_name, context)
And this is the /courses/urls.py file:
from django.contrib import admin
from django.urls import path
from . import views
urlpatterns = [
path('',views.index ,name='index'),
path('<slug:slug>', views.details , name='details'),
]
And at least the /core/templates/base.html file quoted in the error file.
<!doctype html>
{% load static %}
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="Simple MOOC - Uma simples plataforma de ensino a distância" />
<title>Tâmer MOOC</title>
<link rel="stylesheet" href="http://yui.yahooapis.com/pure/0.3.0/pure-min.css">
<link rel="stylesheet" href="{% static 'css/styles.css' %}" />
</head>
<body>
<div class="header">
<div class="pure-menu pure-menu-open pure-menu-fixed pure-menu-horizontal">
<a class="pure-menu-heading" href="{% url 'home' %}">TÂMER MOOC</a>
<ul>
<li class="pure-menu-selected">Início</li>
<li>Cursos</li>
<li><a href="{% url 'contact' %}"}>Contato</a></li>
</ul>
</div>
</div>
<div class = "content">
{% block content %}{% endblock %}
<div class="footer">
Tâmer MOOC - Uma simples plataforma de ensino a distância
</div>
</div>
<script src="http://yui.yahooapis.com/3.12.0/build/yui/yui-min.js"></script>
</body>
</html>
I really read a lot of questions here on stackoverflow about similar errors but cant find a solution.
I think the problem is here.
<a href=" {{ course.get_absolute_url }} "> <!--- {% url 'courses:details' course.slug %}--->
^^^^^ ^^^^
In django template, comments does not work in this way. If you want to comment out something do it like this:
{% comment %}
{% url 'courses:details' course.slug %}
{% endcomment %}
Or
{# url 'courses:details' course.slug #}
Relevant documentation can be found here.