Reverse for 'action' with arguments '('',)' not found - python-3.x

I have error that seemed to happen to some other people, still I didn't figure out what am I doing wrong, so asking you all for help. Can you please support me with my code? As soon as I try to use form element with action "{% url 'mtg:action' card.name %}" I receive error Reverse for 'action' with arguments '('',)' not found
EDIT: I'd like to add that card name is suppsed to be written by the user, so its not available as page is loaded.
Thanks in advance!
views.py:
def index(request):
context = {'cards': Card.objects.all()}
return render(request, 'mtg/index.html', context)
def lookup(request, card_name):
context = {'card_lookup': Card.objects.all()}
return render(request, 'mtg/index.html', context)
def action(request, card_name):
card = get_object_or_404(Card, pk=card_name)
# Always return an HttpResponseRedirect after successfully dealing
# with POST data. This prevents data from being posted twice if a
# user hits the Back button.
return HttpResponseRedirect(reverse('mtg:tmpl', args=card_name))
urls.py:
app_name = 'mtg'
urlpatterns = [
path('', views.index, name="index"),
path('<str:card_name>/img', views.lookup, name='img'),
path('<str:card_name>/action', views.action, name='action'),
]
index.html:
<body>
<form class="wrap" action="{% url 'mtg:action' card.name %}" method="post">
<input class="searchTerm"/>
<button class="center" name="search">Search for synergy</button>
<button class="center" name="lookup">Lookup a card</button>
</form>
{% if lookup_card %}<div>{{ card_lookup }}</div>{% endif %}
</body>
EDIT: as requested adding also logs of error:
Environment:
Request Method: GET
Request URL: http://127.0.0.1:8000/
Django Version: 3.1.3
Python Version: 3.7.8
Installed Applications:
['mtg.apps.MtgConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware']
Template error:
In template C:\Users\Sajemiur\PycharmProjects\MtG_reader\mtg_django\mtg\templates\mtg\index.html, error at line 45
Reverse for 'action' with arguments '('',)' not found. 1 pattern(s) tried: ['(?P<card_name>[^/]+)/action$']
35 : .wrap{
36 : width: 30%;
37 : position: absolute;
38 : top: 30%;
39 : left: 50%;
40 : transform: translate(-50%, -50%);
41 : }
42 : </style>
43 : </head>
44 : <body>
45 : <form class="wrap" action=" {% url 'mtg:action' card.name %} " method="post">
46 : <input class="searchTerm"/>
47 : <button class="center" name="search">Search for synergy</button>
48 : <button class="center" name="lookup">Lookup a card</button>
49 : {% if card_lookup %}<img src="{{ card_lookup }}" width="80" height="200"/>{% endif %}
50 : </form>
51 : </body>
52 : </html>
Traceback (most recent call last):
File "C:\Users\Sajemiur\anaconda3\envs\mtgenv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
response = get_response(request)
File "C:\Users\Sajemiur\anaconda3\envs\mtgenv\lib\site-packages\django\core\handlers\base.py", line 179, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\Sajemiur\PycharmProjects\MtG_reader\mtg_django\mtg\views.py", line 14, in index
return render(request, 'mtg/index.html', context)
File "C:\Users\Sajemiur\anaconda3\envs\mtgenv\lib\site-packages\django\shortcuts.py", line 19, in render
content = loader.render_to_string(template_name, context, request, using=using)
File "C:\Users\Sajemiur\anaconda3\envs\mtgenv\lib\site-packages\django\template\loader.py", line 62, in render_to_string
return template.render(context, request)
File "C:\Users\Sajemiur\anaconda3\envs\mtgenv\lib\site-packages\django\template\backends\django.py", line 61, in render
return self.template.render(context)
File "C:\Users\Sajemiur\anaconda3\envs\mtgenv\lib\site-packages\django\template\base.py", line 170, in render
return self._render(context)
File "C:\Users\Sajemiur\anaconda3\envs\mtgenv\lib\site-packages\django\template\base.py", line 162, in _render
return self.nodelist.render(context)
File "C:\Users\Sajemiur\anaconda3\envs\mtgenv\lib\site-packages\django\template\base.py", line 938, in render
bit = node.render_annotated(context)
File "C:\Users\Sajemiur\anaconda3\envs\mtgenv\lib\site-packages\django\template\base.py", line 905, in render_annotated
return self.render(context)
File "C:\Users\Sajemiur\anaconda3\envs\mtgenv\lib\site-packages\django\template\defaulttags.py", line 446, in render
url = reverse(view_name, args=args, kwargs=kwargs, current_app=current_app)
File "C:\Users\Sajemiur\anaconda3\envs\mtgenv\lib\site-packages\django\urls\base.py", line 87, in reverse
return iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs))
File "C:\Users\Sajemiur\anaconda3\envs\mtgenv\lib\site-packages\django\urls\resolvers.py", line 685, in _reverse_with_prefix
raise NoReverseMatch(msg)
Exception Type: NoReverseMatch at /
Exception Value: Reverse for 'action' with arguments '('',)' not found. 1 pattern(s) tried: ['(?P<card_name>[^/]+)/action$']

you used {% if lookup_card %} but you passed in your view card_lookup
and if you want only name of card than get only name from Card object context = {'cards': Card.objects.values(name)}

Related

error in django templates at {{form.as_table}} when trying to use Create form

