Error : can't get the urls properly.

Hi,
I started my first project in python-django and like any beginner I’ve been running into an error for 2 days already.
My environment:

asgiref             3.6.0
charset-normalizer  3.1.0
Django              4.2
django-cors-headers 3.14.0
djangorestframework 3.14.0
idna                3.4
mysqlclient         2.1.1
pip                 22.3.1
pytz                2023.3
setuptools          65.5.0
sqlparse            0.4.3
tzdata              2023.3
urllib3             1.26.15

I get this error:

Exception in thread django-main-thread:
Traceback (most recent call last):
  File "C:\Python311\Lib\threading.py", line 1038, in _bootstrap_inner
    self.run()
  File "C:\Python311\Lib\threading.py", line 975, in run
    self._target(*self._args, **self._kwargs)
  File "C:\Python311\Lib\site-packages\django\utils\autoreload.py", line 64, in wrapper
    fn(*args, **kwargs)
  File "C:\Python311\Lib\site-packages\django\core\management\commands\runserver.py", line 133, in inner_run
    self.check(display_num_errors=True)
  File "C:\Python311\Lib\site-packages\django\core\management\base.py", line 485, in check
    all_issues = checks.run_checks(
                 ^^^^^^^^^^^^^^^^^^
  File "C:\Python311\Lib\site-packages\django\core\checks\registry.py", line 88, in run_checks
    new_errors = check(app_configs=app_configs, databases=databases)
                 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Python311\Lib\site-packages\django\core\checks\urls.py", line 14, in check_url_config
    return check_resolver(resolver)
           ^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Python311\Lib\site-packages\django\core\checks\urls.py", line 24, in check_resolver
    return check_method()
           ^^^^^^^^^^^^^^
  File "C:\Python311\Lib\site-packages\django\urls\resolvers.py", line 494, in check
    for pattern in self.url_patterns:
                   ^^^^^^^^^^^^^^^^^
  File "C:\Python311\Lib\site-packages\django\utils\functional.py", line 57, in __get__
    res = instance.__dict__[self.name] = self.func(instance)
                                         ^^^^^^^^^^^^^^^^^^^
  File "C:\Python311\Lib\site-packages\django\urls\resolvers.py", line 715, in url_patterns
    patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
                       ^^^^^^^^^^^^^^^^^^^
  File "C:\Python311\Lib\site-packages\django\utils\functional.py", line 57, in __get__
    res = instance.__dict__[self.name] = self.func(instance)
                                         ^^^^^^^^^^^^^^^^^^^
  File "C:\Python311\Lib\site-packages\django\urls\resolvers.py", line 708, in urlconf_module
    return import_module(self.urlconf_name)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Python311\Lib\importlib\__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "<frozen importlib._bootstrap>", line 1206, in _gcd_import
  File "<frozen importlib._bootstrap>", line 1178, in _find_and_load
  File "<frozen importlib._bootstrap>", line 1149, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 690, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 940, in exec_module
  File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed
  File "C:\Users\rt-enterprises\OneDrive\RTSOFTT\PROJECTS\Python Projects\JT_ORDER-FILES\JT_Order\JT_Order\urls.py", line 22, in <module>
    path(r'^',include('JTOrderApp.urls')),
              ^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Python311\Lib\site-packages\django\urls\conf.py", line 38, in include
    urlconf_module = import_module(urlconf_module)
                     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Python311\Lib\importlib\__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "<frozen importlib._bootstrap>", line 1206, in _gcd_import
  File "<frozen importlib._bootstrap>", line 1178, in _find_and_load
  File "<frozen importlib._bootstrap>", line 1149, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 690, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 940, in exec_module
  File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed
  File "C:\Users\rt-enterprises\OneDrive\RTSOFTT\PROJECTS\Python Projects\JT_ORDER-FILES\JT_Order\JTOrderApp\urls.py", line 4, in <module>
    from .views import companyApi
  File "C:\Users\rt-enterprises\OneDrive\RTSOFTT\PROJECTS\Python Projects\JT_ORDER-FILES\JT_Order\JTOrderApp\views.py", line 6, in <module>
    from JTOrderApp import Companies, Supplies, Drivers, Camions, Products, Measures, Orders
ImportError: cannot import name 'Companies' from 'JTOrderApp' (C:\Users\rt-enterprises\OneDrive\RTSOFTT\PROJECTS\Python Projects\JT_ORDER-FILES\JT_Order\JTOrderApp\__init__.py)

Here is my urls.py file

from django.urls import path
from JTOrderApp import views
urlpattern=[
    path(r'^company$', views.companyApi),
    path(r'^company/([0-9]+)$',views.companyApi)
]

and JTOrderApp.urls.py

from django.contrib import admin
from django.urls import path,include
urlpatterns = [
    path('admin/', admin.site.urls),
    path(r'^',include('JTOrderApp.urls')),
]

my views.py file

@csrf_exempt
def companyApi(request, id=0):
    if request.method=='GET':
        companies = Companies.objects.all()
        companies_serializer=CompanySerializers(companies,many=True)
        return JsonResponse(companies_serializer.data,safe=False)
    elif request.method=='POST':
        company_data=JSONParser().parse(request)
        companies_serializer=CompanySerializers(data=company_data)
        if companies_serializer.is_valid():
            companies_serializer.save()
            return JsonResponse("Ajouté avec succès",safe=False)
        return JsonResponse("Erreur d'ajout",safe=False)
    elif request.method=='PUT':
        company_data=JSONParser().parse(request)
        company = Companies.objects.get(CompanyId=company_data['CompanyId'])
        companies_serializer=CompanySerializers(company,data=company_data)
        if companies_serializer.is_valid():
            companies_serializer.save()
            return JsonResponse("Mise à jour avec succès",safe=False)
        return JsonResponse("Erreur de mise jour",safe=False)               
    elif request.method=='DELETE':
        company = Companies.objects.get(CompanyId=id)
        company.delete()
        return JsonResponse("Elément supprimé avec succès",safe=False)

and finally my setting.py file :

INSTALLED_APPS = [
    # 'JTOrderApp.apps.JtorderappConfig',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'rest_framework',
    'corsheaders',
    'JTOrderApp',
]

What is the cause of the error please.
Thanks in advance.

Side note: When posting code, templates, traceback messages, etc, enclose the text between lines of three backtick - ` characters. This means you’ll have a line of ```, then your code or text, then another line of ```. This forces the forum software to keep that text properly formatted. (I’ve taken the liberty of making that change above.)

The first issue is that the path function does not take/use regexes. If you want a regex as a url specification, you need to use the re_path function.

The second problem is that you have:

in your `JTOrderApp.urls file - which means you’re trying to include the current file - that’s not going to work.

I suggest you review the docs at URL dispatcher | Django documentation | Django

I read the documentation and I had tried changing the path function to re_path but nothing it was the same error.
In view of my code, what would you suggest me to do please?

See my comment about the second problem in the code - trying to import a file in itself.

Also, you mentioned that this is your first Django project. Have you worked your way through either or both of the Official Django Tutorial and the Django Girls Tutorial? They both cover the structure of a urls.py file.

@KenWhitesell, I actually got closer to the documentation, got it and tried to create another project based on another learning tutorial, but the result is the same at this level I get the same error. Although I tried different approach.

It’s really difficult to try and diagnose problems like this without seeing the code you’re trying to refer to or the specific error message and traceback.

OK I understand. Could you refer me a link or a tutorial from which I could learn django 4.2 and set up a project from crash.
Thank in advance.

I always recommend people start from either or both of the Official Django Tutorial and the Django Girls Tutorial.

I found the solution to my problem.
First I changed

  • JTOrderApp.urls.py
from django.urls import re_path
from JTOrderApp import views
urlpattern=[
    re_path(r'^company$', views.companyApi),
    re_path(r'^company/([0-9]+)$',views.companyApi)
]
  • my urls.py file also:
from django.contrib import admin
from django.urls import path,re_path,include
urlpatterns = [
    path('admin/', admin.site.urls),
    re_path(r'^',include('JTOrderApp.urls')),
]

So where I use r’^', I take re_path instead of path to avoid errors.

Second, and this is where I had my problem; my models import was not good in my serializers.py file, I changed from JTOrderApp import Companies to from JTOrderApp.models import Companies (rookie mistake, be careful when import).
Now everything is fine, I thank you all for your interventions which helped me to find my solution.