Categories
Python Answers

How to fix Python Django TemplateDoesNotExist error?

To fix Python Django TemplateDoesNotExist error, we can register the template directories in our app.

For instance, in settings.py, we add

TEMPLATE_DIRS = (
    os.path.join(SETTINGS_PATH, 'templates'),
)

to register the templates directory as the directory with the templates.

Categories
Python Answers

How to send email via Python Django?

To send email via Python Django, we can use the EmailMesage class.

For instance, we write

EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_USE_TLS = True
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_HOST_USER = 'youremail@gmail.com'
EMAIL_HOST_PASSWORD = 'email_password'
EMAIL_PORT = 587

to add our email settings in settings.py.

Then we write

from django.core.mail import EmailMessage

email = EmailMessage('Subject', 'Body', to=['your@email.com'])
email.send()

to create an EmailMessage object with the subject, body and to emails.

And then we call send to send the email.

Categories
Python Answers

How to return redirect() with parameters with Python Django?

To return redirect() with parameters with Python Django, we can call redirect.

For instance, given that we have

url(r'element/update/(?P<pk>\d+)/$', 'element.views.element_update', name='element_update'),

in urls.py, we write

from django.shortcuts import redirect
from .models import Element


def element_info(request):
    # ...
    element = Element.object.get(pk=1)
    return redirect('element_update', pk=element.id)

def element_update(request, pk)
    # ...

in views.py to redirect to the view with name element_update in the element_info view.

The pk argument is value of the pk URL parameter.

Categories
Python Answers

How to redirect user to his custom page after login with Python Django?

To redirect user to his custom page after login with Python Django, we can use the HttpResponseRedirect class.

For instance, we write

from django.http import HttpResponseRedirect
from django.urls import reverse
from django.contrib.auth.decorators import login_required

@login_required
def home(request):
    return HttpResponseRedirect(
               reverse(NAME_OF_PROFILE_VIEW, 
                       args=[request.user.username]))

to create the HttpResponseRedirect object with the path of the view that we get from

reverse(NAME_OF_PROFILE_VIEW, args=[request.user.username])

The args argument has the URL parameters.

Categories
Python Answers

How to get model from string with Python Django?

To get model from string with Python Django, we can use the get_model function.

For instance, we write

from django.apps import apps

model = apps.get_model('app_name', 'model_name')

to call apps.get_model with the app name and model name as arguments to get the model.