Skip to content
Advertisement

How to fix TemplatesDoesNotExist error even after BASE_DIR has been Joined with templates in settings.py?

Image 1- Error

I notice Exception Value: registration/login.html , I don’t even have that in the templates, instead, i have sign-in.html, I have no idea why it mentioned login.html. Please see my templates folder below as image 3-Templates.

enter image description here

  1. I’m trying to fix the above error. My project path looks like

Image 2- project path

enter image description here

Image 3- Templates

enter image description here

  1. The image 2 above shows that my templates folder is located in foodtaskerapp folder
  2. In the settings.py I have added 'DIRS': [os.path.join(BASE_DIR, 'templates')], in the TEMPLATES section.
  3. I think there is an error because before we can get to templates from BASE_DIR we need to pass through the foodtaskerapp. This leads me to the following step
  4. In the settings.py I tried 'DIRS': [os.path.join(BASE_DIR, 'foodtaskerapp','templates')], to replace step 2
  5. After the above step, I also tried 'DIRS': [os.path.join(BASE_DIR, 'foodtaskerapp\templates')], . I had use two slashes here because when i used the print command from the interactive console i saw the path was given in that format.
  6. I have also tried move my templates folder from the foodtaskerapp to the root folder and I checked like below to confirm if I’m in the right path:
from django.conf import settings

print(settings.TEMPLATES)

Then I got

'DIRS': ['C:\Users\simple_tech\Desktop\foodtasker-master\foodtasker-master\templates']

The above shows I’m on the right path.

But I still got the error “TemplatesDoesNotExist” whenever I clicked on the server URL after running

python manage.py runserver

For further investigation, bellow is my

URLS.PY

