Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I am new to Python. Please help me if there Is any way to solve this error
`` `PS C:\Users\hp\OneDrive\Desktop\Car\car> python manage.py makemigrations No changes detected Traceback (most recent call last): File "manage.py", line 22, in main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\hp\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\management_init_.py", line 401, in execute_from_command_line utility.execute() File "C:\Users\hp\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\management_init_.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\hp\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\management\base.py", line 341, in run_from_argv connections.close_all() File "C:\Users\hp\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\utils.py", line 230, in close_all connection.close() File "C:\Users\hp\AppData\Local\Programs\Python\Python38\lib\site-packages\django\utils\asyncio.py", line 26, in inner return func(*args, **kwargs) File "C:\Users\hp\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\backends\sqlite3\base.py", line 261, in close if not self.is_in_memory_db(): File "C:\Users\hp\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\backends\sqlite3\base.py", line 380, in is_in_memory_db return self.creation.is_in_memory_db(self.settings_dict['NAME']) File "C:\Users\hp\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\backends\sqlite3\creation.py", line 12, in is_in_memory_db return database_name == ':memory:' or 'mode=memory' in database_name TypeError: argument of type 'WindowsPath' is not iterable` `` I am developing a project on a car showroom management system.I just opened the vs code this error appeared and my django administration is also not working properly.This image is of django administration This is django administration's Login Page. -
How to configure Apache to deploy a project with Django and React?
After testing on localhost and checking that the application works, I want to deploy it from Apache (xampp). I am using Windows Server 2016 operating system, Python 3.11.8. I have also downloaded the file mod_wsgi-4.9.2-cp311-cp311-win_amd64.whl I have tried to modify the Apache configuration (httpd.conf), adding a virtualhost (80) for the frontend and it worked correctly. The problem occurs when I want to add another virtual host (8000) for Django, causing Apache to fail to start: <VirtualHost *:80> ServerName fichaje.local DocumentRoot "C:/Users/Administrador/Documents/fichaje/frontend/build" <Directory "C:/Users/Administrador/Documents/fichaje/frontend/build"> Options Indexes FollowSymLinks AllowOverride All Require all granted LoadFile "C:/Users/Administrador/AppData/Local/Programs/Python/Python311/python311.dll" WSGIPythonHome "C:/Users/Administrador/AppData/Local/Programs/Python/Python311" LoadModule wsgi_module "C:/Users/Administrador/AppData/Local/Programs/Python/Python311/Lib/site-packages/mod_wsgi/server/mod_wsgi.cp311-win_amd64.pyd" <VirtualHost *:8000> ServerName fichaje_back.local Alias /static "C:/Users/Administrador/Documents/fichaje/static" <Directory "C:/Users/Administrador/Documents/fichaje/static"> Require all granted <Directory "C:/Users/Administrador/Documents/fichaje/fichaje"> <Files wsgi.py> Require all granted </Files> </Directory> # Script WSGI WSGIDaemonProcess fichaje python-path=C:/Users/Administrador/Documents/fichaje;C:/Users/Administrador/Documents/fichaje/myenv/Lib/site-packages <IfModule mod_wsgi.c> WSGIPythonHome "C:/Users/Administrador/AppData/Local/Programs/Python/Python311" </IfModule> -
Djoser, does not send email, I do not know what else to do
I am making a base project to send emails with djoser, but I am not receiving any confirmation email -I have two-step verification enabled on your main Gmail account. -I have generated a password for the application. This is my configuration settings. setting.py # Simple_JWT settings SIMPLE_JWT = { "AUTH_HEADER_TYPES": ("JWT",), "ACCESS_TOKEN_LIFETIME": timedelta(minutes=60), "REFRESH_TOKEN_LIFETIME": timedelta(days=1), "ROTATE_REFRESH_TOKENS": True, "UPDATE_LAST_LOGIN": True, } # Email settings EMAIL_BACKEND = "django.core.mail.backends.smtp.EmailBackend" EMAIL_HOST = "smtp.gmail.com" EMAIL_PORT = 587 EMAIL_HOST_USER = os.environ.get("EMAIL_HOST_USER") EMAIL_HOST_PASSWORD = os.environ.get("EMAIL_HOST_PASSWORD") EMAIL_USE_TLS = True # Djoser settings Djoser = { "LOGIN_FIELD": "email", "USER_CREATE_PASSWORD_RETYPE": True, "ACTIVATION_URL": "/activate/{uid}/{token}", "SEND_ACTIVATION_EMAIL": True, "SEND_CONFIRMATION_EMAIL": True, "PASSWORD_CHANGED_EMAIL_CONFIRMATION": True, "PASSWORD_RESET_CONFIRM_URL": "/password-reset/{uid}/{token}", "SET_PASSWORD_RETYPE": True, "PASSWORD_RESET_SHOW_EMAIL_NOT_FOUND": True, "TOKEN_MODEL": None, "SERIALIZERS": { "user_create": "accounts.serializers.UserCreateSerializer", "user": "accounts.serializers.UserCreateSerializer", "user_delete": "djoser.serializers.UserDeleteSerializer", }, "EMAIL": { "activation": "accounts.email.ActivationEmail", "confirmation": "accounts.email.ConfirmationEmail", "password_reset": "accounts.email.PasswordResetEmail", "password_changed_confirmation": "accounts.email.PasswordChangedConfirmationEmail", }, } When I register it accepts my request but does not send anything 14/Mar/2024 09:38:53] "POST /api/auth/users/ HTTP/1.1" 201 103 How could I solve this proble -
Requested setting DEBUG, but settings are not configured
when im in terminal start my django project show that eror django.core.exceptions.ImproperlyConfigured: Requested setting DEBUG, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. im set my dada base as postgresql to sqlite and chek my setting file -
Navigating to a link that is not part of the Django application is throwing a 404 error
I was running a wordpress site at "mydomain.com" with a whmcs installation at mydomain.com/portal. everything was fine. I recently got rid of the wordpress installation and set up a Django website at mydomain.com. The WHMCS installation at mydomain.com/portal is still there. But here is the issue: visiting mydomain.com/portal is giving me 404 error same thing for mydomain.com/portal/admin (404 error) the pages load if i visit mydomain.com/portal/index.php or mydomain.com/portal/login My current .htaccess file in mydomain.com: RewriteEngine On RewriteCond %{HTTPS} !=on RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301,NE] Header always set Content-Security-Policy "upgrade-insecure-requests;" # DO NOT REMOVE. CLOUDLINUX PASSENGER CONFIGURATION BEGIN PassengerAppRoot "/home/user/mydomain.com" PassengerBaseURI "/" PassengerPython "/home/usr/virtualenv/mydomain.com/3.9/bin/python" # DO NOT REMOVE. CLOUDLINUX PASSENGER CONFIGURATION END # DO NOT REMOVE OR MODIFY. CLOUDLINUX ENV VARS CONFIGURATION BEGIN <IfModule Litespeed> </IfModule> # DO NOT REMOVE OR MODIFY. CLOUDLINUX ENV VARS CONFIGURATION END # Newly added text below here, in order to troubleshoot CSS not showing up <IfModule mod_rewrite.c> RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^static/(.*)$ /home/usr/mydomain.com/staticfiles/$1 [QSA,L,NC] </IfModule> <IfModule mod_rewrite.c> RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^media/(.*)$ /home/usr/mydomain.com/blog_images/$1 [QSA,L,NC] </IfModule> <FilesMatch "\.(?i:ico|flv|jpg|jpeg|png|gif|js|css)$"> <IfModule mod_expires.c> ExpiresActive On ExpiresDefault "access plus 1 month" </IfModule> FileETag MTime Size </FilesMatch> I tried adding the below but it did not help. RewriteEngine … -
How can change the primary key in a django model so that other dependent models are also affected and the changes are synced to the postgresql db
I have a django project with a database table that already contains data. The models: class Foo_A(models.Model): field1_pk = models.CharField(max_length=50) field2 . . fieldN_newpk = model.CharField(max_length=50) Data in field1_pk and fieldN_newpk are exactly the same. Lets say I have other models that reference fieldN_newpk as foreign key. I would like to rename a fieldN_newpk in this Foo_A model, without losing any data. This change should also be reflected in my other dependent models. I want to change the primary key from field1_pk to fieldN_newpk I want these changes to be reflected in my postgresql database as well I have seen other answers related to renaming of a model Also Is there a safe way/safe mode to try out these changes/migrations before actually trying on the original codebase -
Synchronizing a Django database with a Realm or Core database in an iOS app
I'm working on an iOS app that needs to synchronize data with a Django backend. The backend uses Django ORM and exposes data through a RESTful API built with Django REST Framework. On the iOS side, I'm using Realm or Core in future as the local database. I need guidance on how to implement synchronization between the Django database and the Realm or Core database in my iOS app. Specifically, I'm looking for advice on the following: How to design the synchronization process to ensure data consistency and integrity. Strategies for fetching data from the Django API and storing it locally in the Realm database. Techniques for handling conflicts between local and server data. Best practices for optimizing synchronization performance and reliability. Recommendations for error handling and retry mechanisms in case of network failures or server errors. Any security considerations or precautions I should take when implementing data synchronization. I would appreciate any insights, sample code, or references to relevant resources that can help me implement robust and efficient data synchronization between my Django backend and iOS app using Realm. Thank you! Some advices who work with -
How to use node modules within a Django app
I developed a web map app using Django. I used Leaflet for the map and I'd like to add some Leaflet plugins that are meant to be installed using npm. I'm new to node (I've only used it in Development during my classes) and have never used it in Production or with Django. I'm wondering if I have to configure anything else in my project or if I can just npm init and then npm install anything. I suppose I'd have to add node_modules to my .gitignore but I'm not sure how should I manage the static files generated by node and how should I import modules into my django templates. I'd be using Node only for front-end stuff, all my back-end is managed by Django. I haven't installed anything yet as I'm afraid I'll break my web. -
How can put my python django project on live?
I have create a project by python django this project work as an documents Archive by uploding the doucments by the admin panle. The problem is that: 1- I want to deploy on my company server. can anyone tell me how to do it because when I have tried the 'python manage.py runsever ipaddressofservermachine, it is working on server machine but it is not working in other laptops. i thought it should have worked but it did not. 2- I want the uploaded file storage not in my :D drive i wanted to be stored in company server I have tried many ways and search in youtube i did not find the way to deploy my project live and make it live and accessible for my employes and make the uploaded file storage not in my :D drive i wanted to be stored in company server -
Remove URL prefix in Jinja + Django
In Django model URLs stored in URL field, so the values are look like "https://example.com/id" In HTML rending with Jinja code should be without https:// prefix like this Can't find any embedded Jinja filters or elegant solution how to remove prefix on the fly without extra coding in DB -
Django view doesn’t recognize the parameter name from template
I am trying to pass two parameters from template (“zn” and “ru”) to filter posts in view. It seems to me, that the variables of both parameters are OK, but not under proper name. The view probably doesn’t recognize which is which. Filtering with parameter “zn” works, but filtering with parameter “ru” doesn’t (see the error statement in picture). enter image description here urls.py: from django.urls import path from . import views urlpatterns = [ ... path("clanky/", views.clanek_vyber, name="clanky_vyber", kwargs={'zn': '', 'ru': ''}), path("clanky/<slug:zn>/", views.clanek_vyber, name="clanky_vyber", kwargs={'ru': ''}), path("clanky/<slug:ru>/", views.clanek_vyber, name="clanky_vyber", kwargs={'zn': ''}), path("clanky/<slug:zn>/<slug:ru>/", views.clanek_vyber, name="clanky_vyber"), views.py: from django.shortcuts import render from django.utils import timezone from django.views import generic from django.core.paginator import Paginator ... from .models import Clanek, Rubrika, Znacka, GalerieObrazku, Hlavni_banner ... def clanek_vyber(request, zn, ru): bannery_1 = Hlavni_banner.objects.filter(published_date__lte=timezone.now()).order_by('-published_date')[:1] clanek_znacka = Clanek.objects.values('znacka') znac = Znacka.objects.filter(id__in=clanek_znacka) rubr = Clanek.objects.distinct('rubrika').order_by('rubrika_id') if (zn!="" and ru!=""): uvodni_clanek = Clanek.objects.filter(znacka__slug=zn).filter(rubrika__slug=ru).order_by('-published_date')[:1] zna = Znacka.objects.get(slug=zn) rub = Rubrika.objects.get(slug=ru) cla_vyb = Clanek.objects.filter(znacka__slug=zn).filter(rubrika__slug=ru).order_by('-published_date')[1:] paginator = Paginator(cla_vyb, 20) # ukáže dvacet dalších článků page_number = request.GET.get("page") page_obj = paginator.get_page(page_number) context = { 'bannery_1': bannery_1, 'uvodni_clanek': uvodni_clanek, 'page_obj': page_obj, 'znac': znac, 'zna': zna, 'zn': zn, 'rubr': rubr, 'rub': rub, 'ru': ru } return render(request, "zentour/clanky.html", context) if(zn!=""): uvodni_clanek = Clanek.objects.filter(znacka__slug=zn).order_by('-published_date')[:1] … -
Why am I getting DoesNotExist for the parent model in save_related
I am firing a celery task in save_related that takes the parent object id and does a get query to obtain the instance for use. Problem is some of the get queries are failing with DoesNotExist. This doesn't make sense to me because the Django docs clearly state that "Note that at this point the parent object and its form have already been saved.". Also why are others not failing? I am about to experiment with what happens when I call super().save_related(...) before the celery task but I don't think that should be an issue because of the note above. Django==4.2.3 -
mock a shell script in Django/DRF test
I tried to make some test on a method in views, but this method call a script shell, this script is write to work in another OS so I need to mocke this. here the test: @patch('check_web_share_file_folder.get_path_from_inode') def test_list_with_search_mocked(self, mock_get_attribute): mock_get_attribute.return_value = 'expected value' request = self.factory.get('/fake-url') force_authenticate(request, user=self.user) view = WebShareFileFolderViewSet.as_view({'get': 'list'}) response = view(request) self.assertEqual(response.status_code, status.HTTP_200_OK) here the problem, I encounter this error with the test: AttributeError: <function check_web_share_file_folder at 0x00000237FD567708> does not have the attribute 'get_path_from_inode' check_web_share_file_folder.py have of course get_path_from_inode() def get_path_from_inode(inode): std, err, code = popen_wrapper([ 'sudo', 'get_path_from_inode.sh', str(inode) ]) if code != 0: return False return str(std.strip())[1:] -
unique_together in bulk_create
this is my model: class Reminder(models.Model): timestamp = models.DateTimeField() time_frame = models.CharField(default = "5minutes" , max_length=30,choices=[ ("5minutes","5minutes"), ("15minutes","15minutes"), ("30minutes","30minutes"), ("1hour","1hour"), ("4hours","4hours"), ("1day","1day") ]) coin = models.ForeignKey(Coin,on_delete=models.CASCADE) class Meta: unique_together = ["coin","time_frame"] i want to use bulk_create command for create a lot of object from this model. options of bulk_create is update_fields and unique_fields. but i have unique_together fields. what i suppose to do for this code: Reminder.objects.bulk_create(reminders, update_conflicts=True,update_fields=['timestamp'],batch_size=1000) -
Connecting a Django project that is hosted on a Virtual Machine with Nginx and Gunicorn
I'm new to deploying applications. Currently, I'm hosting my Django project on an Ubuntu virtual machine with IP address 192.168.xxx.xxx. It is hosted on a physical service with public IP address of 202.xxx.xxx.xxx (using port 8080). I have gunicorn and nginx installed and incorporated, and they're running properly as sudo systemctl status gunicorn and sudo systemctl status nginx show that they're running with no errors. However, when I try to access the public IP address 202.xxx.xxx.xxx:8080, I'm getting the default Nginx page. As for how I setup my gunicorn and nginx, I followed the guide posted here: https://medium.com/@muhammadali_12976/deploying-django-on-a-local-virtual-machine-virtualbox-with-nginx-and-gunicorn-369f70937913 Here's the gunicorn.socket file: [Unit] Description=gunicorn socket [Socket] ListenStream=/home/myProject/myProject.sock [Install] WantedBy=sockets.target Here's the gunicorn.service file: [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=myUserName Group=www-data WorkingDirectory=/home/myProject ExecStart=/home/myProject/env/bin/gunicorn --access-logfile - --workers 3 --bind unix:/home/myProject/myProject.sock core.wsgi:application [Install] WantedBy=multi-user.target Here's the contents of my /etc/nginx/sites-available/myProject file server { listen 80; server_name 192.168.xxx.xxx; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/myProject; } location / { include proxy_params; proxy_pass http://unix:/home/myProject/myProject.sock; } } Should I have used the public address in server_name or the IP address of the virtual machine where my Django project is hosted? In addition, I also tried changing the port … -
I am getting broken image in a html(cart) page
I am creating an add-to-cart function for my website. I am getting broken images in my cart.html page. So, In cart.html: {% for product_id, item in data.items %} <div class="col-md-12 col-lg-8"> <div class="items"> <div class="product"> <div class="row"> <div class="col-md-3"> <img class="img-fluid mx-auto d-block image" src="{{item.image}}" > <!-- #1 --> </div> <div class="col-md-8"> <div class="info"> <div class="row"> <div class="col-md-5 product-name"> <div class="product-name"> <a href="#">{{item.title}}</a> <div class="product-info"> <div>Display: <span class="value">5 inch</span></div> <div>RAM: <span class="value">4GB</span></div> <div>Memory: <span class="value">32GB</span></div> </div> </div> </div> <div class="col-md-4 quantity"> <label for="quantity">Quantity:</label> <input id="quantity" type="number" value ="1" class="form-control quantity-input"> </div> <div class="col-md-3 price"> <span>{{item.price}}</span> </div> </div> </div> </div> </div> </div> </div> </div> You can see in the #1 that I add the image there. I also created view for add-to-cart function So, in views.py: def add_to_cart(request): cart_product={} cart_product[str(request.GET['id'])]={ 'title': request.GET['title'], 'qty': request.GET['qty'], 'price': request.GET['price'], 'image': request.GET['image'], 'pid': request.GET['pid'], } if 'cart_data_obj' in request.session: if str(request.GET['id']) in request.session['cart_data_obj']: cart_data= request.session['cart_data_obj'] cart_data[str(request.GET['id'])]['qty']=int(cart_product[str(request.GET['id'])]['qty']) cart_data.update(cart_data) request.session['cart_data_obj']=cart_data else: cart_data=request.session['cart_data_obj'] cart_data.update(cart_product) request.session['cart_data_obj']=cart_data request.session['total_cart_items'] = len(cart_data) else: request.session['cart_data_obj']=cart_product request.session['total_cart_items'] = len(cart_product) return JsonResponse({"data":request.session['cart_data_obj'],'totalcartitems': request.session['total_cart_items']}) In the function.js: $("#add-to-cart-btn").on("click",function(){ let quantity=$("#product-quantity").val() let product_title=$(".product-title").val() let product_id=$(".product-id").val() let product_price = $("#current-product-price").text() let product_image = $(".product-image").val() let product_pid=$(".product-pid").val() let this_val=$(this) console.log("Quantity:", quantity); console.log("Id:", product_id); console.log("PId:", product_pid); console.log("Image:", product_image); console.log("Title:", product_title); … -
Django 5 postgres superuser login fail
I created a Django project SQLite. I decided to move from SQLite to PostgreSQL. All migrations worked. I created the superuser successfully but when I try logging in the admin it says that the user can't be found. this is the users model from django.db import models from django.contrib.auth.models import AbstractUser # Create your models here. class CustomUser(AbstractUser): """ Class for creating custom users. There are 3 user types in this class """ USER_TYPE_CHOICES = ( ('manager', 'Manager'), ('supervisor', 'Supervisor'), ('employee', 'Employee'), ) user_type = models.CharField(max_length=20, choices=USER_TYPE_CHOICES) is_active = models.BooleanField(default=False) name = models.CharField(max_length=255) email = models.EmailField(unique=True) national_id = models.CharField(max_length=20, unique=True) def __str__(self): return self.email # Provide a unique username or remove the unique constraint from email def save(self, *args, **kwargs): if not self.username: self.username = self.name # Use email as username or provide a unique username super().save(*args, **kwargs) I tried logging in the admin. It says the user is not found. I used both email and username to be sure but the user still can't be found. This is pip freeze: pip freeze asgiref==3.7.2 attrs==23.1.0 bcrypt==4.1.2 Django==5.0 django-cors-headers==4.3.1 django-filter==23.5 djangorestframework==3.14.0 djangorestframework-simplejwt==5.3.1 drf-spectacular==0.27.0 Faker==21.0.0 inflection==0.5.1 jsonschema==4.20.0 jsonschema-specifications==2023.11.2 Markdown==3.5.1 mysqlclient==2.2.3 psycopg2==2.9.9 PyJWT==2.8.0 python-dateutil==2.8.2 pytz==2023.3.post1 PyYAML==6.0.1 referencing==0.32.0 rpds-py==0.15.2 six==1.16.0 sqlparse==0.4.4 typing_extensions==4.9.0 uritemplate==4.1.1 -
Export file automatic download not working in Django
I have trouble when exporting excel file through export button it does not appear download automatically, but when I inspect element then selecting network if I clicked export status it will download, but for me it will hassle to inspect element instead just click one button. I used Chrome I already tried set to automatic download but the result will the same, Is this the issue for the new version of the web browser or in my code? This is my code @csrf_exempt def export_status(request): with connection.cursor() as cursor: cursor.execute(""" SELECT tev_incoming.id,tev_outgoing.dv_no AS dv_no, tev_incoming.code, tev_incoming.account_no, tev_incoming.id_no, tev_incoming.first_name, tev_incoming.middle_name, tev_incoming.last_name, tev_incoming.date_travel, tev_incoming.division, tev_incoming.section, tev_incoming.status_id, au.first_name AS incoming_by,rb.first_name AS reviewed_by, tev_incoming.original_amount, tev_incoming.final_amount, tev_incoming.incoming_in AS date_actual, tev_incoming.updated_at AS date_entry, tev_incoming.incoming_out AS date_reviewed_forwarded, tev_bridge.purpose AS purposes FROM tev_incoming INNER JOIN ( SELECT MAX(id) AS max_id FROM tev_incoming GROUP BY code ) AS latest_ids ON tev_incoming.id = latest_ids.max_id LEFT JOIN tev_bridge ON tev_incoming.id = tev_bridge.tev_incoming_id LEFT JOIN tev_outgoing ON tev_bridge.tev_outgoing_id = tev_outgoing.id LEFT JOIN auth_user AS au ON au.id = tev_incoming.user_id LEFT JOIN auth_user AS rb ON rb.id = tev_incoming.reviewed_by ORDER BY tev_incoming.id DESC; """) rows = cursor.fetchall() response = HttpResponse(content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') response['Content-Disposition'] = 'attachment; filename={date}-TRIS-REPORT.xlsx'.format( date=datetime.now().strftime('%Y-%m-%d'), ) workbook = Workbook() worksheet = workbook.active worksheet.title … -
Django hosting in cpanel with out using Setup Python App
I want to host my Django project in cPanel with out using Setup Python App. How can i do that? Please provide step by step solution from beginning. I search for the solution in google, but i can't get the answer. Please help me. -
Django admin : How to show a model as inline inside another model, which is indirectly related
I have models named user, authtoken and userdevice. class User(LifecycleModelMixin, AbstractUser): email = models.EmailField(unique=True) slug = models.SlugField(max_length=100, unique=True, blank=False, null=True) class AuthToken(models.Model): objects = AuthTokenManager() digest = models.CharField( max_length=CONSTANTS.DIGEST_LENGTH, primary_key=True) token_key = models.CharField( max_length=CONSTANTS.TOKEN_KEY_LENGTH, db_index=True) user = models.ForeignKey(User, null=False, blank=False, related_name='auth_token_set', on_delete=models.CASCADE) created = models.DateTimeField(auto_now_add=True) expiry = models.DateTimeField(null=True, blank=True) class UserDevice(models.Model): token = models.OneToOneField(AuthToken, on_delete=models.CASCADE, related_name="auth_token") device_type = models.CharField(max_length=100, choices=DevicesChoices.choices) access_type = models.CharField(max_length=100, choices=AccessChoices.choices) device_brand = models.CharField(max_length=100, null=True, blank=True) I need to show the userdevice inside the user detail page in admin panel as inline. Django Error admin.E202 'userdevice' has no ForeignKey to 'accounts.user' Getting this error. Any help will be much appreciated. -
MySQL/Django/Docker -> 1045, "1045 (28000): Access denied for user 'X'@'xx.xxx.xx.xx' (using password: YES)", '28000'
I have mariadb/mysql and django running as separate docker containers (both have separate docker-compose.yml files as well). When I try to build my django docker container using docker-compose build(I have a Dockerfile defined for this with makemigrations and migrate commands in it) my container builds fine and correctly and python manage.py makemigrations and python manage.py migrate work fine as well. However when I do docker exec -ti <django-container-name> bash and try to run python manage.py makemigrations and python manage.py migrate, it doesn't work. I get a 1045, "1045 (28000): Access denied for user '<user>'@'<host>' (using password: YES)", '28000'error. Similarly, when I try to do mysql -h <hostname> -P <port> -u <username> -p I get a bash error saying that mysql doesn't exist (I also get this same error when i do just mysql). Accessing MariaDB: When I do docker exec -ti <mariadb-container-name> bash and run the mysql command, I am able to see the migrations from the initial django build but nothing else after that. Where am I going wrong that django can build and do makemigrations/migrate fine but won't run these commands inside the docker container once it is up and running? I should clarify that mariadb/mysql and django … -
React Router version issue [duplicate]
I just had a quick question about a React project I'm working on. I'm trying to get React Router to route to both a login page and, upon successfully doing that, have it re-route to my app's homepage. However, I'm using version 6, and I keep getting the following error when I try to run it: "[PrivateRoute] is not a component. All component children of must be a or <React.Fragment>" Any insight into how I can reformat my code? Thanks!! import React from 'react'; import { BrowserRouter as Router, Route, Routes, Navigate } from 'react-router-dom'; import Login from './Login'; import Spreadsheetester from './Spreadsheet'; const PrivateRoute = ({ element: Element, ...rest}) => ( <Route {...rest} element={ localStorage.getItem('token') ? ( <Element /> ) : ( <Navigate to="/login" replace /> ) } /> ); const App = () => { return ( <Router> <Routes> <Route exact path="/login" element={<Login />} /> <PrivateRoute exact path="/" element={<Spreadsheet />} /> </Routes> </Router> ); }; export default App; -
Wagtail and Elasticsearch , Lookup "icontains"" not recognised
I'm trying to run a search with Wagtail (5.2) and Elastic (7) When I make a search for Users wagtail_admin/users/?q=ffff I got such error FilterFieldError Cannot filter search results with field "email". Please add index.FilterField('email') to User.search_fields Then I add extra field to search fields in the code class User: search_fields = [ index.SearchField("name", partial_match=True), index.FilterField("email", partial_match=True), ] But just got another error FilterError /wagtail_admin/users/ Could not apply filter on search results: "email__icontains = ffff". Lookup "icontains"" not recognised. How it can be fixed? -
axios response.data is empty when django returns a queryset with a single element
I am using axios to get some data from my backend API made with django. Something very very wired is happening and I have been debugging this for hours. This is the axios function that gets the data: function useGetProducts(category: string, subcategory: string, code:string){ const [products, setProducts] = useState<Product[]>([]); useEffect(() => { axios.get(getQueryUrl(category, subcategory, code)) .then(response => { console.log(response) setProducts(response.data); }) .catch(error => { console.error(error); }); },[]); return products; } And here is my ProductView in django class ProductView(viewsets.ModelViewSet): serializer_class = ProductSerializer def get_queryset(self): queryset = Product.objects.all() cat = self.request.query_params.get('category', None) subcat = self.request.query_params.get('subcategory', None) code = self.request.query_params.get('code', None) if cat and subcat and code: # Sanitize the name parameter using Django's ORM queryset = queryset.filter(code__exact=code) elif cat and subcat: queryset = queryset.filter(category__exact=cat, sub_category__exact=subcat) elif cat: queryset = queryset.filter(category__exact=cat) print(queryset) return queryset Now the thing is when the queryset contains only one element the response.data is an empty array but when the queryset contains more than one element the response.data contains the right amount of elements. The method getQueryUrl works correctly. I tried to limit the output of other querysets that supposed to contain more than 1 element to 1 and same thing, empty array on the frontend side. ChatGPT … -
Django linebreaks disallow CSS Style
I have a problem in my new Django project. In fact, I've created a Model named "Tutorial" which has a Description being a TextField(). So when I call it in my HTML file from my View it works correctly for all except for this one because I need to add linebreaks if I want to keep all the body of my description. And without these linebreaks my CSS works correctly but the text goes through the content area and with linebreaks I show all the text but the CSS style is disallowed, please help me.Linebreaks code (Don't take care about striptags). Here it's without the linebreaksAnd here with linebreaks it's horrible lol Need help please I hope you can help me cause I didn't find anything anywhere.