I'm workin on a project of a webApp for fleet managment, using Django 3.1 and Python 3.7.
I'm using models:
class Driver(Employee):
supervisor_id = models.ForeignKey('Supervisor', on_delete=models.CASCADE, blank=True, null=True)
projects = models.ManyToManyField('Client', through='ProjectFleet', blank=True, null=True)
is_driver=True
def __str__(self):
return (self.last_name)
class Client(models.Model):
client_name = models.CharField(max_length=128, blank=True, null=True)
client_adress = models.CharField(max_length=128, blank=True, null=True)
client_logo = models.ImageField(upload_to='ClientsLogos/', max_length=100, blank=True, null=True)
phone_number1 = PhoneNumberField(blank=True, null=True)
phone1_label = models.CharField(max_length=128, blank=True, null=True)
phone_number2 = PhoneNumberField(blank=True, null=True)
phoneé_label = models.CharField(max_length=128, blank=True, null=True)
phone_number3 = PhoneNumberField( blank=True, null=True)
phone3_label = models.CharField(max_length=128, blank=True, null=True)
client_email1 = models.EmailField(blank=True, null=True)
email1_label = models.CharField(max_length=128, blank=True, null=True)
client_email2 = models.EmailField(blank=True, null=True)
email2_label = models.CharField(max_length=128, blank=True, null=True)
client_email3 = models.EmailField(blank=True, null=True)
email3_label = models.CharField(max_length=128, blank=True, null=True)
drivers = models.ManyToManyField('Driver', through='ProjectFleet')
def __str__(self):
return (self.client_name)
class ProjectFleet(models.Model):
client_id = models.ForeignKey('Client', blank=True, null=True, on_delete=models.SET_NULL)
drivers = models.ForeignKey('Driver', blank=True, null=True, on_delete=models.SET_NULL)
def __str__(self):
return (self.client_id)
class Contract(models.Model):
client_id = models.ForeignKey('Client', blank=True, null=True, on_delete=models.SET_NULL)
contract_title = models.CharField(max_length=128, blank=True, null=True)
contract_details = models.CharField(max_length=512, blank=True, null=True)
effective_date = models.DateField(auto_now=False, auto_now_add=False, blank=True, null=True)
expiration_date = models.DateField(auto_now=False, auto_now_add=False, blank=True, null=True)
def __str__(self):
return (self.contract_title)
the views I'm trying to use :
class DriverCreationView(LoginRequiredMixin, CreateView):
model = Driver
fields = ['registration_number','first_name', 'last_name', 'password', 'cni', 'birth_date', 'birth_city', 'picture', 'matricule_cnss', 'driving_licence', 'recruitment_date', 'phone', 'salary', 'Contract_type', 'adress', 'city_id', 'region_id', 'payment_mode', 'bank_address', 'bank_id', 'is_driver', 'vehicle_id', 'supervisor_id', 'projects']
success_url = reverse_lazy('Drivers_App_Management:all-drivers')
class ClientCreationView(LoginRequiredMixin, CreateView):
model = Client
fields = '__all__'
success_url = reverse_lazy('Drivers_App_Management:all-clients')
class ProjectFleetCreationView(LoginRequiredMixin, CreateView):
model = ProjectFleet
fields = '__all__'
success_url = reverse_lazy('Drivers_App_Management:all-projectsfleet')
class ContractCreationView(LoginRequiredMixin, CreateView):
model = Contract
fields = '__all__'
success_url = reverse_lazy('Drivers_App_Management:all-contracts')
The problem I have is when I try to access the forms for the creation of Project fleet which is a trough table and also the creation of Contract.
The Templates for each one are:
projectfleet_form.html
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Client Creation</title>
</head>
<body>
<h1>This is the Project Fleet Creation form </h1>
<form class="" action="" method="post">
{% csrf_token %}
<table>
{{ form.as_table }}
</table>
<input type="submit" name="" value="submit">
<input type="submit" onclick="window.location='{% url 'Drivers_App_Management:all-projectsfleet' %}' ; return False;" value="Cancel">
</form>
</body>
</html>
and the contract_form.html
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Contract Creation</title>
</head>
<body>
<h1>This is the Contract Creation form </h1>
<form class="" action="" method="post">
{% csrf_token %}
<table>
{{form.as_table}}
{{ form.contract_title }}
{{ form.contract_details }}
{{ form.effective_date }}
{{ form.expiration_date }}
</table>
<input type="submit" name="" value="submit">
<input type="submit" onclick="window.location='{% url 'Drivers_App_Management:all-contracts' %}' ; return False;" value="Cancel">
</form>
</body>
</html>
for both templates I get an error that I don't understand:
Environment:
Request Method: GET
Request URL: http://127.0.0.1:8000/Drivers_App_Management/ProjectFleetCreation
Django Version: 3.1.3
Python Version: 3.7.4
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.gis',
'django_extensions',
'phonenumber_field',
'Drivers_App_Management',
'django_rename_app']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware']
Template error:
In template /home/mohammed/Projects/Transport_Project/Drivers_App_Management/templates/Drivers_App_Management/projectfleet_form.html, error at line 11
__str__ returned non-string (type NoneType)
1 : <html lang="en" dir="ltr">
2 : <head>
3 : <meta charset="utf-8">
4 : <title>Client Creation</title>
5 : </head>
6 : <body>
7 : <h1>This is the Project Fleet Creation form </h1>
8 : <form class="" action="" method="post">
9 : {% csrf_token %}
10 : <table>
11 : {{ form.as_table }}
12 : </table>
13 : <input type="submit" name="" value="submit">
14 : <input type="submit" onclick="window.location='{% url 'Drivers_App_Management:all-projectsfleet' %}' ; return False;" value="Cancel">
15 : </form>
16 : </body>
17 : </html>
18 :
Traceback (most recent call last):
File "/home/mohammed/anaconda3/envs/myEnv/lib/python3.7/site-packages/django/core/handlers/exception.py", line 47, in inner
response = get_response(request)
File "/home/mohammed/anaconda3/envs/myEnv/lib/python3.7/site-packages/django/core/handlers/base.py", line 202, in _get_response
response = response.render()
File "/home/mohammed/anaconda3/envs/myEnv/lib/python3.7/site-packages/django/template/response.py", line 105, in render
self.content = self.rendered_content
File "/home/mohammed/anaconda3/envs/myEnv/lib/python3.7/site-packages/django/template/response.py", line 83, in rendered_content
return template.render(context, self._request)
File "/home/mohammed/anaconda3/envs/myEnv/lib/python3.7/site-packages/django/template/backends/django.py", line 61, in render
return self.template.render(context)
File "/home/mohammed/anaconda3/envs/myEnv/lib/python3.7/site-packages/django/template/base.py", line 170, in render
return self._render(context)
File "/home/mohammed/anaconda3/envs/myEnv/lib/python3.7/site-packages/django/template/base.py", line 162, in _render
return self.nodelist.render(context)
File "/home/mohammed/anaconda3/envs/myEnv/lib/python3.7/site-packages/django/template/base.py", line 938, in render
bit = node.render_annotated(context)
File "/home/mohammed/anaconda3/envs/myEnv/lib/python3.7/site-packages/django/template/base.py", line 905, in render_annotated
return self.render(context)
File "/home/mohammed/anaconda3/envs/myEnv/lib/python3.7/site-packages/django/template/base.py", line 988, in render
output = self.filter_expression.resolve(context)
File "/home/mohammed/anaconda3/envs/myEnv/lib/python3.7/site-packages/django/template/base.py", line 671, in resolve
obj = self.var.resolve(context)
File "/home/mohammed/anaconda3/envs/myEnv/lib/python3.7/site-packages/django/template/base.py", line 796, in resolve
value = self._resolve_lookup(context)
File "/home/mohammed/anaconda3/envs/myEnv/lib/python3.7/site-packages/django/template/base.py", line 858, in _resolve_lookup
current = current()
File "/home/mohammed/anaconda3/envs/myEnv/lib/python3.7/site-packages/django/forms/forms.py", line 277, in as_table
errors_on_separate_row=False,
File "/home/mohammed/anaconda3/envs/myEnv/lib/python3.7/site-packages/django/forms/forms.py", line 236, in _html_output
'field_name': bf.html_name,
File "/home/mohammed/anaconda3/envs/myEnv/lib/python3.7/site-packages/django/utils/html.py", line 376, in <lambda>
klass.__str__ = lambda self: mark_safe(klass_str(self))
File "/home/mohammed/anaconda3/envs/myEnv/lib/python3.7/site-packages/django/forms/boundfield.py", line 34, in __str__
return self.as_widget()
File "/home/mohammed/anaconda3/envs/myEnv/lib/python3.7/site-packages/django/forms/boundfield.py", line 97, in as_widget
renderer=self.form.renderer,
File "/home/mohammed/anaconda3/envs/myEnv/lib/python3.7/site-packages/django/forms/widgets.py", line 241, in render
context = self.get_context(name, value, attrs)
File "/home/mohammed/anaconda3/envs/myEnv/lib/python3.7/site-packages/django/forms/widgets.py", line 678, in get_context
context = super().get_context(name, value, attrs)
File "/home/mohammed/anaconda3/envs/myEnv/lib/python3.7/site-packages/django/forms/widgets.py", line 639, in get_context
context['widget']['optgroups'] = self.optgroups(name, context['widget']['value'], attrs)
File "/home/mohammed/anaconda3/envs/myEnv/lib/python3.7/site-packages/django/forms/widgets.py", line 587, in optgroups
for index, (option_value, option_label) in enumerate(self.choices):
File "/home/mohammed/anaconda3/envs/myEnv/lib/python3.7/site-packages/django/forms/models.py", line 1157, in __iter__
yield self.choice(obj)
File "/home/mohammed/anaconda3/envs/myEnv/lib/python3.7/site-packages/django/forms/models.py", line 1171, in choice
self.field.label_from_instance(obj),
File "/home/mohammed/anaconda3/envs/myEnv/lib/python3.7/site-packages/django/forms/models.py", line 1240, in label_from_instance
return str(obj)
Exception Type: TypeError at /Drivers_App_Management/ProjectFleetCreation
Exception Value: __str__ returned non-string (type NoneType)
and for the Contract form :
Environment:
Request Method: GET
Request URL: http://127.0.0.1:8000/Drivers_App_Management/ContractCreation
Django Version: 3.1.3
Python Version: 3.7.4
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.gis',
'django_extensions',
'phonenumber_field',
'Drivers_App_Management',
'django_rename_app']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware']
Template error:
In template /home/mohammed/Projects/Transport_Project/Drivers_App_Management/templates/Drivers_App_Management/contract_form.html, error at line 11
__str__ returned non-string (type NoneType)
1 : <html lang="en" dir="ltr">
2 : <head>
3 : <meta charset="utf-8">
4 : <title>Contract Creation</title>
5 : </head>
6 : <body>
7 : <h1>This is the Contract Creation form </h1>
8 : <form class="" action="" method="post">
9 : {% csrf_token %}
10 : <table>
11 : {{form.as_table}}
12 : {{ form.contract_title }}
13 : {{ form.contract_details }}
14 : {{ form.effective_date }}
15 : {{ form.expiration_date }}
16 : </table>
17 : <input type="submit" name="" value="submit">
18 : <input type="submit" onclick="window.location='{% url 'Drivers_App_Management:all-contracts' %}' ; return False;" value="Cancel">
19 : </form>
20 : </body>
21 : </html>
Traceback (most recent call last):
File "/home/mohammed/anaconda3/envs/myEnv/lib/python3.7/site-packages/django/core/handlers/exception.py", line 47, in inner
response = get_response(request)
File "/home/mohammed/anaconda3/envs/myEnv/lib/python3.7/site-packages/django/core/handlers/base.py", line 202, in _get_response
response = response.render()
File "/home/mohammed/anaconda3/envs/myEnv/lib/python3.7/site-packages/django/template/response.py", line 105, in render
self.content = self.rendered_content
File "/home/mohammed/anaconda3/envs/myEnv/lib/python3.7/site-packages/django/template/response.py", line 83, in rendered_content
return template.render(context, self._request)
File "/home/mohammed/anaconda3/envs/myEnv/lib/python3.7/site-packages/django/template/backends/django.py", line 61, in render
return self.template.render(context)
File "/home/mohammed/anaconda3/envs/myEnv/lib/python3.7/site-packages/django/template/base.py", line 170, in render
return self._render(context)
File "/home/mohammed/anaconda3/envs/myEnv/lib/python3.7/site-packages/django/template/base.py", line 162, in _render
return self.nodelist.render(context)
File "/home/mohammed/anaconda3/envs/myEnv/lib/python3.7/site-packages/django/template/base.py", line 938, in render
bit = node.render_annotated(context)
File "/home/mohammed/anaconda3/envs/myEnv/lib/python3.7/site-packages/django/template/base.py", line 905, in render_annotated
return self.render(context)
File "/home/mohammed/anaconda3/envs/myEnv/lib/python3.7/site-packages/django/template/base.py", line 988, in render
output = self.filter_expression.resolve(context)
File "/home/mohammed/anaconda3/envs/myEnv/lib/python3.7/site-packages/django/template/base.py", line 671, in resolve
obj = self.var.resolve(context)
File "/home/mohammed/anaconda3/envs/myEnv/lib/python3.7/site-packages/django/template/base.py", line 796, in resolve
value = self._resolve_lookup(context)
File "/home/mohammed/anaconda3/envs/myEnv/lib/python3.7/site-packages/django/template/base.py", line 858, in _resolve_lookup
current = current()
File "/home/mohammed/anaconda3/envs/myEnv/lib/python3.7/site-packages/django/forms/forms.py", line 277, in as_table
errors_on_separate_row=False,
File "/home/mohammed/anaconda3/envs/myEnv/lib/python3.7/site-packages/django/forms/forms.py", line 236, in _html_output
'field_name': bf.html_name,
File "/home/mohammed/anaconda3/envs/myEnv/lib/python3.7/site-packages/django/utils/html.py", line 376, in <lambda>
klass.__str__ = lambda self: mark_safe(klass_str(self))
File "/home/mohammed/anaconda3/envs/myEnv/lib/python3.7/site-packages/django/forms/boundfield.py", line 34, in __str__
return self.as_widget()
File "/home/mohammed/anaconda3/envs/myEnv/lib/python3.7/site-packages/django/forms/boundfield.py", line 97, in as_widget
renderer=self.form.renderer,
File "/home/mohammed/anaconda3/envs/myEnv/lib/python3.7/site-packages/django/forms/widgets.py", line 241, in render
context = self.get_context(name, value, attrs)
File "/home/mohammed/anaconda3/envs/myEnv/lib/python3.7/site-packages/django/forms/widgets.py", line 678, in get_context
context = super().get_context(name, value, attrs)
File "/home/mohammed/anaconda3/envs/myEnv/lib/python3.7/site-packages/django/forms/widgets.py", line 639, in get_context
context['widget']['optgroups'] = self.optgroups(name, context['widget']['value'], attrs)
File "/home/mohammed/anaconda3/envs/myEnv/lib/python3.7/site-packages/django/forms/widgets.py", line 587, in optgroups
for index, (option_value, option_label) in enumerate(self.choices):
File "/home/mohammed/anaconda3/envs/myEnv/lib/python3.7/site-packages/django/forms/models.py", line 1157, in __iter__
yield self.choice(obj)
File "/home/mohammed/anaconda3/envs/myEnv/lib/python3.7/site-packages/django/forms/models.py", line 1171, in choice
self.field.label_from_instance(obj),
File "/home/mohammed/anaconda3/envs/myEnv/lib/python3.7/site-packages/django/forms/models.py", line 1240, in label_from_instance
return str(obj)
Exception Type: TypeError at /Drivers_App_Management/ContractCreation
Exception Value: __str__ returned non-string (type NoneType)
I want to mention that I don't get any error if I use form with fields names {{form.contract_title}} for example but I got them without the label.
You managed to trick yourself into thinking that nullable foreign keys in a through model is a sane thing. It's not. In any ManyToMany relation, both foreign keys to the relation models should be set, otherwise there is no relation and no need for a row in the model.
This results in model choices with None values for the labels, which is what it's complaining about.
Root problem
The underlying problem is your __str__() method for both models. As the name indicates, it should always return a string, but you allow it to return None.
Change to:
def __str__(self) -> str:
return self.contract_title or ""
But you should really revisit your model design. Having fields with null=True has its uses, but for a CharField without unique=True, it's only causing problems with no benefits.

