Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Error: Invalid Date/Time Format - The value "0000-00-00 00:00:00.000000" matches the format but is invalid as a date/time in Django validation
`your class EnrollmentModel(models.Model): Semesters=[ (1, 'One'), (2, 'Two'), (3, 'Three'), (4, 'Four'), (5, 'Five'), (6, 'Six'), (7, 'Seven'), (8, 'Eight'), ] payment_type=( ('Marchent','Marchent'), ('Bkash','Bkash'), ('Rocket','Rocket'), ('Nagad','Nagad'), ('Cash Hand','Cash Hand'), ('Apps','Apps'), ('Upay','Upay'), ) enroll_status=( ('Pending','Pending'), ('Due','Due'), ('Due-Pending','Due-Pending'), ('Complete','Complete'), ('Refunded','Refunded'), ('Due-Paid','Due-Paid'), ('Customized-Paid','Customized-Paid'), ) layer=( ('Full','Full'), ('Department','Department'), ('Non-Department','Non-Department'), ) softmax_student_id = models.CharField(max_length=50, unique=True,null=True, blank=True) student = models.ForeignKey(StudentModel, related_name='student_enroll', on_delete=models.CASCADE,null=True,db_index=True) package = models.ForeignKey(PackageModel, related_name='package_enroll', on_delete=models.CASCADE,null=True,db_index=True) plan = models.ForeignKey(PlanModel, related_name='plans', on_delete=models.CASCADE,null=True,db_index=True) category = models.ForeignKey(CategoryModel, related_name='categories', on_delete=models.CASCADE,null=True,db_index=True) employee = models.ForeignKey(User, related_name='employee_enroll', on_delete=models.CASCADE, null=True,db_index=True) subject=models.ManyToManyField(DepartmentSubjectModel, related_name='dept_subject',blank=True) semester = models.IntegerField(choices=Semesters, null=True, blank=True) course_fee = models.IntegerField(default=0,null=True,blank=True) payable_fee = models.IntegerField(default=0,blank=True,null=True) due_payment_date = models.DateField(default=current_date, null=True, blank=True) extra_amount = models.IntegerField(default=0,null=True, blank=True) sponsored_amount = models.IntegerField(default=0,null=False, blank=True) initial_paid = models.IntegerField(default=0,null=False, blank=True) payment_type = models.CharField(max_length=100, choices=payment_type, blank=True, null=True) payment_number = models.CharField(max_length=100, null=True, blank=True) is_due_enrollment = models.BooleanField(default=False) invoice_number = models.CharField(max_length=100, null=True, blank=True) course_note = models.TextField(max_length=500, null=True, blank=True) status = models.CharField(max_length=20, choices=enroll_status, default='Pending') package_layer=models.CharField(max_length=100,null=True,blank=True,choices=layer) created_at = models.DateTimeField( default=timezone.now,db_index=True,null=True, blank=True) updated_at=models.DateTimeField(auto_now=True) is_old_student= models.BooleanField( default=False, null=True, blank=True) is_message_send= models.BooleanField( default=False,null=True, blank=True) is_service_satisfied= models.BooleanField( default=False,null=True, blank=True) class Update_EnrollmentSerializer(serializers.ModelSerializer): # package = serializers.PrimaryKeyRelatedField(queryset=PackageModel.objects.all(), required=True) # student = serializers.PrimaryKeyRelatedField(queryset=StudentModel.objects.all(), required=True) subject = serializers.PrimaryKeyRelatedField(queryset=DepartmentSubjectModel.objects.all(), required=False, many=True) created_at = serializers.DateTimeField( input_formats=[ '%Y-%m-%dT%H:%M:%S', '%Y-%m-%dT%H:%M:%S.%f', '%Y-%m-%d %H:%M:%S', '%Y-%m-%d', '%Y-%m-%d %I:%M %p' # Handle "12:00 AM" case ], required=False ) class Meta: model = EnrollmentModel fields = … -
Django / Python Error: Could not parse the remainder: ' Server' from 'SQL Server'
Im getting this error when rendering an HTM file on my Django instance. It is thrown in a py-script tag. However, if I drop the following code into a .py file and run/debug it in either Powershell or VSCode, its just fine. I just started learning Python and Django and its neat. It took me a couple of days to get it set up and running, and I like it very much. Anyway Code: <py-script> print("booyaaaa") import pyodbc import ctypes connectionString = "DRIVER={{SQL Server}};SERVER=###;DATABASE=###;UID=##;PWD=###" conn = pyodbc.connect(connectionString) SQL_QUERY = """ SELECT TOP 55 * FROM dbo.tbl### ORDER BY ID DESC """ cursor = conn.cursor() cursor.execute(SQL_QUERY) records = cursor.fetchall() recordString = "" for r in records: recordString += str(r.DonorID) + "\n" print(recordString) </py-script> Error: Environment: Request Method: GET Request URL: http://localhost/ Django Version: 5.0.10 Python Version: 3.13.1 Installed Applications: ['whitenoise.runserver_nostatic', 'myDjangoProj', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Template error: In template C:\Users\marlon\myDjangoProj\myDjangoProj\templates\index.htm, error at line 18 Could not parse the remainder: ' Server' from 'SQL Server' 8 : <script defer src="https://pyscript.net/alpha/pyscript.js"></script> 9 : 10 : <title>PyScript Demo</title> 11 : </head> 12 : <body> 13 : <py-script> 14 : print("booyaaaa") 15 : … -
Django model-objects permission per logged user/owner?
I've got django model , that has creator field = logged user. class MyModel(models.Model): creator = models.ForeignKey(User, on_delete=models.SET_NULL ) It works fine. Then, in all my views (lists, create update, delete etc)... I would like to allow only the owner (creator) to be able to view and modify his objects. Do I need to check it manually in the beginning of every view, ie.. check the creator of the object to be deleted (for example) if equals logged user, or is there any more elegant way? -
Django Oauth Toolkit with custom User model
a question here. I want to use https://django-oauth-toolkit.readthedocs.io/en/latest/index.html. But I want the authentication to use different user model (not the settings.AUTH_USER_MODEL). Is that possible ? All answers I found just said, to set the AUTH_USER_MODEL to my custom model - but this is not what I want. Regular admin authentication would use default model of course. Thanks. -
How do I pass an item and an associated formset from the view to the template in Django?
I understand how to pass multiple items in the views to the template, you just pass multiple items in the context. I'm trying to learn to build a checklist app for learning and to have a formset for links associated to each item to learn. So you can like save multiple youtube instructional links to each item. But let's say that I am passing query of items over. And for each item has a formset created for it. How do I pass over the associated formset over with the item? Thru using chatgpt and google, I've come up with this def currentchecklist(request): items = Item.objects.filter(user=request.user, datecompleted__isnull=True) courses = request.user.checklist_courses.all() LinkFormSet = inlineformset_factory(Item, Link, fields=('url',), extra=1) formsets = [] for item in items: formsets.append((item, LinkFormSet(instance=item))) return render(request, "BJJApp/currentchecklist.html", {"items": items,"courses": courses, "formsets": formsets}) and then in the template, I have this {% for item, formset in formsets %} <div class="formset" id="linkform-{{ item.id }}" style="display: none;"> <label for="title">Links for {{ item.title }}</label> {{ formset.as_p }} </div> This code works so far to display the formset, I'm next working on saving the links. I just wanted to ask, is this the best way to access the item and associated formset? By using the … -
Django: Context not available when rendering a djang_tables2 table
I have a django_tables2 class: class DeviceTable(tables.Table): class Meta: template_name = "main/tables/bootstrap_custom.html" Then a base class: class BaseClass(SingleTableMixin, LoginRequiredMixin, PermissionRequiredMixin, FilterView): def get_context_data(self, **kwargs: Any) -> Dict[str, Any]: context = super().get_context_data(**kwargs) context["foo_base"] = "bar_base" return context And a view class: class ViewClass(BaseClass): table_class = DeviceTable def get_context_data(self, **kwargs: Any) -> Dict[str, Any]: context = super().get_context_data(**kwargs) context["foo_view"] = "bar_view" return context When rendering the "bootstrap_custom.html", the context doesn't contain the expected information. Neither "{{ foo_base }}" nor "{{ foo_view }}" are available in the context. Any idea? -
How to properly set up django channels and websocket
I'm trying to implement websocket and django channels. On frontend I have react and on backend django. I've installed channels and added it to INSTALLED_APPS in settings and I also added to settings.py ASGI_APPLICATION = 'VideoScreen.routing.application' CHANNEL_LAYERS = { 'default': { 'BACKEND': 'channels.layers.InMemoryChannelLayer', }, } The routing is as follows: websocket_urlPattern = [ path("ws/device-key/", DeviceCodeConsumer.as_asgi()), ] application = ProtocolTypeRouter( { "http": get_asgi_application(), "websocket": AuthMiddlewareStack(URLRouter(websocket_urlPattern)), } ) channel_routing = {"http.request": StaticFilesHandler()} And DeviceCodeConsumer is as follows: class DeviceCodeConsumer(WebsocketConsumer): def connect(self): self.group_name = 'device_key' async_to_sync(self.channel_layer.group_add)( self.group_name, self.channel_name ) print(f"Added to group {self.group_name}") # Debugging message # Accept the WebSocket connection self.accept() def receive(self, text_data): # Handle incoming JSON messages if needed print('RECIEVED: ' + text_data) text_data_json = json.loads(text_data) message = text_data_json['message'] async_to_sync(self.channel_layer.group_send)( self.group_name, { 'type': 'update_device_key', 'message': message } ) def update_device_key(self, event): message = event['message'] self.send(text_data=json.dumps({ 'type': 'update_device_key', 'message': message })) Thus I create group with name device_key and I want to add a message to that group when some code executes in django view and to notify the frontend about it. The view in django that I have is as follows: @login_required def device_edit_view(request, device_id): if device_id <= 0: device = Device() else: device = Device.objects.get(pk=device_id) if request.method == "POST": … -
Assistance Required: Vercel 404 Error While Deploying Django Application
I am trying to deploy a Django application on Vercel, but I keep encountering a 404: NOT_FOUND error. Below is a summary of my setup and the configuration I have used: vercel.json Configuration { "version": 2, "builds": [ { "src": "build_files.sh", "use": "@vercel/static-build", "config": { "distDir": "staticfiles_build" } }, { "src": "notes/wsgi.py", "use": "@vercel/python", "config": { "maxLambdaSize": "15mb", "runtime": "python3.9" } } ], "routes": [ { "src": "/(.*)", "dest": "notes/wsgi.py" }, { "src": "/static/(.*)", "dest": "/static/$1" } ] } What I Have Tried Verified that wsgi.py is properly configured and callable. Confirmed that static files have been collected and are stored in the staticfiles_build directory. Checked the routes and rewrites section of the vercel.json file to ensure proper mapping. Problem Description After deployment, I receive the 404: NOT_FOUND error when accessing the app. However, the build process completes successfully, and the deployment URL is generated. The Django application works perfectly on my local machine, but it seems something is missing in my deployment configuration for Vercel. Question What changes or additions do I need to make in my vercel.json file or deployment process to resolve this issue? Any guidance or suggestions would be greatly appreciated! Github link: https://github.com/Arnav613Gupta/Notes-Api.git vercel url … -
What is the best way to save preload data to prevent N+1 in NestedModelAdmin
We have an N+1 problem that our NestedModelAdmin has to deal with multiple databases. After working around it, we decided to fetch it beforehand in get_queryset. The drawback is that it will fetch all records in that table. class PODOrderAdmin(nested_admin.NestedModelAdmin): list_display = ('order_id', 'get_order_name', 'get_order_type', 'get_suppliers') def get_queryset(self, request): order_filter = request.GET.get('order') qs = super().get_queryset(request).prefetch_related( Prefetch( 'podlineitem_set', queryset=PODLineItem.objects.select_related('line_item') ), ).select_related('order') self.suppliers = list(PodSupplier.objects.only('id', 'name')) return qs def get_suppliers(self, obj): # Filter the pod_line_items by pod_order.id to match obj.id supplier_ids = [line_item.supplier_id for line_item in obj.podlineitem_set.all()] filtered_suppliers = [] if hasattr(self, 'suppliers'): filtered_suppliers = [supplier for supplier in self.suppliers if supplier.id in supplier_ids] else: filtered_suppliers = PodSupplier.objects.filter(id__in=supplier_ids) if filtered_suppliers: supplier_names = [(supplier.name,) for supplier in filtered_suppliers] return format_html_join('\n', '{}<br>', supplier_names) return None get_suppliers.short_description = 'Suppliers' admin.site.register(PODOrder, PODOrderAdmin) We tried to use queryset super().get_queryset(request) to reduce the number of records but it's not working, after checking some documents, it turns out get_queryset is called BEFORE paging happen qs = super().get_queryset(request).prefetch_related('podlineitem_set').select_related('order') pod_order_ids = qs.values_list('id', flat=True) self.pod_line_items = list(PODLineItem.objects.filter(pod_order_id__in=pod_order_ids)) self.suppliers = list(PodSupplier.objects.filter(id__in=[pod_line_item.supplier_id for pod_line_item in self.pod_line_items])) Another solution is to mimic paging but it only make code more complicated page = int(request.GET.get('p', 0)) limit = self.list_per_page subqueryset = queryset[page * limit: (page + 1) … -
Django - dynamically update a count model field when related objects are added or removed
I've tried to research this myself but can't figure it out so I'm hoping someone may be able to offer me some direction. I have the following 2 models: class Group(models.Model): short_name = models.CharField(max_length=10, primary_key=True) # company acronym full_name = models.CharField(max_length=200) learner_count = models.PositiveIntegerField(default=0) contract = models.ForeignKey(Contract, on_delete=models.CASCADE) course = models.ForeignKey(Course, on_delete=models.CASCADE) startDate = models.DateField() endDate = models.DateField() notes = models.TextField(blank=True, null=True) class Learner(models.Model): ... group = models.ForeignKey(Group, on_delete=models.CASCADE) Is it possible to update the learner_count field of Group dynamically as learners are added to, or removed from, a group? -
Queryset needs to be custom sorted into dictonary
can I have sort my queryset in custom order. By custom I mean for every ten products I receive, the first two should be featured (set to true), while the remaining eight should be unfeatured. This pattern should be repeated for each set of ten products and saved to a dictionary. The dictionary should save the data in the format of 'id':'score'. The database should be hited one time. Product.objects.all().order_by('rank', '-created').values('is_featured', 'id', 'rank') <EavQuerySet [{'is_featured': True, 'id': 19, 'rank': -20241209}, {'is_featured': True, 'id': 18, 'rank': -20241209}, {'is_featured': True, 'id': 17, 'rank': -20241209}, {'is_featured': True, 'id': 16, 'rank': -20241209}, {'is_featured': True, 'id': 15, 'rank': -20241209}, {'is_featured': False, 'id': 14, 'rank': -20241209}, {'is_featured': False, 'id': 13, 'rank': -20241209}, {'is_featured': False, 'id': 12, 'rank': -20241209}, {'is_featured': False, 'id': 11, 'rank': -20241209}, {'is_featured': False, 'id': 10, 'rank': -20241209}, {'is_featured': False, 'id': 9, 'rank': -20241209}, {'is_featured': False, 'id': 8, 'rank': -20241209}, {'is_featured': True, 'id': 7, 'rank': -20241206}, {'is_featured': True, 'id': 6, 'rank': -20241206}, {'is_featured': False, 'id': 1, 'rank': -20241128}, {'is_featured': True, 'id': 4, 'rank': -20241128}, {'is_featured': False, 'id': 5, 'rank': 0}, {'is_featured': False, 'id': 2, 'rank': 0}, {'is_featured': False, 'id': 3, 'rank': 0}]> -
Callback function not executing in Django Celery group when one task fails
I am working on a Django project that uses Celery to execute a group of tasks asynchronously. I noticed that when one of the tasks in the group fails, the callback function is not executed. Here is an overview of my setup: Task group definition: I use group from celery to run multiple tasks together. Callback function: A function should execute after all tasks in the group are completed, regardless of their success or failure. Problem: If any task in the group fails, the callback function is not triggered. @shared_task def fun1(): return "Task 1 completed successfully" @shared_task def fun22(): print('Task22') raise ValueError('Error') @shared_task def fun3(): return "Task 3 completed successfully" @shared_task(bind=True) def callback_task(results): print("Callback@@@@@@@@@@@@@@") processed_results = [] errors = [] for result in results: if isinstance(result, dict) and result.get("status") == "error": errors.append(result) else: processed_results.append(result) if errors: print(f"Errors encountered: {errors}") else: print(f"All tasks succeeded. Results: {processed_results}") return {"processed_results": processed_results, "errors": errors} @shared_task def error_handler(): print('Handler') return "error handler" @shared_task def fun2(): task_group = [ fun1.s(), fun22.s().on_error(error_handler.s()), fun3.s(), ] result = chord(task_group, callback_task.s()).apply_async() print(f"Group Id: {result.id}") return result.id Expected Behavior: Even if one task fails, the callback function should execute and handle the results or failures. Actual Behavior: When one task … -
Why does the _allowed_methods() function in django APIView return all http methods even though only GET is implemented?
I have a view being inherited by APIView and I have only implemented the GET method in it. class MyView(APIView): def get(self, request, id): # do something But when I call ClassInstance._allowed_methods() I get list of all the HTTP methods even though they are not implemented. Is there a way to only get the methods that are actually allowed in that class? -
TemplateDoesNotExist at /members/login/ registration/login.html
There are two similar questions on stackoverflow but they didn't help. I guess I got myself into trouble because I did a lot of copy and past from other projects. please help my settings.py: INSTALLED_APPS = [ ... 'core', 'members', ] TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] LOGIN_URL = 'members:login' LOGIN_REDIRECT_URL = '/' # Default landing page after login LOGOUT_REDIRECT_URL = '/' # Default landing page after logout # Email verification EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = "smtp.gmail.com" EMAIL_HOST_USER = "nadirspam3@gmail.com" EMAIL_HOST_PASSWORD = "xwie mpdm tmyu lyiw" EMAIL_PORT = 587 EMAIL_USE_TLS = True DEFAULT_FROM_EMAIL = "nadirspam3@gmail.com" my members app views file: def login_user(request): if request.method == 'POST': email = request.POST['email'] password = request.POST['password'] user = authenticate(request, username=email, password=password) if user is not None: login(request, user) # Redirect to a success page. return redirect('home') else: messages.success(request, 'Wrong username or password. Try again ..') return redirect('members:login') else: return render(request, 'members/login.html', {}) # so we can reference the user model as User instead of CustomUser User = get_user_model() ... my members app urls file: from . import views app_name = 'members' urlpatterns = [ path('login_user', views.login_user, name='login'), path('signup/', … -
Django + FactoryBoy -> Postgres not converting datetime to utc correctly
Okay, this is a weird one. I've got a Django model that I'm writing to Postgres via FactoryBoy for testing. contract = ContractFactory( effective_date=datetime.datetime(2023, 1, 1, tzinfo=pytz.timezone('US/Central')) ) I'm in US/Central, and I expect the database to store the object in UTC. The datetime in Postgres should be 2023-01-01 06:00:00 UTC since the difference between timezones is 6 hours. If I fetch the object back and print the date, it's wrong! 2023-01-01 05:51:00+00:00 If I fetch it from Postgres directly, it's also wrong: 2023-01-01 05:51:00.000000 +00:00 I checked the raw time in the database and it's correct. Postgres is running in a Docker container, and if I do a select now() the time is just fine in UTC. Where could this be coming from? -
Django Deployment on Azure: 504 Timeout and ROOT_URLCONF Error
I'm deploying a Django app to Azure using GitHub Actions, but encountering a 504 Gateway Timeout on the first request and an AttributeError: 'Settings' object has no attribute 'ROOT_URLCONF' error afterwards. I've followed the documentation and confirmed the ROOT_URLCONF setting in my settings.py. The app also downloads a machine learning model from Azure Blob Storage during startup. wsgi.py: import os from django.core.wsgi import get_wsgi_application settings_module = 'FakeNewsDetectorAPI.deployment' if 'WEBSITE_HOSTNAME' in os.environ else 'FakeNewsDetectorAPI.settings' os.environ.setdefault('DJANGO_SETTINGS_MODULE', settings_module) print("Before get_wsgi_application()") application = get_wsgi_application() print("After get_wsgi_application()") settings.py: import os from pathlib import Path print("Loading settings.py") BASE_DIR = Path(__file__).resolve().parent.parent DEBUG = False ALLOWED_HOSTS = ['fake-news-app22.azurewebsites.net','localhost', '127.0.0.1'] INSTALLED_APPS = [ 'django.contrib.contenttypes', 'django.contrib.staticfiles', 'django.contrib.auth', 'rest_framework', 'core.livenews', 'core.newsquiz', 'corsheaders', ] # Template configuration TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', ], }, }, ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', # Azure Blob Storage Settings AZURE_STORAGE_CONNECTION_STRING = os.environ.get('AZURE_STORAGE_CONNECTION_STRING') AZURE_STORAGE_CONTAINER_NAME = 'models' MODEL_BLOB_NAME = 'model_1_5_2.pkl' LOCAL_MODEL_PATH = os.path.join(BASE_DIR, 'models', 'model_1_5_2.pkl') # Database settings DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } CORS_ALLOWED_ORIGINS = [ "http://localhost:19000", "http://127.0.0.1:8000", "https://fake-news-app22.azurewebsites.net", ] CORS_ALLOW_CREDENTIALS = True REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.AllowAny', ], 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination', … -
django.db.utils.ProgrammingError: (1146, "Table 'test_db.sensori' doesn't exist")
i have this problem when i run my testcase with django and mysql. when i run manage.py test i've got this error. Found 1 test(s). Creating test database for alias 'default'... System check identified no issues (0 silenced). E ====================================================================== ERROR: test_sensor_list_view (gestioneSensori.tests.ViewsTest.test_sensor_list_view) ---------------------------------------------------------------------- Traceback (most recent call last): File "C:\Users\faboz\OneDrive\Desktop\ESAME_TWAI\Codice\venv\Lib\site-packages\django\db\backends\utils.py", line 105, in _execute return self.cursor.execute(sql, params) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\faboz\OneDrive\Desktop\ESAME_TWAI\Codice\venv\Lib\site-packages\django\db\backends\mysql\base.py", line 76, in execute return self.cursor.execute(query, args) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\faboz\OneDrive\Desktop\ESAME_TWAI\Codice\venv\Lib\site-packages\MySQLdb\cursors.py", line 179, in execute res = self._query(mogrified_query) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\faboz\OneDrive\Desktop\ESAME_TWAI\Codice\venv\Lib\site-packages\MySQLdb\cursors.py", line 330, in _query db.query(q) File "C:\Users\faboz\OneDrive\Desktop\ESAME_TWAI\Codice\venv\Lib\site-packages\MySQLdb\connections.py", line 265, in query _mysql.connection.query(self, query) MySQLdb.ProgrammingError: (1146, "Table 'test_db.sensori' doesn't exist") The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\faboz\OneDrive\Desktop\ESAME_TWAI\Codice\gestioneSensori\tests.py", line 10, in test_sensor_list_view sensore1 = Sensori.objects.create(id=1, tipo="Temperature", descrizione='desc', accuratezza=.0, precisione=.0, temperaturamin=0.0, temperaturamax=10.0, tolleranza=.1, tensioneesercizio=12.0, sensibilita=.2) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\faboz\OneDrive\Desktop\ESAME_TWAI\Codice\venv\Lib\site-packages\django\db\models\manager.py", line 87, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\faboz\OneDrive\Desktop\ESAME_TWAI\Codice\venv\Lib\site-packages\django\db\models\query.py", line 679, in create obj.save(force_insert=True, using=self.db) File "C:\Users\faboz\OneDrive\Desktop\ESAME_TWAI\Codice\venv\Lib\site-packages\django\db\models\base.py", line 892, in save self.save_base( File "C:\Users\faboz\OneDrive\Desktop\ESAME_TWAI\Codice\venv\Lib\site-packages\django\db\models\base.py", line 998, in save_base updated = self._save_table( ^^^^^^^^^^^^^^^^^ File "C:\Users\faboz\OneDrive\Desktop\ESAME_TWAI\Codice\venv\Lib\site-packages\django\db\models\base.py", line 1161, in _save_table results = self._do_insert( ^^^^^^^^^^^^^^^^ File "C:\Users\faboz\OneDrive\Desktop\ESAME_TWAI\Codice\venv\Lib\site-packages\django\db\models\base.py", line 1202, in _do_insert return manager._insert( ^^^^^^^^^^^^^^^^ File "C:\Users\faboz\OneDrive\Desktop\ESAME_TWAI\Codice\venv\Lib\site-packages\django\db\models\manager.py", line 87, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) … -
Callable default on unique field will not generate unique values upon migrating
Using Django/DRF to create a CRUD api I'm trying to use the RandomUUID to create a UUID from Postgres: from django.db import models from django.contrib.postgres.functions import RandomUUID class Year(models.Model): year_id = models.UUIDField( primary_key=True, default=RandomUUID, editable=False) When I run python manage.py makemigrations It gives me this error: Callable default on unique field year.year_id will not generate unique values upon migrating What am I doing wrong? I want Django ORM to tell Postgres to create the UUID. I don't want to use Python's uuid module. -
How I can let Django and FastAPI share the context (user) with the orm requests?
So I am writing an app with NiceGUI that is built on FastAPI and with Django. Right now I have no problem in the FastAPI to call the Django ORM in async to save in the database etc. The problem is that I am trying to share to the ORM requests that I do also the context in this way knows who is the user doing the various requests. I have implemented the login manually with aauthenticate and works (I save a token in the user model for the auth) but if I call a model like "Product" doens't have the request.context so I can't use https://github.com/jazzband/django-simple-history/ to save the author of the changes. I was thinking to create a custom auth middleware but how I can be sure that the ORM requests I will do will get that context? Another test I was doing was to create a RequestFactory and create a HTTPRequest manually with the session and login at the end but I have the same doubts. Another solution could be create a custom history and not use that package but I have some doubts that the issue will happen again for another reason. -
NoReverseMatch at /cart/
As I delete the item from the cart from the minus button the following error occurs Reverse for 'remove_cart' with arguments '(2,)' not found. 1 pattern(s) tried: ['cart/remove_cart/(?P<product_id>[0-9]+)/(?P<cart_item_id>[0-9]+)/$'] how can I fix it views.py of carts app def remove_cart(request, product_id, cart_item_id): cart = Cart.objects.get(cart_id = _cart_id(request)) product = get_object_or_404(Product, id=product_id) try: cart_item = CartItem.objects.get(product = product, cart = cart, id=cart_item_id) if cart_item.quantity > 1: cart_item.quantity -= 1 cart_item.save() else: cart_item.delete() except: pass return redirect('cart') urls.py file of the carts app path('remove_cart/<int:product_id>/<int:cart_item_id>/', views.remove_cart, name='remove_cart'), Cart.html file <div class="input-group-prepend"> <a href="{% url 'remove_cart' cart_item.product.id, cart_item.id %}" class="btn btn-light" type="button" id="button-plus"> <i class="fa fa-minus"></i> </a> </div> -
How to redirect a user to a mobile app (without browser) using Django (Universal Link / App Link) with .well-known configuration?
I am working on a Django-based web application, and I need to implement a feature where users are redirected to a mobile app directly (without using a browser) when they visit a specific URL. I want to use Universal Links (for iOS) or App Links (for Android) and ensure the redirect happens seamlessly. My setup: URL pattern: I am using a URL like /api/app/login/str:session_token/. Mobile app URL: I want to redirect users to a custom scheme URL like myapp://path/to/page/. Current view: This is my view that tries to handle the redirection: from django.http import HttpResponseRedirect from django.views import View class MobileRedirectView(View): def get(self, request, *args, **kwargs): # Custom mobile app URL (Universal Link for iOS or App Link for Android) mobile_app_url = "myapp://path/to/page/" # Redirecting to the mobile app return HttpResponseRedirect(mobile_app_url) The problem: When trying to redirect to the mobile app URL using the custom scheme (myapp://), I get this error: django.core.exceptions.DisallowedRedirect: Unsafe redirect to URL with protocol 'myapp'. I know that Django by default only allows redirects to http:// or https:// URLs, but I need to allow custom schemes like myapp://. Goal: I want the redirection to happen without using a browser (directly into the mobile app), and I … -
Django request.POST is empty
Im using django, allauth and dj-rest-auth. I'm implementing apple sign in. There is an issue with apple that I need multiple client_id's configured, its because you need a different one for ios en android/web. The issue is discussed here: https://github.com/pennersr/django-allauth/issues/2718 With also some solutions. Anyway, my question is not about that issue. I'm trying to implement a solution but django is not working like I expect it to. The issue is that that I cant access request.POST data. Which I think should be possible. # We add client_id when we make the post request, and we use it to filter for it def list_apps(self, request, provider=None, client_id=None): print(request.POST) --> returns empty dict # print(request.body) --> error # print(request.data) --> error assert False print(request.POST.get('client_id')) apps = super().list_apps(request=request, provider=provider, client_id=client_id) return apps request.body gives the error: django.http.request.RawPostDataException: You cannot access body after reading from request's data stream request.data gives the error: AttributeError: 'WSGIRequest' object has no attribute 'data' I would expect that I can access at least one of request.body, request.data or request.POST. Or else how can I access my posted data? -
Django admin - using dja have a style problem
i have an issue in the style admin of Django, when i enter on the web admin it show this: it show a broken style, with black lines I have this in my user_settings.py STATIC_URL = 'static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), ] STATIC_ROOT = os.path.join(BASE_DIR, 'static') MEDIA_ROOT = '/srv/media' MEDIA_URL = 'media/' The version of python is 3.12.3 and Django is 4.2 Any suggestions on how to resolve this problem would be greatly appreciated. -
CSRF Failed: CSRF token missing
I am writing my code in django python, Here is my view.py @csrf_exempt @api_view(['POST']) def Userlogin1(request): print('login working') username = request.data.get('username') password = request.data.get('password') user = authenticate(request=request._request, username = username, password = password) if user is not None: login(request._request, user) return Response({'message': 'login successful.'}, status=status.HTTP_200_OK) return Response({'error': 'Invalid credentials.', 'user':user, 'username':username, 'password':password}, status=status.HTTP_401_UNAUTHORIZED) when i run this on the postman, on first POST request, postman returning a correct response <'message': 'login successful.> but on second and further hit, post man throwing 403 error with this message { "detail": "CSRF Failed: CSRF token missing." } after removing the cookies from postman, it can run once but shows again same issue I disabled the csrf token added CSRF_TRUSTED_ORIGINS created custom -
Python project wrongly linked to Django
I'm pretty new with Django and I'm making a Flight Searching App with the Amadeus API. I've made it so, that it creates a .csv file with the cheapest flights from one destination to another. I now want to create a web application that lets the user enter cities and dates and displays the .csv file. I've made the HTML template but whenever I click on "Search" I get thrown a 404 Error. I think there is an error with urls.py or views.py but can't seem to figure it out. This is my views.py from django.shortcuts import render import requests import pandas as pd def search_flights(request): if request.method == 'POST': origen = request.POST.get('origen') destino = request.POST.get('destino') fecha_ida = request.POST.get('fecha_ida') fecha_regreso = request.POST.get('fecha_regreso') params = { "originLocationCode": origen, "destinationLocationCode": destino, "departureDate": fecha_ida, "returnDate": fecha_regreso, "adults": 1, "max": 7 } url = "https://test.api.amadeus.com/v2/shopping/flight-offers" access_token = "*********************" headers = { "Authorization": f"Bearer {access_token}" } response = requests.get(url, headers=headers, params=params) if response.status_code == 200: resultados = response.json().get("data", []) vuelos_data = [] for vuelo in resultados: price = vuelo.get("price", {}).get("total", "N/A") currency = vuelo.get("price", {}).get("currency", "N/A") for itinerary in vuelo.get("itineraries", []): for segment in itinerary.get("segments", []): departure = segment.get("departure", {}) arrival = segment.get("arrival", {}) carrier_code …