Template in Django not found - django

In the code below, my problem is that template file 'UserAccount' is not found. I set the app in the settings and create a directory in the app and an html file in the directory.
from django.shortcuts import render
# Create your views here.
def login(request):
context = {}
return render(request, 'UserAccount/login.html', context)

this should be your settings.py:
INSTALLED_APPS = [
# django essentials
"django.contrib.admin",
...
# my apps
"myapp", #the app name is "myapp"
]
...
TEMPLATES = [
{
"BACKEND": "django.template.backends.django.DjangoTemplates",
"DIRS": [str(BASE_DIR.joinpath("template"))], # change this line in your settings
"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",
],
},
},
]
now create a directory in the same directory as your apps. sth like this:
myapp
app_two
template
...
now in template directory create another directory with the name of your app. in tha t put your html fiels. like this:
| myapp
| app_two
| template
|----myapp
|----sth.html
|----sth_2.html
|----app_two
now when you want to reference them do it like this:
return render(request, 'myapp/sth.html', context)
General tips on asking question on Stackoverflow:
for title : a summary of your problem with keywords like "django" or "django-views"
for putting your code use three backticks --> code
search a lot before asking question. there is a huge chance that someone had posted the same problem before you and you can find your answer there

Related

Error "ImproperlyConfigured at /dj-rest-auth/login/" in use "dj_rest_auth"

I Want Use packeage 'dj_rest_auth' in django-rest-framework for login but get error:
ImproperlyConfigured at /dj-rest-auth/login/
No default throttle rate set for 'dj_rest_auth' scope
In setting.py File:
INSTALLED_APPS = [
...
# 3rd Party
'rest_framework',
'rest_framework.authtoken',
'rest_framework_simplejwt',
'dj_rest_auth',
# local
...
]
REST_USE_JWT = True
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES':[
'rest_framework_simplejwt.authentication.JWTAuthentication',
'dj_rest_auth.jwt_auth.JWTCookieAuthentication',
],
'DEFAULT_PERMISSION_CLASSES':[
'rest_framework.permissions.AllowAny'
],
'DEFAULT_RENDERER_CLASSES':[
'rest_framework.renderers.JSONRenderer'
],
'DEFAULT_THROTTLE_CLASSES':[
'rest_framework.throttling.AnonRateThrottle',
'rest_framework.throttling.UserRateThrottle',
'rest_framework.throttling.ScopedRateThrottle',
],
'DEFAULT_THROTTLE_RATES':{
'anon':'50/hour',
'user':'200/hour',
'register':'5/hour',
'ref_token':'5/minute',
'create_article':'5/minute',
}
}
And url.py:
urlpatterns = [ ... path('dj-rest-auth/',include('dj_rest_auth.urls')), ]
TL;DR
Add this into your settings.py file
'DEFAULT_THROTTLE_RATES': {
'dj_rest_auth': '10000/day',
...
},
or set the throttle_scope within the view to something else like anon.
Experienced the same issue and found this line within the project code
https://github.com/iMerica/dj-rest-auth/blob/4b3a4ce846c1fd358dfb1ff9fa3fdc8120d884f9/dj_rest_auth/views.py#L274
The view sets a custom throttle scope which you would not have configured within the REST_FRAMEWORK section of the settings.py file hence the error. No idea why they would make this change and not document it correctly.

Rendering new custom html templates in existing Django project

I'm not a Django expert but I need to make customizations of this software which is written in Django using the rest framework.
I need to render a custom html template let's say a.html, however when I go to http://localhost:8080/custom/custom/a I get redirected back to different page - not a.html.
This is what I've done so far. I created a new folder in apps called custom:
cvat
apps
custom
templates
custom
_init.py
a.html, b.html, ...
urls.py
apps.py
from django.apps import AppConfig
class CustomConfig(AppConfig):
name = 'cvat.apps.custom'
urls.py
from django.urls import path
from . import views
urlpatterns = [
path('custom/<str:name>', views.CustomView),
]
views.py
from django.shortcuts import render
def CustomView(request, name):
return render(request, 'custom/'+name+'.html')
In addition, I have modified these existing files to add the custom folder that was created in apps:
in urls.py added my url patterns:
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('cvat.apps.engine.urls')),
path('django-rq/', include('django_rq.urls')),
path('custom/', include('cvat.apps.custom.urls')),
]
in base.py added this:
INSTALLED_APPS = [
...
'cvat.apps.custom'
]
Any advice on what I'm doing wrong?
You can try something like this
url can be like this
urlpatterns = [
path('custom/<name>/', views.CustomView),
]
and your view should be like this.
def CustomView(request, name):
return render(request, f'custom/{name}.html')
Hope this will help you.

Cutomize dj_rest_auth Password reset email