Unable to render template with flask wsgi [duplicate]

This question already has answers here:
Flask raises TemplateNotFound error even though template file exists
(13 answers)
Closed 2 years ago.
I have deployed a flask application, using mod_wsgi with apache2
Now, checking if everything works as intended, it looks like my endpoints which render templates are provoking some 500 status code errors.
Here's an approximative tree of my project:
main_folder
requirements.txt
mainfile.wsgi
app_folder
controllers
views.py
models
repository
services
static
templates
terms
en
terms.html
fr
terms.html
uploads
__init__.py
config.cfg
webapp.py
I am calling an endpoint which is supposed to render the templates/terms/en/terms.html and I get the following in the logs:
Traceback (most recent call last):
File "/usr/local/lib/python3.7/dist-packages/flask/app.py", line 2446, in wsgi_app
response = self.full_dispatch_request()
File "/usr/local/lib/python3.7/dist-packages/flask/app.py", line 1951, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/usr/local/lib/python3.7/dist-packages/flask/app.py", line 1820, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/usr/local/lib/python3.7/dist-packages/flask/_compat.py", line 39, in reraise
raise value
File "/usr/local/lib/python3.7/dist-packages/flask/app.py", line 1949, in full_dispatch_request
rv = self.dispatch_request()
File "/usr/local/lib/python3.7/dist-packages/flask/app.py", line 1935, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/var/www/main_folder/app_folder/controllers/views.py", line 33, in gts
return render_template('terms/' + lang + '/terms.html')
File "/usr/local/lib/python3.7/dist-packages/flask/templating.py", line 138, in render_template
ctx.app.jinja_env.get_or_select_template(template_name_or_list),
File "/usr/local/lib/python3.7/dist-packages/jinja2/environment.py", line 869, in get_or_select_template
return self.get_template(template_name_or_list, parent, globals)
File "/usr/local/lib/python3.7/dist-packages/jinja2/environment.py", line 830, in get_template
return self._load_template(name, self.make_globals(globals))
File "/usr/local/lib/python3.7/dist-packages/jinja2/environment.py", line 804, in _load_template
template = self.loader.load(self, name, globals)
File "/usr/local/lib/python3.7/dist-packages/jinja2/loaders.py", line 113, in load
source, filename, uptodate = self.get_source(environment, name)
File "/usr/local/lib/python3.7/dist-packages/flask/templating.py", line 60, in get_source
return self._get_source_fast(environment, template)
File "/usr/local/lib/python3.7/dist-packages/flask/templating.py", line 89, in _get_source_fast
raise TemplateNotFound(template)
jinja2.exceptions.TemplateNotFound: terms/en/terms.html
Here's an excerp of the code where I try to render the template in app_folder/controllers/views.py:
from flask import render_template, request, send_file
from app_folder.controllers import Controllers as controllers
def gts(lang='fr'):
return render_template('terms/' + lang + '/terms.html')
controllers().register(
'/cgu/<string:lang>',
'cgu_lang',
gts
)
I want to specify that endpoints with JSON body results are functionning, uploading ressources are working as well, and getting an uploaded ressource is working.
Only endpoints which should render templates are not working, which is getting me worried as well for endpoints which should send emails using an email template
Is there any fix I should apply when serving the application with wsgi?
Edit: FYI, this is the __init__.py in the controllers folder
import pkgutil
METHODS = set([
'GET',
'POST',
'PUT',
'PATCH',
'DELETE',
'COPY',
'HEAD',
'OPTIONS',
'LINK',
'UNLINK',
'PURGE',
'LOCK',
'UNLOCK',
'PROPFIND',
'VIEW'
])
class Controllers:
class __OnlyOne:
# ======================================================
# the code goes here
# =======================================================
def __init__(self):
self.val = None
self.rules = []
def __str__(self):
return 'self' + self.val
def register(self, rule, view_name, view_func):
r = {}
r["rule"] = rule
r["view_name"] = view_name
r["view_func"] = view_func
self.rules.append(r)
def register_methods(self, rule, view_name, view_func, methods=METHODS):
r = {}
r["rule"] = rule
r["view_name"] = view_name
r["view_func"] = view_func
r["methods"] = methods
self.rules.append(r)
def grab(self, app):
for r in self.rules:
if "methods" not in r.keys():
app.add_url_rule(r["rule"], r["view_name"], r["view_func"])
else:
app.add_url_rule(r["rule"], r["view_name"],
r["view_func"], methods=r["methods"])
# =================================================================
# the code goes up there
# ==================================================================
instance = None
def __new__(cls): # __new__ always a classmethod
if not Controllers.instance:
Controllers.instance = Controllers.__OnlyOne()
return Controllers.instance
def __getattr__(self, name):
return getattr(self.instance, name)
def __setattr__(self, name):
return setattr(self.instance, name)
# import all the modules in folder
__all__ = []
for loader, module_name, is_pkg in pkgutil.walk_packages(__path__):
__all__.append(module_name)
_module = loader.find_module(module_name).load_module(module_name)
globals()[module_name] = _module
I symlinked my app_folder/templates into my main_folder and it's now working