from django.conf.urls import url, include
        from django.contrib import admin
        from django.contrib.auth import views as auth_views
        from django.conf.urls.static import static
        from django.conf import settings
        from foodtaskerapp import views, apis
        
        urlpatterns = [
            url(r'^admin/', admin.site.urls),
            url(r'^$', views.home, name='home'),
            url(r'^restaurant/sign-in/$', auth_views.LoginView.as_view(), {'template_name': 'restaurant/sign_in.html'}, name = 'restaurant-sign-in'),
            url(r'^restaurant/sign-out', auth_views.LogoutView.as_view(), {'next_page': '/'}, name = 'restaurant-sign-out'),
            url(r'^restaurant/sign-up', views.restaurant_sign_up, name = 'restaurant-sign-up'),
            url(r'^restaurant/$', views.restaurant_home, name = 'restaurant-home'),
            url(r'^restaurant/account/$', views.restaurant_account, name = 'restaurant-account'),
            url(r'^restaurant/meal/$', views.restaurant_meal, name = 'restaurant-meal'),
            url(r'^restaurant/meal/add/$', views.restaurant_add_meal, name = 'restaurant-add-meal'),
            url(r'^restaurant/meal/edit/(?P<meal_id>d+)/$', views.restaurant_edit_meal, name = 'restaurant-edit-meal'),
            url(r'^restaurant/order/$', views.restaurant_order, name = 'restaurant-order'),
            url(r'^restaurant/report/$', views.restaurant_report, name = 'restaurant-report'),
        
            # Sign In/ Sign Up/ Sign Out
            url(r'^api/social/', include('rest_framework_social_oauth2.urls')),
            # /convert-token (sign in/ sign up)
            # /revoke-token (sign out)
            url(r'^api/restaurant/order/notification/(?P<last_request_time>.+)/$', apis.restaurant_order_notification),
            # APIs for CUSTOMERS
            url(r'^api/customer/restaurants/$', apis.customer_get_restaurants),
            url(r'^api/customer/meals/(?P<restaurant_id>d+)/$', apis.customer_get_meals),
            url(r'^api/customer/order/add/$', apis.customer_add_order),
            url(r'^api/customer/order/latest/$', apis.customer_get_latest_order),
            url(r'^api/customer/driver/location/$', apis.customer_driver_location),
        
            # APIs for DRIVERS
            url(r'^api/driver/orders/ready/$', apis.driver_get_ready_orders),
            url(r'^api/driver/order/pick/$', apis.driver_pick_order),
            url(r'^api/driver/order/latest/$', apis.driver_get_latest_order),
            url(r'^api/driver/order/complete/$', apis.driver_complete_order),
            url(r'^api/driver/revenue/$', apis.driver_get_revenue),
            url(r'^api/driver/location/update/$', apis.driver_update_location),
        
            ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
**views.py** 
    from django.shortcuts import render, redirect
    from django.contrib.auth.decorators import login_required
    from foodtaskerapp.forms import UserForm, RestaurantForm, UserFormForEdit, MealForm
    from django.contrib.auth import authenticate, login
    
    from django.contrib.auth.models import User
    from foodtaskerapp.models import Meal, Order, Driver
    
    from django.db.models import Sum, Count, Case, When
    
    
    def home(request):
        return redirect(restaurant_home)
    
    
    @login_required(login_url='/restaurant/sign-in/')
    def restaurant_home(request):
        return redirect(restaurant_order)
    
    
    @login_required(login_url='/restaurant/sign-in/')
    def restaurant_account(request):
        user_form = UserFormForEdit(instance=request.user)
        restaurant_form = RestaurantForm(instance=request.user.restaurant)
    
        if request.method == "POST":
            user_form = UserFormForEdit(request.POST, instance=request.user)
            restaurant_form = RestaurantForm(request.POST, request.FILES, instance=request.user.restaurant)
    
            if user_form.is_valid() and restaurant_form.is_valid():
                user_form.save()
                restaurant_form.save()
    
        return render(request, 'restaurant/account.html', {
            "user_form": user_form,
            "restaurant_form": restaurant_form
        })
    
    
    @login_required(login_url='/restaurant/sign-in/')
    def restaurant_meal(request):
        meals = Meal.objects.filter(restaurant=request.user.restaurant).order_by("-id")
        return render(request, 'restaurant/meal.html', {"meals": meals})
    
    
    @login_required(login_url='/restaurant/sign-in/')
    def restaurant_add_meal(request):
        form = MealForm()
    
        if request.method == "POST":
            form = MealForm(request.POST, request.FILES)
    
            if form.is_valid():
                meal = form.save(commit=False)
                meal.restaurant = request.user.restaurant
                meal.save()
                return redirect(restaurant_meal)
    
        return render(request, 'restaurant/add_meal.html', {
            "form": form
        })
    
    
    @login_required(login_url='/restaurant/sign-in/')
    def restaurant_edit_meal(request, meal_id):
        form = MealForm(instance=Meal.objects.get(id=meal_id))
    
        if request.method == "POST":
            form = MealForm(request.POST, request.FILES, instance=Meal.objects.get(id=meal_id))
    
            if form.is_valid():
                form.save()
                return redirect(restaurant_meal)
    
        return render(request, 'restaurant/edit_meal.html', {
            "form": form
        })
    
    
    @login_required(login_url='/restaurant/sign-in/')
    def restaurant_order(request):
        if request.method == "POST":
            order = Order.objects.get(id=request.POST["id"], restaurant=request.user.restaurant)
    
            if order.status == Order.COOKING:
                order.status = Order.READY
                order.save()
    
        orders = Order.objects.filter(restaurant=request.user.restaurant).order_by("-id")
        return render(request, 'restaurant/order.html', {"orders": orders})
    
    
    @login_required(login_url='/restaurant/sign-in/')
    def restaurant_report(request):
        # Calculate revenue and number of order by current week
        from datetime import datetime, timedelta
    
        revenue = []
        orders = []
    
        # Calculate weekdays
        today = datetime.now()
        current_weekdays = [today + timedelta(days=i) for i in range(0 - today.weekday(), 7 - today.weekday())]
    
        for day in current_weekdays:
            delivered_orders = Order.objects.filter(
                restaurant=request.user.restaurant,
                status=Order.DELIVERED,
                created_at__year=day.year,
                created_at__month=day.month,
                created_at__day=day.day
            )
            revenue.append(sum(order.total for order in delivered_orders))
            orders.append(delivered_orders.count())
    
        # Top 3 Meals
        top3_meals = Meal.objects.filter(restaurant=request.user.restaurant) 
                         .annotate(total_order=Sum('orderdetails__quantity')) 
                         .order_by("-total_order")[:3]
    
        meal = {
            "labels": [meal.name for meal in top3_meals],
            "data": [meal.total_order or 0 for meal in top3_meals]
        }
    
        # Top 3 Drivers
        top3_drivers = Driver.objects.annotate(
            total_order=Count(
                Case(
                    When(order__restaurant=request.user.restaurant, then=1)
                )
            )
        ).order_by("-total_order")[:3]
    
        driver = {
            "labels": [driver.user.get_full_name() for driver in top3_drivers],
            "data": [driver.total_order for driver in top3_drivers]
        }
    
        return render(request, 'restaurant/report.html', {
            "revenue": revenue,
            "orders": orders,
            "meal": meal,
            "driver": driver
        })
    
    
    def restaurant_sign_up(request):
        user_form = UserForm()
        restaurant_form = RestaurantForm()
    
        if request.method == "POST":
            user_form = UserForm(request.POST)
            restaurant_form = RestaurantForm(request.POST, request.FILES)
    
            if user_form.is_valid() and restaurant_form.is_valid():
                new_user = User.objects.create_user(**user_form.cleaned_data)
                new_restaurant = restaurant_form.save(commit=False)
                new_restaurant.user = new_user
                new_restaurant.save()
    
                login(request, authenticate(
                    username=user_form.cleaned_data["username"],
                    password=user_form.cleaned_data["password"]
                ))
    
                return redirect(restaurant_home)
    
        return render(request, "restaurant/sign_up.html", {
            "user_form": user_form,
            "restaurant_form": restaurant_form
        })
**model.py** 
    from django.db import models
    from django.contrib.auth.models import User
    from django.utils import timezone
    
    class Restaurant(models.Model):
        user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='restaurant')
        name = models.CharField(max_length=500)
        phone = models.CharField(max_length=500)
        address = models.CharField(max_length=500)
        logo = models.ImageField(upload_to='restaurant_logo/', blank=False)
    
        def __str__(self):
            return self.name
    
    class Customer(models.Model):
        user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='customer')
        avatar = models.CharField(max_length=500)
        phone = models.CharField(max_length=500, blank=True)
        address = models.CharField(max_length=500, blank=True)
    
        def __str__(self):
            return self.user.get_full_name()
    
    class Driver(models.Model):
        user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='driver')
        avatar = models.CharField(max_length=500)
        phone = models.CharField(max_length=500, blank=True)
        address = models.CharField(max_length=500, blank=True)
        location = models.CharField(max_length=500, blank=True)
    
        def __str__(self):
            return self.user.get_full_name()
    
    class Meal(models.Model):
        restaurant = models.ForeignKey(Restaurant, on_delete=models.CASCADE, related_name='meal')
        name = models.CharField(max_length=500)
        short_description = models.CharField(max_length=500)
        image = models.ImageField(upload_to='meal_images/', blank=False)
        price = models.IntegerField(default=0)
    
        def __str__(self):
            return self.name
    
    class Order(models.Model):
        COOKING = 1
        READY = 2
        ONTHEWAY = 3
        DELIVERED = 4
    
        STATUS_CHOICES = (
            (COOKING, "Cooking"),
            (READY, "Ready"),
            (ONTHEWAY, "On the way"),
            (DELIVERED, "Delivered"),
        )
    
        customer = models.ForeignKey(Customer, on_delete=models.DO_NOTHING)
        restaurant = models.ForeignKey(Restaurant, on_delete=models.DO_NOTHING)
        driver = models.ForeignKey(Driver, on_delete=models.DO_NOTHING, blank = True, null = True)
        address = models.CharField(max_length=500)
        total = models.IntegerField()
        status = models.IntegerField(choices = STATUS_CHOICES)
        created_at = models.DateTimeField(default = timezone.now)
        picked_at = models.DateTimeField(blank = True, null = True)
    
        def __str__(self):
            return str(self.id)
    
    class OrderDetails(models.Model):
        order = models.ForeignKey(Order, on_delete=models.DO_NOTHING, related_name='order_details')
        meal = models.ForeignKey(Meal, on_delete=models.DO_NOTHING)
        quantity = models.IntegerField()
        sub_total = models.IntegerField()
    
        def __str__(self):
            return str(self.id)

Please help!

Thanks for your time.

Advertisement

Answer

Django does not have a “default” login.html template . see more here

the login view uses the registration/login.html template just like ny other app in your project, third apps or in this case, a contrib (builtin) app.. you need to crate templates inside a known path. In this case path = registration/login.html

All you have todo is, create in your templates root dir, another dir with name registration and the, inside it, a template file called login.html

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement