Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Websocket not working with django on deployment
i hope that u can help me. I deployed my django application to an ubuntu 20.04 server with nginx and gunicorn. This is my settings: gunicorn.service [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=ubuntu Group=www-data WorkingDirectory=/var/www/PlugSell ExecStart=/var/www/PlugSell/env/bin/gunicorn --access-logfile - --error-logfile - -k uvicorn.workers.UvicornWorker --workers 3 --bind unix:/run/gunicorn.sock minible.asgi:application [Install] WantedBy=multi-user.target app nginx conf server { server_name 3.73.206.145 127.0.0.1 sell.plug-shop.com; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /var/www/PlugSell; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } location /ws/ { proxy_set_header Host $http_host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Host $server_name; proxy_set_header X-Forwarded-Proto $scheme; proxy_set_header X-Url-Scheme $scheme; proxy_redirect off; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection $connection_upgrade; proxy_pass http://unix:/run/gunicorn.sock; } listen 443 ssl; # managed by Certbot ssl_certificate /etc/letsencrypt/live/sell.plug-shop.com/fullchain.pem; # managed by Certbot ssl_certificate_key /etc/letsencrypt/live/sell.plug-shop.com/privkey.pem; # managed by Certbot include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot } server { if ($host = sell.plug-shop.com) { return 301 https://$host$request_uri; } # managed by Certbot listen 80; server_name 3.73.206.145 127.0.0.1 sell.plug-shop.com; return 404; # managed by Certbot } in settings.py i have CHANNEL_LAYERS = { "default": { "BACKEND": "channels_redis.core.RedisChannelLayer", "CONFIG": { "hosts": [("127.0.0.1", 6379)], }, }, } and in my asgi.py os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'minible.settings') … -
Customize django behavior on requests from mobile app and any sort of web browser
Good day, So I have made a mobile Android/IOS app that communicates with django backend through the http requests. As you understand the backend is hosted on some https://www.example.com domain... However, in case a user accesses that domain or any extensions (/home, /profile and etc..) from any web browser from any platform, I want to display just a plain page (maybe the name of the app). How can I do so? Thanks -
NOT NULL constraint failed: new__BRS_user.tables_id
When i'm trying to migrate the User model, NOT NULL constraint failed: new__BRS_user.tables_id error appears There is no field named tables in my model, i'm removed it long ago. class User(Model): id = models.AutoField(primary_key=True) first_name = models.CharField(max_length=60) second_name = models.CharField(max_length=60) third_name = models.CharField(max_length=60) email = models.CharField(max_length=320, unique=True) password = models.CharField(max_length=127) is_admin = models.BooleanField(default=False) is_student = models.BooleanField(default=True) is_teacher = models.BooleanField(default=False) input = models.OneToOneField(Input, on_delete=models.CASCADE, null=True) Class = models.IntegerField() -
AttributeError in Django Overlapping validation checking
i am cretaing a validation rule in djano to check overlapping but i am getting this error, can you guys help me there is two data field , when the data field will be overlapped than validation error will rise. start_r= model.integerfield(blank=True, Null=True) end_t=model.intergerfield(blank=True,Null=True) form.py class CheckForm(forms.ModelForm): def clean(self): start_r = cleaned_data.get("start_r",[]) end_t =cleaned_data.get("end_t",[]) if (start_r.end >= end_t.start) and (start_r.start <= end_t.end): raise ValidationError("Overlap not allowed.") i am getting error this one 'NoneType' object has no attribute 'end' -
Django + Vue google maps
I have a django + vue (for learn) project. I'm trying to implement google maps. I installed django-location-field and Google Vue 3 maps. For example, the output from the django location field is 51.39772199999999,16.2095788 and Google Vue 3 maps require input like this {lat: 51.093048, lng: 6.842120}, I don't really know how to write it in js. I know you have to use the split(",") option but I could use a little help from you. I'd like to split input from django and assign to two variables and do something like this center: {lat: value1, lng: value2}, this is my code <template> <section class="portfolio-block projects-cards"> <div class="container"> <div class="heading"> <h2>{{ firma.nazwa_firmy }}</h2> </div> <div class="row"> <p>{{ firma.opis }}</p> <p>{{ firma.strona_www}}</p> <p>{{ firma.miasto}}</p> <GoogleMap api-key="myapikey:)" style="width: 100%; height: 500px" :center="center" :zoom="15"> <Marker :options="{ position: center }" /> </GoogleMap> <p>{{ delta }}</p> </div> </div> </section> </template> <script> import axios from 'axios' import { GoogleMap, Marker } from "vue3-google-map"; export default { name: 'FirmaDetails', setup() { const center = { lat: 40.689247, lng: -74.044502 }; return { center }; // Get toast interface // const toast = useToast(); // return { toast } }, data() { return { firma: [], lokali: [], errors: … -
unrecognized arguments: --username appuser when When I try to run the createsuperuser command
My code class UserManager(BaseUserManager): use_in_migrations = True def _create_user(self, email, password, **extra_fields): if not email: raise ValueError("email field is required") email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_user(self, email, password, **extra_fields): extra_fields.setdefault("is_staff", False) extra_fields.setdefault("is_superuser", False) return self._create_user(email, password, **extra_fields) def create_superuser(self, email, password, **extra_fields): extra_fields.setdefault("is_staff", True) extra_fields.setdefault("is_superuser", True) extra_fields.setdefault("username", None) if extra_fields.get("is_staff") is not True: raise ValueError("Superuser must have is_staff=True") if extra_fields.get("is_superuser") is not True: raise ValueError("Superuser must have is_superuser=True") return self._create_user(email, password, **extra_fields) class User(AbstractUser): username = "user" email = models.EmailField('email adress', unique=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] class Meta: db_table = "USER" Note that my user must only authenticate with his email and password. Terminal outpout usage: manage.py createsuperuser [-h] [--email EMAIL] [--noinput] [--database DATABASE] [--version] [-v {0,1,2,3}] [--settings SETTINGS] [--pythonpath PYTHONPATH] [--traceback] [--no-color] [--force-color] [--skip-checks] manage.py createsuperuser: error: unrecognized arguments: --username appuser -
How to get the sum of transactions per month in django
I'm building a transaction application and need to display the data in charts using chart.js. I don't know how to get the sum for each month of the year. my model class Transaction(models.Model): trans_id = models.CharField(max_length=100, primary_key=True) trans_date = models.DateTimeField(auto_now_add=True) group_id = models.ForeignKey('Group', on_delete=models.CASCADE) username = models.ForeignKey(User, on_delete=models.CASCADE) trans_amount = models.FloatField() trans_type = models.CharField(max_length=20, default="contribution") def __str__(self): return str(self.trans_id) How can I get the sum totals? -
Duplicating checkbox in Django template
I'm building a web app and I went through something I'm unable to fix: in my app, I have a list of movies, and each movie has a little checkbox that shows the users if he has seen or not the mentioned movie. Everything works fine, every user can flag/unflag their movies. The problem begins when the user flags more than one movie: if one/none movie is flagged, everything works fine, when the user flags more than 2 movies, the checkboxes begin to duplicate, so that if I have 5 movies flagged, I'll have 5 checkboxes for each movie. I know where is the problem, but I don't really know how to fix it. Really, I spent over 2 days thinking about a possible solution, but I don't get it. Hope you will help me! <form action="" method="POST"> {% csrf_token %} <div class="row"> {% for film in films %} ... {% if user.seen.all %} {% for film2 in user.seen.all %} <input class="form-check-input" type="checkbox" id="check_seen" name="check_seen" value="{{film.pk}}" {% if film2.name == film.name %}checked{% endif %}> {% endfor %} {% elif not user.seen.all %} <input class="form-check-input" type="checkbox" id="check_seen" name="check_seen" value="{{film.pk}}"> {% endif %} (little save button)... </form> Essentially, what is happening here … -
Django constraints for UniqueConstraint does not work
I have tried to implement constraints for UniqueConstraint for two foreign keys in the Django model. So far it has not been working as expected. Here below is the model definition : class AssetMember(models.Model): asset = models.ForeignKey(Asset, null=True, related_name='assetmember_asset', on_delete=models.CASCADE) project = models.ForeignKey(Project, null=True, related_name='assetmember_project', on_delete=models.DO_NOTHING) class Meta: constraints = [ models.UniqueConstraint(fields=["asset", "project"], name="assetmember_unique_object") ] Yet, when I try to create two assetmember objects with the same asset and project as foreign key, I can see that the constraints are not working as expected : How shall I implement the model and the UniqueConstraint, so that it will not create the same object with asset and project twice? -
Error websocket djangochannelsrestframework
I did websocket connection by djangochannelsrestframework library, it connects but when I send some message it gets this error below Error image -
django test case setUp - queryset not updating
I'm experiencing issues trying to update a queryset on setUp: class MyTestCase(BaseTestCase): OPERATOR_USERNAME = "test_operator" OPERATOR_PASSWORD = "secret" OPERATOR_EMAIL = "test@example.org" @classmethod def setUpClass(cls): super().setUpClass() cls.operator = Operator.objects.create_superuser( username=cls.OPERATOR_USERNAME, password=cls.OPERATOR_PASSWORD, email=cls.OPERATOR_EMAIL ) def setUp(self) -> None: self.client.login(username=self.OPERATOR_USERNAME, password=self.OPERATOR_PASSWORD) utd_ids = MyModel.objects.filter( ref_year=2021).values_list("id", flat=True )[:10] utd_qs = MyModel.objects.filter(id__in=utd_ids) # just added another step for debugging purposes # update initial utd status _updates = utd_qs.update(status="INITIAL_STATE_VALUE") print(_updates) # it prints 10 self.ssn_list = list(utd_qs.values_list("user__ssn", flat=True)) self.client.login(username=self.OPERATOR_USERNAME, password=self.OPERATOR_PASSWORD) print(MyModel.objects.filter(id__in=utd_ids).values("status").distinct()) # this should retrieve 1 value but instead it retrieve multiple values different from INITIAL_STATE_VALUE am I doing something wrong? I tried the same update through python manage.py shell on a similar queryset and it works as expected -
Trying to set a minimum value within a form based on the total amount in the inventory
Views.py ( Where I want to check) def addInProcess(request): if request.user.is_authenticated: form = inProcess_form() if request.method =="POST": calc = InProcessPowder.objects.create( date = request.POST.get('date'), tc_date = request.POST.get('tc_date'), tc_weight = request.POST.get('tc_weight'), tc_remarks = request.POST.get('tc_remarks'), tgl_date = request.POST.get('tgl_date'), tgl_weight = request.POST.get('tgl_weight'), tgl_remarks = request.POST.get('tgl_remarks'), checked_by = request.user, ) context = {'form': form} return render(request, 'base/InProcess/InProcess_form.html', context) else: return render (request, 'landing.html') and in our Home view we call this as the total inventory amount def home(request): if request.user.is_authenticated: totalCal_yld = calamansi.objects.all().aggregate(Sum('yld')) ['yld__sum']or 0.00 This gets the total yield of calamansi juice from the calamansi object I want to compare tc_weight with totalCal_yld What I am trying to do is I want to minues tc_weight(processes calamansi) from totalCal_yld and equal a total which will represent the inventory of calamansi. Since calamansi is an ingredient in TC we are trying to make sure that it wont go negative or even not give them the option to do so. Help is very much appreciated -
JSON.parse: unexpected character at line 1 column 1 of the JSON data(django)
i was making an ecommerce website using django & trying to send data using fetch in javascript but this message is keep showing up. tried 100 times to figure out what's the issue but can't find one. i'm new btw total = total bill ship = True means, shipping is necesarry bcz the product is not digital. form is a form where the user added their info var userFormData = { "name": "null", "email": "null", "total": total, }; var shippingFormData = { "address": null, "city": null, "zipcode": null, "state": null, }; if (user == "AnnonymousUser") { userFormData.name = form.name.value; userFormData.email = form.email.value; } if (ship == "True") { shippingFormData.address = form.address.value; shippingFormData.city = form.city.value; shippingFormData.zipcode = form.zipcode.value; shippingFormData.state = form.state.value; } console.log(userFormData); console.log(shippingFormData); var url = "/checkout_info_process/"; fetch(url, { method: "POST", headers: { "Content-Type": "application/json", "X-CSRFToken": csrftoken, }, body:JSON.stringify({ "userform": userFormData, "shippingform": shippingFormData, }), }) .then((response) => response.json()) .then((data) => { console.log(data); -
How serve django media files on production? [Shared Hosting]
I have my django project running on Namecheap Shared Hosting but when I turn off the debug mode it stops fetching the media files. As I am on shared hosting I cannot edit the Apache Config file and Namecheap will not allow me to modify it. How can I serve the media file in shared hosting? Settings.py STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static') ] STATIC_ROOT = os.path.join(BASE_DIR, 'root') MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') Urls.py urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Please suggest me what to do in this scenario for shared hosting. -
No wkhtmltopdf executable found in widows
I am not able to solve this error. This error giving in windows. Please tell me how to solve this error. Error: OSError at /1/ No wkhtmltopdf executable found: "b''" If this file exists please check that this process can read it or you can pass path to it manually in method call, check README. Otherwise please install wkhtmltopdf - https://github.com/JazzCore/python-pdfkit/wiki/Installing-wkhtmltopdf Request Method: GET Request URL: http://localhost:8000/1/ Django Version: 4.0.4 Exception Type: OSError Exception Value: No wkhtmltopdf executable found: "b''" If this file exists please check that this process can read it or you can pass path to it manually in method call, check README. Otherwise please install wkhtmltopdf - https://github.com/JazzCore/python-pdfkit/wiki/Installing-wkhtmltopdf Exception Location: C:\Users\Manoj\AppData\Local\Programs\Python\Python39\lib\site-packages\pdfkit\configuration.py, line 38, in __init__ Python Executable: C:\Users\Manoj\AppData\Local\Programs\Python\Python39\python.exe Python Version: 3.9.5 Python Path: ['C:\\Users\\Manoj\\Desktop\\sample\\resume_website', 'C:\\Users\\Manoj\\AppData\\Local\\Programs\\Python\\Python39\\python39.zip', 'C:\\Users\\Manoj\\AppData\\Local\\Programs\\Python\\Python39\\DLLs', 'C:\\Users\\Manoj\\AppData\\Local\\Programs\\Python\\Python39\\lib', 'C:\\Users\\Manoj\\AppData\\Local\\Programs\\Python\\Python39', 'C:\\Users\\Manoj\\AppData\\Roaming\\Python\\Python39\\site-packages', 'C:\\Users\\Manoj\\AppData\\Local\\Programs\\Python\\Python39\\lib\\site-packages', 'C:\\Users\\Manoj\\AppData\\Local\\Programs\\Python\\Python39\\lib\\site-packages\\win32', 'C:\\Users\\Manoj\\AppData\\Local\\Programs\\Python\\Python39\\lib\\site-packages\\win32\\lib', 'C:\\Users\\Manoj\\AppData\\Local\\Programs\\Python\\Python39\\lib\\site-packages\\Pythonwin'] Server time: Mon, 23 May 2022 09:41:24 +0000 -
Django URLs Reverse working but not updating my URL
I'm new to Django 4.0.4. I'm trying to use reverse in model to dynamically change the url without affecting other branch not affecting. url.py: urlpatterns = [ path('', home_view, name='home'), path('products/', product_list, name='product_list'), path('products/<int:myid>/', dynamic_lookup_view, name='product-detail'), path('admin/', admin.site.urls), ] models.py def get_absolute_url(self): return reverse("product-detail", kwargs={"myid": self.id}) html <p> {{instance.id}} <a href="{{instance.get_absolute_url}}">{{instance.title}}</a> </p> Output(working): enter image description here enter image description here Problem: when i change root url for dynamic_lookup_view from 'products/int:myid/' to 'ps/int:myid/' in url.py path('products/', product_list, name='product_list'), path('p/<int:myid>/', dynamic_lookup_view, name='product-detail'), There is no update in my instance.get_absolute_url in my html!? -
Django method to return a dictionary value from request payload
I have a serializer class like this class HousingSerializer(serializers.ModelSerializer[Housing]): class Meta: model = Housing fields = "__all__" depth = 1 with request payload as [{"id":"1234","created_at":"2022-05-20T15:55:43.611922Z","updated_at":"2022-05-20T15:55:43.611938Z","status":"pending"}]% I want to create a method that if giving a Housing 'id', it should return the status from the payload, in this case, it should return the status as 'pending'. -
using google api eith django
I'm trying to connect events withing py project to google calendar. my application doesn't used google login as it is intended for only a small group of people. I've been looking for hours on how to get it done and it doesnt work. Any help is appreciated. models.py class AgendaClient(models.Model): # used to store info(same as enviroment variables) name = models.CharField(max_length=30, null=True, blank=True, unique=True) json = models.TextField(blank=True, null=True) class Event(models.Model): summary = models.CharField(max_length=50, choices=EVENT_CHOICES) description = models.CharField(max_length=50, null=True, blank=True) start_date = models.DateField() google_link = models.CharField(max_length=150, null=True, blank=True) signals.py import datetime import json from django.db.models.signals import post_delete, post_save from google.auth.transport.requests import Request from google.cloud import storage from google.oauth2 import service_account from google.oauth2.credentials import Credentials from google_auth_oauthlib.flow import InstalledAppFlow from googleapiclient.discovery import build from googleapiclient.errors import HttpError from users.models import Lid from .models import AgendaClient, Event, NIEvent # If modifying these scopes, delete the file token.json. try: SCOPES = (AgendaClient.objects.get(name='SCOPES').json).strip("][").split(', ') except: pass def get_service(refresh = False): '''this functions gets and builds the service using the token and the client_secret''' creds = None # The file token.json stores the user's access and refresh tokens, and is # created automatically when the authorization flow completes for the first # time. if len(AgendaClient.objects.filter(name='token'))==1: creds … -
Django - Saving to DB, CSV file without single quotes
I have been trying to save a CSV file with information to add to db. And, is necessary to remove the single quotes, and ")". I already tried doing the replace but, didn't worked. Also, I am doing this by an admin view. I add the csv file with informations to create objects on my db. And, it's from multiple tables. I don't know if I am using the right code or logic for this. def upload_csv(self,request): form = CSVImportForm(request.POST, request.FILES) if request.method == "POST": csv_file = request.FILES['csv_upload'] file_data = csv_file.read().decode("utf-8") csv_data = file_data.split("\n") csv_data = file_data.replace("'", "") try : for x in csv_data: fields = x.split(",") print(fields) create_hospital = {} create_hospital['hospital_name'] = fields[0], create_hospital['hospital_website'] = fields[1], create_hospital['hospital_fiscalAddress'] = fields[2], create_hospital['hospital_shippingAddress'] = fields[3], create_hospital['hospital_region'] = fields[4], create_hospital['country'] = fields[5], create_hospital['hospital_contactPerson'] = fields[6], create_hospital['hospital_contactPhone'] = fields[7], create_hospital['hospital_contactEmail'] = fields[8], create_hospital['hospital_ImageLogo'] = fields[9] created_hospital = HospitalViewRoleForUsers.objects.create(**create_hospital) create_users = {} create_users['FKLab_User'] = fields[0], create_users['user_type'] = "1", create_users['email'] = fields[11], create_users['password'] = BaseUserManager().make_random_password(8), create_users['name'] = fields[10], # create_users['FKLab_User'] = created_hospital.id # create_users['user_type'] = "1" # create_users['email'] = fields[14], # create_users['password'] = BaseUserManager().make_random_password(8), # create_users['name'] = fields[13], # create_users['FKLab_User'] = created_hospital.id # create_users['user_type'] = "1" # create_users['email'] = fields[17], # create_users['password'] = BaseUserManager().make_random_password(8), # create_users['name'] … -
Django admin prefetch content_type model
I used the django debug toolbar to analyse why the calls to my usermodel were so painfully slow within the django admin. There I saw that I had hundreds of duplicate calls to the content_type model: SELECT ••• FROM "django_content_type" WHERE "django_content_type"."id" = 1 LIMIT 21 362 similar queries. Duplicated 4 times. To be honest, I do not understand where these calls come from in the first place but I wanted to pre_fetch the model. However, this seems not to be possible in the normal way because there is actually no ForeignKey or any other kind of direct relationship between the models. How could I reduce those 362 content_type calls? This is the usermodel in question: class User(AbstractBaseUser, PermissionsMixin): """ Base model for the user application """ USERNAME_FIELD = "email" objects = UserManager() username_validator = None username = None email = models.EmailField(_("email address"), unique=True) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=True) date_joined = models.DateTimeField(default=timezone.now) first_name = models.CharField(max_length=150, blank=True) last_name = models.CharField(max_length=150, blank=True) title_of_person = models.ForeignKey( TitleOfPerson, on_delete=models.CASCADE, blank=True, null=True ) is_verified = models.BooleanField(default=False) language = models.ForeignKey( Language, blank=True, null=True, on_delete=models.SET_NULL ) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: verbose_name = _("User") verbose_name_plural = _("Users") def __str__(self) -> str: return self.email … -
Can i make sfu webrtc in django for live broadcasting of stream to many people ? any source code or tutorial?
I am a python new developer I am planning to do own SFU implementation for broadcasting video conferencing app in addition I am planning to do face recognition with attendance system. So decided to use python. Can you help me by giving answer of above question. can I use django as media server Can I pass the media to the server -
django-import-export want to calculate totals of CSV columns before importing and issuing warning
Using django-import-export, Wanted to import rows into postgresql table only after calculating the total of a particular column of CSV. If it is beyond a limit, want to issue a warning and prevent import else get the page which asks for confirmation of import of this tool. The def before_save_instance method is only for 1 instance at a time. How can I implement for all the rows of the CSV at a time? -
Django migrations no longer running on aws
I am hosting a site via elastic beanstalk and I have a 01_migrate.sh file in .platform/hooks/postdeploy in order to migrate model changes to a postgres database on Amazon RDS: #!/bin/sh source /var/app/venv/staging-LQM1lest/bin/activate python /var/app/current/manage.py migrate --noinput python /var/app/current/manage.py createsu python /var/app/current/manage.py collectstatic --noinput This used to work well bu now when I check the hooks log, although it appears to find the file there is no output to suggest that the migrate command has been ran i.e. previously I would get the following even if no new migrations: 2022/03/29 05:12:56.530728 [INFO] Running command .platform/hooks/postdeploy/01_migrate.sh 2022/03/29 05:13:11.872676 [INFO] Operations to perform: Apply all migrations: account, admin, auth, blog, contenttypes, home, se_balance, sessions, sites, socialaccount, taggit, users, wagtailadmin, wagtailcore, wagtaildocs, wagtailembeds, wagtailforms, wagtailimages, wagtailredirects, wagtailsearch, wagtailusers Running migrations: No migrations to apply. Found another file with the destination path 'favicon.ico'. It will be ignored since only the first encountered file is collected. If this is not what you want, make sure every static file has a unique path. Whereas now I just get 2022/05/23 08:47:49.602719 [INFO] Running command .platform/hooks/postdeploy/01_migrate.sh Found another file with the destination path 'favicon.ico'. It will be ignored since only the first encountered file is collected. If this is … -
Django manage.py commands generates error in Cronjob
Whenever I'm running a manage.py command (e.g. migrate, runserver) everything is fine. I'm using the following Cronjob command: * * * * * python3 /home/ec2-user/Project/manage.py migrate However, whenever I'm scheduling a manage.py command in Crontab, the following error comes up: File "/home/ec2-user/project/manage.py", line 22, in <module> main() File "/home/ec2-user/project/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/home/ec2-user/.local/lib/python3.7/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/home/ec2-user/.local/lib/python3.7/site-packages/django/core/management/__init__.py", line 395, in execute django.setup() File "/home/ec2-user/.local/lib/python3.7/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/ec2-user/.local/lib/python3.7/site-packages/django/apps/registry.py", line 114, in populate app_config.import_models() File "/home/ec2-user/.local/lib/python3.7/site-packages/django/apps/config.py", line 301, in import_models self.models_module = import_module(models_module_name) File "/usr/lib64/python3.7/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 728, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/home/ec2-user/.local/lib/python3.7/site-packages/django/contrib/auth/models.py", line 3, in <module> from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager File "/home/ec2-user/.local/lib/python3.7/site-packages/django/contrib/auth/base_user.py", line 48, in <module> class AbstractBaseUser(models.Model): File "/home/ec2-user/.local/lib/python3.7/site-packages/django/db/models/base.py", line 122, in __new__ new_class.add_to_class('_meta', Options(meta, app_label)) File "/home/ec2-user/.local/lib/python3.7/site-packages/django/db/models/base.py", line 326, in add_to_class value.contribute_to_class(cls, name) File "/home/ec2-user/.local/lib/python3.7/site-packages/django/db/models/options.py", line 207, in contribute_to_class self.db_table = truncate_name(self.db_table, connection.ops.max_name_length()) File "/home/ec2-user/.local/lib/python3.7/site-packages/django/utils/connection.py", line 15, in __getattr__ return getattr(self._connections[self._alias], item) File "/home/ec2-user/.local/lib/python3.7/site-packages/django/utils/connection.py", … -
Django: URL Path not found jumps into next app
I have two apps: backend shop I my urls in main app dir: path('backend/', include('backend.urls')), path('', include('shop.urls')), the problem is if I write in my url: localhost:8000/backend/abc which not exist Django jumps over to shop.urls and the app is crashing because it can not find the slug and the query goes in fail. How can I prevent if I go to the url /backend/somethingwhichnotexist is returning an 404 and not search in other app urls for this folder? I have thought that this is one of the main reason for split the urls in app folders. Here are some urls from backend/urls.py: from django.urls import path, re_path from . import views as backend_views from django.contrib.auth import views as auth_views from froala_editor import views from django.conf.urls import include urlpatterns = [ path('stamdata/', backend_views.edit_masterdata), path('praefikser/', backend_views.edit_prefixes), path('leverandorer/', backend_views.suppliers_view), path('leverandorer/add', backend_views.add_supplier), ] handler404 = 'backend.views.page_not_found_view' regards Christopher.