I want to send customized emails when a user request a password reset. I am using dj_rest_auth with django. Here is what I have done: 1. Defined a custom serializer that inherits from PasswordResetSerializer of dj_rest_auth
class CustomPasswordResetSerializer(PasswordResetSerializer):
def get_email_options(self):
return {
'html_mail_template_name': 'registration/password_reset_email.html',
}
Then in settings.py pointed to this serializer:
REST_AUTH_SERIALIZERS = {
'LOGIN_SERIALIZER': 'users.serializers.CustomLoginSerializer',
'PASSWORD_RESET_SERIALIZER': 'users.serializers.CustomPasswordResetSerializer',
}
Then configured templates in settings.py
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, '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',
],
},
},
]
Then I created templates folder in project root, created a registration folder inside it and placed password_reset_email.html inside it.
This is what I found as an exact solution formy problem after googling some time,but this is not working for me. What did I miss?
This answer helped me
https://stackoverflow.com/a/70624462/15624533
I just put my files (html or txt) directly to templates folder, and changed 'account/email/password_reset_key' to just 'password_reset_key' in send_mail method.
I faced the same challenge and got the solution from this issue on GitHub. https://github.com/iMerica/dj-rest-auth/issues/9 . It's easier than you think
Create your custom password reset serializer
from dj_rest_auth.serializers import PasswordResetSerializer
class CustomPasswordResetSerializer(PasswordResetSerializer):
def save(self):
request = self.context.get('request')
# Set some values to trigger the send_email method.
opts = {
'use_https': request.is_secure(),
'from_email': 'example#yourdomain.com',
'request': request,
# here I have set my desired template to be used
# don't forget to add your templates directory in settings to be found
'email_template_name': 'password_reset_email.html'
}
opts.update(self.get_email_options())
self.reset_form.save(**opts)
If you only want to customize email parameters nothing more or less, you can ignore overriding save() method and override get_email_options() instead
from dj_rest_auth.serializers import PasswordResetSerializer
class MyPasswordResetSerializer(PasswordResetSerializer):
def get_email_options(self) :
return {
'email_template_name': 'password_reset_email.html'
}
then point to your custom serializer in settings.py
REST_AUTH_SERIALIZERS = {
'PASSWORD_RESET_SERIALIZER': 'path.to.your.CustomPasswordResetSerializer'
}

Override url.html in Django Admin

I have overridden the template url.html(template path: /admin/widgets/url.html) file of Django Admin. Now I need to keep that overridden file in my project folder so that whenever the functionality of url.html file is needed, the admin app should look into the overridden template(present inside the project folder) but not the template from Django Admin templates present inside the site-packages folder.
Here is my settings.py file settings for templates:
TEMPLATES = [
{
"BACKEND": "django.template.backends.django.DjangoTemplates",
"DIRS": [
os.path.join(BASE_DIR, "company", "app2"),
os.path.join(BASE_DIR, "company", "app2", "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",
]
},
}
]
I have placed the overridden file in the following path in my project:
compnay -> app2 -> templates -> admin -> widgets -> url.html
url.html is present in the widgets folder. The changes made in the overridden template aren't being reflected in the Django Admin UI(For example, in the url.html file, I kept target="_blank" attribute inside the anchor tag to open the corresponding link in a new tab. These changes aren't being reflected.). So, I think it's not taking overridden template present inside my project.
What should I do to take the overridden url.html file present in my project folder?
I had same problem. Solution to problem is:
Add 'django.forms' to your INSTALLED_APPS
Add FORM_RENDERER = 'django.forms.renderers.TemplatesSetting' to
your settings.py
Documentation says:
This renderer gives you complete control of how form and widget templates are sourced.

How do I add two applications/pages onto my Django-site?

I have been trying twice now to add a second application onto my Django-site, whereas it results in some kind of errors.
I have followed instructions from youtube which has been of great help but now I am stuck at adding a second page. My first one is working just fine.
This is my main url.py:
from django.conf.urls import url, include
from django.contrib import admin
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^table/', include('table.urls')),
url(r'^', include('login.urls')),
]
This is my main settings.py:
INSTALLED_APPS = [
'login',
'table',
....
TEMPLATES = [
{
'BACKEND': 'django.templates.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.templates.context_processors.debug',
'django.templates.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
This is my working page url.py:
from django.conf.urls import url, include
from . import views
urlpatterns = [
url(r'^$', views.index, name='index'),
]
This is my working page view.py:
from django.shortcuts import render
def index(request):
return render(request,'login/login.html', {'content': ['username',
'password']} )
This is my non-working page url.py:
from django.conf.urls import url, include
from . import views
urlpatterns = [
url(r'^$', views.index, name = 'index'),
]
This is my non-working page view.py:
from django.shortcuts import render
from django.http import HttpResponse
def index(request):
return render(request,'table/table.html')
Thus far I have thought of the index(request) being an issue since they are both having the name "view" and same function name...?
And I have no idea where to look on the "error-page" nor what to show you guys, I'm sorry. And I appreciate any help. Thank you.
"During handling of the above exception ('django'), another exception occurred:
C:\python36\lib\site-packages\django\core\handlers\exception.py in inner
response = get_response(request) ...
▼ Local vars
Variable Value
exc
ModuleNotFoundError("No module named 'django.templates'",)
get_response
>>>
>
request
"
EDIT: I have named all my template-folders templates, always. Though I mistakenly named it without an s while creating it inside the second application but it is changed by refactoring.
I think this is my error now:
Exception Type: ModuleNotFoundError at /
Exception Value: No module named 'django.templates'
The error message is stating you are referring to django.templates somewhere. This module does not exist in django, but django.template does. You can find several django.template.x statements in your settings.py file.
Replace django.templates.x with django.template.x and you are good to go!
In your urls.py, specify the app_name like this:
# ...imports...
app_name = 'tables'
urlpatterns = [
#...
]
The name of the url can then be accessed by your template by tables:index