Unable to load static files after transferring uploaded files to AWS S3 Bucket

Ok so , I am using Python Django. I am trying to deploy my application. But first, I wanted to transfer my media file (where the user uploads their images like for ex-profile picture.). However now, I made a S3 bucket and transferred my media file to the bucket.
Unfortunately all of my static files that needs to be loaded during the template rendering using {% load static %} are unable to do so. It is throwing an error.
Here is my traceback:-
Environment:
Request Method: GET
Request URL: http://127.0.0.1:8000/profile/
Django Version: 2.2
Python Version: 3.7.3
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'crispy_forms',
'social_django',
'cart.apps.CartConfig',
'payment.apps.PaymentConfig',
'orders.apps.OrdersConfig',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'storages',
'products',
'drf_paytm',
'drfaddons',
'feedback.apps.FeedbackConfig',
'users.apps.UsersConfig',
'shop.apps.ShopConfig']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'social_django.middleware.SocialAuthExceptionMiddleware']
Template error:
In template /Users/shyambalakrishnan/dev/trydjango/src/templates/base.html, error at line 0
Required parameter name not set
1 : {% load static %}
2 : <!DOCTYPE html>
3 : <html>
4 : <head>
5 : <title>{% block title %} Online Shop {% endblock %}</title>
6 : <!-- Required meta tags -->
7 : <meta charset="utf-8">
8 :
9 :
10 : <!-- Bootstrap CSS -->
Traceback:
File "/Users/shyambalakrishnan/Dev/trydjango/lib/python3.7/site-packages/django/template/base.py" in _resolve_lookup
829. current = current[bit]
During handling of the above exception ('ImageFieldFile' object is not subscriptable), another exception occurred:
File "/Users/shyambalakrishnan/Dev/trydjango/lib/python3.7/site-packages/django/core/handlers/exception.py" in inner
34. response = get_response(request)
File "/Users/shyambalakrishnan/Dev/trydjango/lib/python3.7/site-packages/django/core/handlers/base.py" in _get_response
115. response = self.process_exception_by_middleware(e, request)
File "/Users/shyambalakrishnan/Dev/trydjango/lib/python3.7/site-packages/django/core/handlers/base.py" in _get_response
113. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Users/shyambalakrishnan/Dev/trydjango/lib/python3.7/site-packages/django/contrib/auth/decorators.py" in _wrapped_view
21. return view_func(request, *args, **kwargs)
File "/Users/shyambalakrishnan/Dev/trydjango/src/users/views.py" in profile
50. return render(request, 'profile.html', context)
File "/Users/shyambalakrishnan/Dev/trydjango/lib/python3.7/site-packages/django/shortcuts.py" in render
36. content = loader.render_to_string(template_name, context, request, using=using)
File "/Users/shyambalakrishnan/Dev/trydjango/lib/python3.7/site-packages/django/template/loader.py" in render_to_string
62. return template.render(context, request)
File "/Users/shyambalakrishnan/Dev/trydjango/lib/python3.7/site-packages/django/template/backends/django.py" in render
61. return self.template.render(context)
File "/Users/shyambalakrishnan/Dev/trydjango/lib/python3.7/site-packages/django/template/base.py" in render
171. return self._render(context)
File "/Users/shyambalakrishnan/Dev/trydjango/lib/python3.7/site-packages/django/template/base.py" in _render
163. return self.nodelist.render(context)
File "/Users/shyambalakrishnan/Dev/trydjango/lib/python3.7/site-packages/django/template/base.py" in render
937. bit = node.render_annotated(context)
File "/Users/shyambalakrishnan/Dev/trydjango/lib/python3.7/site-packages/django/template/base.py" in render_annotated
904. return self.render(context)
File "/Users/shyambalakrishnan/Dev/trydjango/lib/python3.7/site-packages/django/template/loader_tags.py" in render
150. return compiled_parent._render(context)
File "/Users/shyambalakrishnan/Dev/trydjango/lib/python3.7/site-packages/django/template/base.py" in _render
163. return self.nodelist.render(context)
File "/Users/shyambalakrishnan/Dev/trydjango/lib/python3.7/site-packages/django/template/base.py" in render
937. bit = node.render_annotated(context)
File "/Users/shyambalakrishnan/Dev/trydjango/lib/python3.7/site-packages/django/template/base.py" in render_annotated
904. return self.render(context)
File "/Users/shyambalakrishnan/Dev/trydjango/lib/python3.7/site-packages/django/template/loader_tags.py" in render
62. result = block.nodelist.render(context)
File "/Users/shyambalakrishnan/Dev/trydjango/lib/python3.7/site-packages/django/template/base.py" in render
937. bit = node.render_annotated(context)
File "/Users/shyambalakrishnan/Dev/trydjango/lib/python3.7/site-packages/django/template/base.py" in render_annotated
904. return self.render(context)
File "/Users/shyambalakrishnan/Dev/trydjango/lib/python3.7/site-packages/django/template/base.py" in render
987. output = self.filter_expression.resolve(context)
File "/Users/shyambalakrishnan/Dev/trydjango/lib/python3.7/site-packages/django/template/base.py" in resolve
671. obj = self.var.resolve(context)
File "/Users/shyambalakrishnan/Dev/trydjango/lib/python3.7/site-packages/django/template/base.py" in resolve
796. value = self._resolve_lookup(context)
File "/Users/shyambalakrishnan/Dev/trydjango/lib/python3.7/site-packages/django/template/base.py" in _resolve_lookup
837. current = getattr(current, bit)
File "/Users/shyambalakrishnan/Dev/trydjango/lib/python3.7/site-packages/django/db/models/fields/files.py" in url
62. return self.storage.url(self.name)
File "/Users/shyambalakrishnan/Dev/trydjango/lib/python3.7/site-packages/storages/backends/s3boto3.py" in url
620. params['Bucket'] = self.bucket.name
File "/Users/shyambalakrishnan/Dev/trydjango/lib/python3.7/site-packages/storages/backends/s3boto3.py" in bucket
326. self._bucket = self._get_or_create_bucket(self.bucket_name)
File "/Users/shyambalakrishnan/Dev/trydjango/lib/python3.7/site-packages/storages/backends/s3boto3.py" in _get_or_create_bucket
363. bucket = self.connection.Bucket(name)
File "/Users/shyambalakrishnan/Dev/trydjango/lib/python3.7/site-packages/boto3/resources/factory.py" in create_resource
474. client=self.meta.client)(*args, **kwargs)
File "/Users/shyambalakrishnan/Dev/trydjango/lib/python3.7/site-packages/boto3/resources/base.py" in __init__
119. 'Required parameter {0} not set'.format(identifier))
Exception Type: ValueError at /profile/
Exception Value: Required parameter name not set
During handling of the above exception ('ImageFieldFile' object is not subscriptable).
What could be the issue? My server is running . Also all the templates that do not need static are opening.
boto3==1.9.163
botocore==1.12.163
certifi==2019.3.9
chardet==3.0.4
defusedxml==0.6.0
dj-database-url==0.5.0
Django==2.2
django-crispy-forms==1.7.2
django-filter==2.0.0
django-sendsms==0.3.1
django-storages==1.7.1
djangorestframework==3.9.0
djangorestframework-jwt==1.11.0
docutils==0.14
drf-paytm==0.0.2
drfaddons==0.1.3
gunicorn==19.9.0
idna==2.8
jmespath==0.9.4
oauthlib==3.0.1
Pillow==6.0.0
pycrypto==2.6.1
pycryptodome==3.8.1
PyJWT==1.7.1
python-dateutil==2.8.0
python3-openid==3.1.0
pytz==2018.9
requests==2.21.0
requests-oauthlib==1.2.0
s3transfer==0.2.1
six==1.12.0
social-auth-app-django==3.1.0
social-auth-core==3.1.0
South==1.0.2
sqlparse==0.3.0
urllib3==1.24.3
whitenoise==4.1.2
In My settings.py file:-
I have added this codes at the end.
AWS_ACCESS_KEY_ID = os.environ.get('AWS_ACCESS_KEY_ID')
AWS_SECRET_ACCESS_KEY = os.environ.get('AWS_SECRET_ACCESS_KEY')
AWS_STORAGE_BUCKET_NAME = os.environ.get('AWS_STORAGE_BUCKET_NAME')
AWS_S3_FILE_OVERWRITE = False
AWS_DEFAULT_ACL = None
DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage'
And this codes for my static and media
STATIC_URL = '/static/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "static"),
#'/var/www/static/',
]
STATIC_ROOT =os.path.join(os.path.dirname(BASE_DIR), "static_cdn")
This is an image of my file directory.
File directory
Can anyone help me what I am doing wrong>

How do I use a Custom Provider [keycloak] for OAuth2.0 in Flask-Appbuilder?

I am trying to implement keycloak as a OAuth2.0 provider. I have all the necessary OAUTH_PROVIDER information and I have declared the AUTH_TYPE, AUTH_USER_REGISTRATION, AUTH_USER_REGISTRATION_ROLE (See code below)
AUTH_TYPE = AUTH_OAUTH
AUTH_USER_REGISTRATION = True
AUTH_USER_REGISTRATION_ROLE = "Public"
OAUTH_PROVIDERS = [
{
‘name’: ‘provider_name’,
‘icon’: ‘fa-icon’,
’token_key’: ‘access_token’,
‘remote_app’: {
‘base_url’: ‘https://www.base_url.com‘,
‘request_token_params’: {
‘scope’: ‘email profile’
},
‘request_token_url’: None,
‘access_token_url’: ‘https://www.access_token_url.com’,
‘authorize_url': ‘https://www.authorize_url.com',
‘consumer_key’: ‘PROVIDER_OAUTH_KEY’,
‘consumer_secret’: ‘PROVIDER_OAUTH_SECRET’
}
}
]
Because this is a custom provider (apart from the usual google, facebook, ... providers), in my security manager I have overridden the get_oauth_user_info function that is declared in the flask-appbuilder manager.py
def get_oauth_user_info(self, provider, response=None):
logging.debug("Oauth2 provider: {0}.".format(provider))
me = self.appbuilder.sm.oauth_remotes[provider].get("user")
logging.error(me)
return {
"preferred_username": me.data.get("preferred_username",""),
"first_name": me.data.get("given_name", ""),
"last_name": me.data.get("family_name", ""),
"email": me.data.get("email", "")
I expect results the application to be redirected to the keycloak login page, however the following error is thrown on the post request:
DEBUG:flask_oauthlib:Request 'https://...' with 'POST' method
ERROR:flask_appbuilder.security.manager:User info does not have username or email {}
[2019-05-23 12:52:10,130] ERROR in app: Exception on /oauth-authorized/login [GET]
Traceback (most recent call last):
File "/usr/local/lib/python3.6/site-packages/flask/app.py", line 1982, in wsgi_app
response = self.full_dispatch_request()
File "/usr/local/lib/python3.6/site-packages/flask/app.py", line 1614, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/usr/local/lib/python3.6/site-packages/flask/app.py", line 1517, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/usr/local/lib/python3.6/site-packages/flask/_compat.py", line 33, in reraise
raise value
File "/usr/local/lib/python3.6/site-packages/flask/app.py", line 1612, in full_dispatch_request
rv = self.dispatch_request()
File "/usr/local/lib/python3.6/site-packages/flask/app.py", line 1598, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/usr/local/lib/python3.6/site-packages/flask_appbuilder/security/views.py", line 519, in oauth_authorized
resp = self.appbuilder.sm.oauth_remotes[provider].authorized_response()
If anyone has some pointers as to what I am doing wrong please could you assist me.
You should add annotation #appbuilder.sm.oauth_user_info_getter to the get_oauth_user_info func like in the docs https://flask-appbuilder.readthedocs.io/en/latest/security.html#authentication-oauth
Also change
me = self.appbuilder.sm.oauth_remotes[provider].get("user")
to
me = self.appbuilder.sm.oauth_remotes[provider].get("userinfo")
in case if base_url is like https://{keycloak-domain}/auth/realms/{realm}/protocol/openid-connect/

TemplateDoesNotExist at /music/1/favourite/ music/details.html

I am new to Django and i am using it's version 2.0.7. I have already created template named as details.html but it's still not showing
The video tutorial which i am referring is https://www.youtube.com/watch?v=qgGIqRFvFFk&list=PL6gx4Cwl9DGBlmzzFcLgDhKTTfNLfX1IK&index=24
The error which I got is this
Environment:
Request Method: POST
Request URL: http://127.0.0.1:8000/music/1/favourite/
Django Version: 2.0.7
Python Version: 3.6.6
Installed Applications:
['music.apps.MusicConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware']
Template loader postmortem
Django tried loading these templates, in this order:
Using engine django:
* django.template.loaders.app_directories.Loader: C:\Users\Adesh\Desktop\website\music\templates\music\details.html (Source does not exist)
* django.template.loaders.app_directories.Loader: C:\Users\Adesh\AppData\Local\Programs\Python\Python36\lib\site-packages\django\contrib\admin\templates\music\details.html (Source does not exist)
* django.template.loaders.app_directories.Loader: C:\Users\Adesh\AppData\Local\Programs\Python\Python36\lib\site-packages\django\contrib\auth\templates\music\details.html (Source does not exist)
Traceback:
File "C:\Users\Adesh\AppData\Local\Programs\Python\Python36\lib\site-packages\django\utils\datastructures.py" in __getitem__
77. list_ = super().__getitem__(key)
During handling of the above exception ('song'), another exception occurred:
File "C:\Users\Adesh\Desktop\website\music\views.py" in favourite
22. selected_song = album.song_set.get(pk=request.POST['song'])
File "C:\Users\Adesh\AppData\Local\Programs\Python\Python36\lib\site-packages\django\utils\datastructures.py" in __getitem__
79. raise MultiValueDictKeyError(key)
During handling of the above exception ('song'), another exception occurred:
File "C:\Users\Adesh\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\handlers\exception.py" in inner
35. response = get_response(request)
File "C:\Users\Adesh\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\handlers\base.py" in _get_response
128. response = self.process_exception_by_middleware(e, request)
File "C:\Users\Adesh\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\handlers\base.py" in _get_response
126. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\Adesh\Desktop\website\music\views.py" in favourite
26. 'error_message':"You did not select a valid song",
File "C:\Users\Adesh\AppData\Local\Programs\Python\Python36\lib\site-packages\django\shortcuts.py" in render
36. content = loader.render_to_string(template_name, context, request, using=using)
File "C:\Users\Adesh\AppData\Local\Programs\Python\Python36\lib\site-packages\django\template\loader.py" in render_to_string
61. template = get_template(template_name, using=using)
File "C:\Users\Adesh\AppData\Local\Programs\Python\Python36\lib\site-packages\django\template\loader.py" in get_template
19. raise TemplateDoesNotExist(template_name, chain=chain)
Exception Type: TemplateDoesNotExist at /music/1/favourite/
Exception Value: music/details.html
My template is as follows named as details.html
<img src="{{ album.album_logo}}">
<h1>{{ album.album_title }}</h1>
<h2>{{ album.artist }}</h2>
{% if error_message %}
<p><strong>{{ error_message }}</strong></p>
{% endif %}
<form action="{% url 'music:favourite' album.id %}" method="post" >
{% csrf_token %}
{% for song in album.song_set.all %}
<input type="radio" id="song{{ forloop.counter }}" name="song"
value="{{ song.id }}">
<label for="song {{ forloop.counter }}">
{{ song.song_title }}
{% if song.is_favourite %}
<img src="random_image.png"/>
{% endif %}
</label><br>
{% endfor %}
<input tye="submit" value="Favourite">
</form>
Check your template folders in the settings, in this part of the error you can see Django can't find the template:
Using engine django:
* django.template.loaders.app_directories.Loader: C:\Users\Adesh\Desktop\website\music\templates\music\details.html (Source does not exist)
* django.template.loaders.app_directories.Loader: C:\Users\Adesh\AppData\Local\Programs\Python\Python36\lib\site-packages\django\contrib\admin\templates\music\details.html (Source does not exist)
* django.template.loaders.app_directories.Loader: C:\Users\Adesh\AppData\Local\Programs\Python\Python36\lib\site-packages\django\contrib\auth\templates\music\details.html (Source does not exist)
These are the directories that Django tried to find the template in. The directories that Django looks for are specified in the settings.py file of your project, either this variable: TEMPLATE_DIRS or TEMPLATES has the paths that Django looks for templates.
Either move the template to one of these folders or add the folder where you've saved the template to this variable.
Also see this part of the Django documentation about templates:
https://docs.djangoproject.com/en/2.0/topics/templates/#django.template.backends.base.Template.render
Try to add the path of your "Template" directory on settings.py file. You can check the code block below; I added full path of my template directory to 'DIRS' in TEMPLATES part and it solved my problem.
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [r'C:\Users\Exper\PycharmProjects\Django\Templates'
],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]

Resources