Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - Cannot make a celery worker and test transactions on test file without "You can't execute queries until the end of the 'atomic' block." error
Soo, here's the deal, Im creating a test in order to check if an improvement a made for performance is working or not, the improvements consists in making some signals logic an async task instead of an async process, I wanted to test this out but when I manually create a celery worker I get the django.db.transaction.TransactionManagementError: An error occurred in the current transaction. You can't execute queries until the end of the 'atomic' block. To have more context.. I'm avoiding creating a worker from the start because the pipeline does not use redis by default, or at least it avoids the celery creation, so I need to make one manually, but when I create the service I get the error def test_delete_optimal_deletion_time(self): """ Verifies that the `deletion logic` is under an acceptable running time. :return: """ # ... non-relevant code # Start Celery worker in a separate context to avoid nested atomic transactions with start_worker(celery_app, perform_ping_check=False): data_delete_start = time.time() og_org.delete() data_delete_end = time.time() data_total_test_end = time.time() data_total_test_time = data_total_test_end - data_total_test_start data_delete_time = data_delete_end - data_delete_start print("time to create test data: ", data_creation_time) print("time to delete test data: ", data_delete_time) print("time to run all test data: ", data_total_test_time) print("settings.CELERY_TASK_ALWAYS_EAGER: … -
How to test Django models against a DB without manage.py in a standalone package using pytest and GitHub Actions?
Context: I am developing a standalone Django package that is intended to be added to existing Django projects. This package includes Django models with methods that interact directly with a database. I want to write tests for these methods using pytest and pytest-django. I need to run these tests in a CI/CD environment, specifically using GitHub Actions. Problems Encountered: Database Setup: Since this is a standalone package, it does not include a manage.py file. This makes it challenging to run typical Django management commands like migrate to set up the database schema for testing. Table Creation: I encounter errors indicating that the table for my model does not exist because the necessary migrations are not applied. This is problematic because my tests need to interact with the database tables directly. Fixtures and Setup: I need to ensure the database tables are created and populated with initial data before the tests run. My attempts to use pytest fixtures and manually create database tables within the tests have not been successful. What I've Tried: Using pytest fixtures to set up the initial database state. Manually creating database tables within the test setup using direct SQL execution. Using the mixer library to populate … -
How do fetch the real time latitude and longitude in Django and display that as a tracking map in the template? [closed]
I want to fetch the real time latitude and longitude from the Kotlin. I just want to display the real time latitude and longitude as a map in a template by using a Django frame work how do I do this? can anyone solve this? -
getting errors with django templates
I am practicing Django lately and i get this error, can someone assist Invalid block tag on line 17: 'else', expected 'endblock'. Did you forget to register or load this tag? The template {% extends 'base.html' %} {% block content %} {% if not request.user.is_authenticated %} <div> <form method="POST"> {% csrf_token %} {% if error %} <span style="color: red">{{ error }}</span> {% endif %} <div> <input type="text" name="username" placeholder="username" /> </div> <div> <input type="password" name="password" placeholder="password" /> </div> <button type="submit">Login</button> </form> </div> {% else %} <div> <span style="color: red"> Already logged in. Would you like to <a href="/logout">logout?</a> </span> </div> {% endif %} {% endblock %} Everything corrrectly set -
Django Internationalization test error:Couldn't retrieve redirection page
I wrote a blog project in Django,in some pages i used loginrequierdmixin to make sure user is loged in but in test i got error in testing my project test: def test_get_profile_unauthenticated(self): response = self.client.get(self.profile_url) self.assertEqual(response.status_code, 302) expected_url = f"{self.register_url}?next={self.profile_url}" self.assertRedirects(response, expected_url) AssertionError: 302 != 200 : Couldn't retrieve redirection page '/accounts/register/': response code was 302 (expected 200) i print response: <HttpResponseRedirect status_code=302, "text/html; charset=utf-8", url="/accounts/register/?next=/en/accounts/profile/1/"> and my exepted url: /en/accounts/register/?next=/en/accounts/profile/1/ i asked chatGPT and here is response: def test_get_profile_unauthenticated(self): self.client.cookies.clear() with translation.override('en'): response = self.client.get(self.profile_url, HTTP_ACCEPT_LANGUAGE='en') self.assertEqual(response.status_code, 302) expected_url = f"{self.register_url}?next={self.profile_url}" self.assertRedirects(response, expected_url) -
When using the command docker-compose exec web python core/manage.py makemigration accountss I see the error "No module named 'accounts"
When using the command docker-compose exec web python core/manage.py makemigration accountss I see the error ModuleNotFoundError: No module named 'accounts' INSTALLED_APPS: enter image description here The error that is observed: Traceback (most recent call last): File "/code/core/manage.py", line 22, in <module> main() File "/code/core/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/usr/local/lib/python3.12/site-packages/django/core/management/__init__.py", line 442, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.12/site-packages/django/core/management/__init__.py", line 416, in execute django.setup() File "/usr/local/lib/python3.12/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/usr/local/lib/python3.12/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) ^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.12/site-packages/django/apps/config.py", line 178, in create mod = import_module(mod_path) ^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.12/importlib/__init__.py", line 90, in import_module return _bootstrap._gcd_import(name[level:], package, level) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "<frozen importlib._bootstrap>", line 1387, in _gcd_import File "<frozen importlib._bootstrap>", line 1360, in _find_and_load File "<frozen importlib._bootstrap>", line 1310, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 488, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1387, in _gcd_import File "<frozen importlib._bootstrap>", line 1360, in _find_and_load File "<frozen importlib._bootstrap>", line 1324, in _find_and_load_unlocked ModuleNotFoundError: No module named 'accounts' when makemigrations, I saw the above error -
Ajax is not working without refreshing the page
Ajax is not working without refreshig the page to make it work.I am coding an ecommerce website in django and need to show quantity of products in the cart but it dont show quantity without refresh the page. <script> $(document).on("click", "#add_button", function (e) { e.preventDefault(); $.ajax({ type: "POST", url: "{% url "add_cart" %}", data: { product_id: $("#add_button").val(), csrfmiddlewaretoken: "{{ csrf_token }}", action: "post", }, success: function (json) { {#console.log(json)#} document.getElementById("cart_quantity").textContent = json.qty }, error: function (xhr, errmsg, err) { } }); }) </script> class Cart: def __init__(self, request): self.session = request.session cart = self.session.get("cart_key") if cart is None: cart = self.session["cart_key"] = {} self.cart = cart def add(self, product): product_id = str(product.id) if product_id in self.cart: pass else: self.cart[product_id] = {"Price: ": str(product.price)} self.session.modified = True def __len__(self): return len(self.cart) def add_cart(request): cart = Cart(request) if request.POST.get("action") == "post": product_id = int(request.POST.get("product_id")) product = get_object_or_404(Product, id=product_id) cart.add(product=product) cart_quantity = cart.__len__() # response = JsonResponse({"product name: ": product.name}) response = JsonResponse({"qty: ": cart_quantity}) return response <p id="cart_quantity" >{{ cart|length }}</p> -
how can i dockerize my project with two app in seprate services
how can i dockerize my django project So that run two apps run in two diffrent services and one run with port:8000 and other one run with port:8001 sorry for my englisgh lol!! i tried making two dockerfile in each app # Use an official Python runtime as a parent image FROM python:3.8-slim # Set the working directory WORKDIR /usr/src/app # Copy the requirements file into the container COPY app1/requirements.txt ./ # Install any needed packages specified in requirements.txt RUN pip install --no-cache-dir -r requirements.txt # Copy the rest of the application code COPY app1/ . # Run the application CMD ["python", "manage.py", "runserver", "0.0.0.0:8000"] and for app2 # Use an official Python runtime as a parent image FROM python:3.8-slim # Set the working directory WORKDIR /usr/src/app # Copy the requirements file into the container COPY app2/requirements.txt ./ # Install any needed packages specified in requirements.txt RUN pip install --no-cache-dir -r requirements.txt # Copy the rest of the application code COPY app2/ . # Run the application CMD ["python", "manage.py", "runserver", "0.0.0.0:8001"] and one docker-compose.yml in root of project version: '3.8' services: app1: build: context: . dockerfile: app1/Dockerfile volumes: - ./app1:/usr/src/app ports: - "8000:8000" environment: - DJANGO_SETTINGS_MODULE=myproject.settings app2: build: context: … -
django-rest-framework-datatables server side FieldError: Cannot resolve keyword '0' into field
I am getting this error: django.core.exceptions.FieldError: Cannot resolve keyword '0' into field. Choices are: adjustmentsheader, authusergroups, authuseruserpermissions, brand, brand_modified_by_set, brandcategory, brandcategory_modified_by_set, company, company_modified_by_set, customer, customer_modified_by_set, customerbranch, customerbranch_modified_by_set, customerproduct, customerproduct_modified_by_set, customertype, customertype_modified_by_set, damageheader, date_joined, djangoadminlog, drfheader, drfheader_approved_by_set, drfheader_cancelled_by_set, drfheader_modified_by_set, email, first_name, id, is_active, is_staff, is_superuser, last_login, last_name, password, product, product_modified_by_set, productsupplier, productsupplier_modified_by_set, pulloutheader, pulloutheader_approved_by_set, receivingheader, receivingheader_modified_by_set, supplier, supplier_modified_by_set, username But I dont have a keyword '0' in my code: models.py class AuthUser(models.Model): first_name = models.CharField(max_length=150) last_name = models.CharField(max_length=150) email = models.CharField(max_length=254) serializers.py: class UsersSerializer(serializers.ModelSerializer): class Meta: model = models.AuthUser fields = ('first_name', 'last_name', 'email') urls.py router = routers.DefaultRouter() router.register(r'user_viewset', views.UsersViewSet) urlpatterns = [ path('api/', include(router.urls)), views.py class UsersViewSet(viewsets.ModelViewSet): queryset = models.AuthUser.objects.all().order_by("last_name") serializer_class = serializers.UsersSerializer template: <div class="table-responsive-xl"> <table class="table table-hover table-striped table-sm" id="table1"> <thead class="sticky-top top-0"> <tr> <th>Item Code</th> <th>Customer Barcode</th> <th>Brand</th> <th>Category</th> <th>Description</th> <th>Customer Price</th> </tr> </thead> </table> </div> </div> <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script> <script src="//cdn.datatables.net/2.0.8/js/dataTables.min.js"></script> <script> $(document).ready(function () { $('#table1').DataTable({ "serverSide": true, "ajax": "../api/product_viewset/?format=datatables" }); }); </script> I dont have a keyword '0' in my model or database. Where could it be coming from? -
WebSocket Channels in Django not connecting
I'm struggling why still insist not being connected my WebSocket using Django, I've used laragon as Mysql and I just used my local database, and I just want to try first before saving to database it if it works or not but I getting an error. Did I forgot something? so I have this format and I have error in my html url on line const chatSocket = new WebSocket(url) html $(document).ready(function () { let url = `ws://${window.location.host}/ws/socket-server/` const chatSocket = new WebSocket(url) chatSocket.onmessage = function(e){ let data = JSON.parse(e.data) console.log('Data:', data) if(data.type === 'chat'){ let messages = document.getElementById('messages') messages.insertAdjacentHTML('beforeend', `<div> <p>${data.message}</p></div>`) } } }); main/routing.py from django.urls import re_path from main import consumers websocket_urlpatterns = [ re_path(r'ws/socket-server/', consumers.ChatConsumer.as_asgi()) ] main/consumers.py import json from channels.generic.websocket import WebsocketConsumer from asgiref.sync import async_to_sync class ChatConsumer(WebsocketConsumer): def connect(self): self.room_group_name = 'test' async_to_sync(self.channel_layer.group_add)( self.room_group_name, self.channel_name ) self.accept() def receive(self, text_data): text_data_json = json.loads(text_data) message = text_data_json['message'] async_to_sync(self.channel_layer.group_send)( self.room_group_name, { 'type':'chat_message', 'message':message } ) def chat_message(self, event): message = event['message'] self.send(text_data=json.dumps({ 'type':'chat', 'message':message })) tev/asgi.py import os from django.core.asgi import get_asgi_application from channels.routing import ProtocolTypeRouter, URLRouter from channels.auth import AuthMiddlewareStack import main.routing os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'tev.settings') application = ProtocolTypeRouter({ 'http':get_asgi_application(), 'websocket':AuthMiddlewareStack( URLRouter( main.routing.websocket_urlpatterns ) ) }) settings.py … -
Django why is my image refusing to upload
For my website- I implemented a profile pic you can add to your profile which works: models.py class Profileuser(models.Model): owner = models.OneToOneField(User, on_delete=models.CASCADE) name = models.CharField(max_length=50) tagline = models.CharField(max_length=100) bio = models.TextField(blank=True) website = models.URLField(blank=True) profile_pic = models.ImageField(upload_to="profiles/", blank=True) def __str__(self): return f"{self.id} | {self.name}" views.py class ProfileuserCreateView(LoginRequiredMixin, CreateView): model = Profileuser fields = ['name', 'profile_pic', 'tagline', 'bio', 'website'] success_url = reverse_lazy('recipes-home') def form_valid(self, form): form.instance.owner = self.request.user return super(ProfileuserCreateView, self).form_valid(form) Urls.py if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) However- when I tried to implement adding photos to my recipe posts- the images just don't upload, I can see the folder sitting empty models.py class Recipe(models.Model): title = models.CharField(max_length=100) recipe_image = models.ImageField(upload_to="imagerecipes/", blank=True) ingredients = models.TextField() description = models.TextField() author = models.ForeignKey(User, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def get_absolute_url(self): return reverse('recipes-detail', kwargs={"pk": self.pk}) def __str__(self): return self.title views.py class RecipeCreateView(LoginRequiredMixin, CreateView): model = models.Recipe fields = ['title', 'recipe_image', 'ingredients', 'description'] def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) I don't understand why one works but the other doesn't as the code is virtually the same- if I upload via admin- it does work, I have also tested profile pictures and it still allows me to upload them. No error … -
How to Avoid Duplicate Validation When Creating Django Model Instances Manually and via Forms?
I’m new to Django and I need some help with model validation. Here’s what I’m trying to figure out: When I create new instances using forms, I know that calling is_valid on the form automatically runs the full_clean method for validation. After that, I just call save on the form. But when I create new instances manually, I need to call full_clean manually before calling save. I saw online that some people suggest overriding the save method in the model to ensure custom validation always runs, like this: def save(self, *args, **kwargs): self.full_clean() super().save(*args, **kwargs) This works fine when I’m creating instances manually, but it seems to call full_clean twice when I use forms (once during is_valid and once during save). This feels redundant and probably not efficient. My Question: What’s the best way to make sure my custom validation runs in Django models both when creating instances manually and via forms, without calling full_clean twice? Any advice or best practices would be really appreciated! Thanks a lot! -
python django library project
i have been making libraries with many tutorials and tips but couldnt find one that really suited my project can anybody give me suggestions on it i would really apreciate where to find some proper tutorials that can show me how to make an python django library that allows me to have two roles vendor and librarian, vendor sells books can edit the names of the books and basic things like that and librarian can search up the books and find the one he/she will like well i have tried multiple tutorials which did pretty well but not up to the level i need for -
Problem connecting to BlueStacks from the Django project using ADB
1. Creating a Django project: 2. Preparation of forms (models.py): enter image description here 3. Preparation of presentations (views.py): enter image description here enter image description here enter image description here 4. Set up templates (templates/bot_controller.html): enter image description here ADB settings: adb connect 127.0.0.1:5555 adb devices CSP CORS settings.py: enter image description here The full project link: https://github.com/MoYonsei/AbotZ/tree/master Attempts to solve the problem: Made sure that ADB is working properly and BlueStacks is connected. Updated the CSP and CORS settings to allow loading the emulator inside the framework. Tried using different addresses in the iframe such as localhost and 127.0.0.1. -
Why is my AWS EC2 instance Supervisor failing?
I'm deploying a Django API I've named "ScientistBirthYear" to AWS EC2 following these instructions, including using the gunicorn.conf code, but modifying it to account for my virtual environment's name, project name, and X.wsgi:application from my project. At 24:50, the presenter's instance shows gunicorn running, where mine has failed multiple times. I've come across several solutions online, and none of them have worked. Here's the last several entries of my /var/log/supervisor/supervisord.log: 2024-07-16 22:56:07,174 INFO spawned: 'gunicorn' with pid 1861 2024-07-16 22:56:07,281 WARN exited: gunicorn (exit status 0; not expected) 2024-07-16 22:56:09,284 INFO spawned: 'gunicorn' with pid 1866 2024-07-16 22:56:09,391 WARN exited: gunicorn (exit status 0; not expected) 2024-07-16 22:56:12,396 INFO spawned: 'gunicorn' with pid 1871 2024-07-16 22:56:12,502 WARN exited: gunicorn (exit status 0; not expected) 2024-07-16 22:56:12,503 INFO gave up: gunicorn entered FATAL state, too many start retries too quickly 2024-07-16 22:56:25,588 CRIT Supervisor is running as root. Privileges were not dropped because no user is specified in the config file. If you intend to run as root, you can set user=root in the config file to avoid this message.> 2024-07-16 22:56:25,589 INFO Included extra file "/etc/supervisor/conf.d/gunicorn.conf" during parsing 2024-07-16 22:56:25,589 INFO RPC interface 'supervisor' initialized 2024-07-16 22:56:25,589 CRIT Server 'unix_http_server' … -
Testing services with django-pytest: User.DoesNotExist
I'm trying to test functions with pytest. It returns No tables found. While i see migrate output and test sqlite3 database. authentication/tests/test_services.py::test_register_user - users.models.User.DoesNotExist: User matching query does not exist. My conftest is: import os import pytest from django.core.management import call_command from rest_framework.test import APIClient from users.models import User @pytest.fixture(scope='session') def delete_db(): print("delete_db") try: os.remove("db_test.sqlite3") except Exception: pass @pytest.fixture(scope='session') def django_db_setup(delete_db, django_db_blocker): print("django_db_setup") with django_db_blocker.unblock(): call_command('sqlflush') with django_db_blocker.unblock(): call_command('migrate', '--noinput') yield @pytest.fixture(autouse=True, scope='session') # def user(data, django_db_blocker): def user(django_db_setup, django_db_blocker): with django_db_blocker.unblock(): user = User.objects.create( name='Test user', email='test@eaxmple.com', password='Password' ) @pytest.fixture(autouse=True, scope='session') def guest_client(): return APIClient() @pytest.fixture(autouse=True, scope='session') def user_client(guest_client, django_db_blocker): with django_db_blocker.unblock(): client = APIClient() user = User.objects.get(email='test@example.com') response = guest_client.post('/api/v1/auth/login/', data={"email": user.email, "password": "Adminqwe1,"}) token = str(response.json().get("access")) client.credentials(HTTP_AUTHORIZATION="Bearer " + token) return client Test user from fixture is created my test file is: import pytest from authentication.services import register_user @pytest.mark.django_db() def test_register_user(guest_client): data = {'email': 'test1@example.com', 'name': 'Test user', 'password': 'Adminqwe1.'} user = register_user(data=data) assert user.name == 'Test user' assert user.check_password('Admninqwe1.') is True tested function: from users.models import User def register_user(data): password = data.pop("password") user = User.objects.create(**data) user.set_password(password) user.save() return user settings_test: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db_test.sqlite3', } } pytest.ini: [pytest] DJANGO_SETTINGS_MODULE … -
Vuetify2 styles not working properly with Django
I'm trying to add vue + vuex + vuetify framework to my django project I have installed node.js and yarn, then prescribed the commands - yarn global add @vue/cli and vue create client in project root dir, and modified the config files: package.json { "name": "client", "version": "0.1.0", "private": true, "scripts": { "serve": "vue-cli-service serve", "build": "vue-cli-service build", "dev": "vue-cli-service build --dest=../../static/builds/dev --mode=development --watch" }, "dependencies": { "axios": "^0.21.4", "copy-to-clipboard": "^3.3.1", "core-js": "^3.6.5", "vue": "^2.6.11", "vue-modal-dialogs": "^3.0.0", "vue-router": "^3.2.0", "vuedraggable": "^2.24.3", "vuetify": "2.6.5", "vuex": "^3.4.0" }, "devDependencies": { "@vue/cli-plugin-babel": "~4.5.0", "@vue/cli-service": "~4.5.0", "sass": "~1.32.0", "sass-loader": "^10.0.0", "vue-cli-plugin-vuetify": "~2.4.2", "vue-template-compiler": "^2.6.11", "vuetify-loader": "^1.7.0" } } main.js import Vue from 'vue' import App from './App.vue' import router from './router' import store from './store' import vuetify from './plugins/vuetify' Vue.config.productionTip = false new Vue({ router, store, vuetify, render: h => h(App) }).$mount('#app') vuetify.js import Vue from 'vue' import Vuetify from 'vuetify/lib/framework' import ru from 'vuetify/es5/locale/ru' import "vuetify/dist/vuetify.min.css"; Vue.use(Vuetify); export default new Vuetify({ lang: { locales: {ru}, current: 'ru' } }); then I ran the yarn dev command and plugged the assembled files into the existing html from static <script defer="defer" src="{% static 'builds/dev/js/app.js'%}"></script> <div class="tab-pane fade" id="structure-tab-content" role="tabpanel" aria-labelledby="structure-tab"> <div id="app"></div> </div> But vuetify … -
Error When Publishing to LinkedIn via API - Code: 422
I'm encountering an error when publishing to LinkedIn via their API. Here are the details: Error code: 422 Response: { "message": "ERROR :: /author :: \"urn:li:person:aba2390d-7792-4cb2-ad6b-e116d9783606\" does not match urn:li:company:\\d+|urn:li:member:\\d+\n", "status": 422 } Context Request type: POST API URL: https://api.linkedin.com/v2/ugcPosts Payload: { "author": "urn:li:person:aba2390d-7792-4cb2-ad6b-e116d9783606", "lifecycleState": "PUBLISHED", "specificContent": { "com.linkedin.ugc.ShareContent": { "shareCommentary": { "text": "Here is the content of my post." }, "shareMediaCategory": "ARTICLE", "media": [ { "status": "READY", "originalUrl": "https://www.example.com/article", "title": { "text": "Example Article" } } ] } }, "visibility": { "com.linkedin.ugc.MemberNetworkVisibility": "PUBLIC" } } Here is my code: def linkedin_login(request): auth_url = f"https://www.linkedin.com/oauth/v2/authorization?response_type=code&client_id={settings.LINKEDIN_CLIENT_ID}&redirect_uri={settings.LINKEDIN_REDIRECT_URI}&scope=w_member_social" return redirect(auth_url) def linkedin_callback(request): if 'error' in request.GET: error = request.GET.get('error') error_description = request.GET.get('error_description') return render(request, 'error.html', {'error': error, 'description': error_description}) code = request.GET.get('code') if not code: return render(request, 'error.html', {'error': 'No code provided'}) # Exchange the code for a token token_url = 'https://www.linkedin.com/oauth/v2/accessToken' data = { 'grant_type': 'authorization_code', 'code': code, 'redirect_uri': settings.LINKEDIN_REDIRECT_URI, 'client_id': settings.LINKEDIN_CLIENT_ID, 'client_secret': settings.LINKEDIN_CLIENT_SECRET } response = requests.post(token_url, data=data) if response.status_code != 200: return render(request, 'error.html', {'error': 'Failed to obtain access token', 'description': response.text}) token_data = response.json() access_token = token_data.get('access_token') expires_in = token_data.get('expires_in', 3600) # default to 1 hour if not provided # Generate a unique identifier for this token linkedin_id = … -
Connect Django to Docker MS SQL
I have requirements: Python 3.11.9 ( Windows https://github.com/pyenv/pyenv ) latest version of Django (5.0.7.) MS SQL 2019 To create a simple REST app with Django AUTH logic. As I have local installed Python and the packages in .env folder I use MS SQL 2019 in Docker. The app works if I use default default SQLite DB engine. After changing it to mssql-django (https://pypi.org/project/mssql-django/) I get: django.db.utils.InterfaceError: ('IM002', '[IM002] [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified (0) (SQLDriverConnect)') requirements.txt asgiref Django django-cors-headers djangorestframework djangorestframework-simplejwt PyJWT pytz sqlparse python-dotenv pyodbc mssql-django .env DB_HOST=localhost DB_PORT=1433 DB_USER=mssql DB_NAME=friendly_beaver DB_PASSWORD=admin(!)pass settings.py DATABASES = { 'default': { # 'ENGINE': 'django.db.backends.sqlite3', # 'NAME': BASE_DIR / 'db.sqlite3', 'ENGINE': 'mssql', 'NAME': os.getenv('DB_NAME'), 'USER': os.getenv('DB_USER'), 'PASSWORD': os.getenv('DB_PASSWORD'), 'HOST': os.getenv('DB_HOST'), 'PORT': os.getenv('DB_PORT'), 'OPTIONS': { 'driver': 'ODBC Driver 19 for SQL Server', }, } } Docker is up and running (https://hub.docker.com/r/microsoft/mssql-server): docker run -e "ACCEPT_EULA=Y" -e "MSSQL_SA_PASSWORD=admin(!)pass" -p 1433:1433 -d mcr.microsoft.com/mssql/server:2019-latest Any assist would be grateful. -
How to Properly Handle Character Encoding in Django Database Dump?
I'm working on a Django project and I've encountered a character encoding issue when dumping my sqlite3 database to a JSON file. The database contains special characters such as accented letters (e.g., "França", "Bélgica"), but when I dump the data, these characters are not displayed correctly. Im trying to migrate the data from sqlite3 to MySQL. Currently, my dump file contains incorrectly encoded characters like: "França" instead of "França" "Bélgica" instead of "Bélgica" "EslovÛnia" instead of "Eslovênia" "Ge¾rgia" instead of "Geórgia" Could someone please guide me on how to ensure the Django dumpdata command creates a JSON file with the correct UTF-8 encoding from the start? When i execute the commando: python manage.py dumpdata > db_data.json, my JSON is shown as "UTF-16 LE" Here are the steps I've taken so far: I've ensured my database (MySQL) is set to UTF-8 encoding. I've tried using Python scripts to manually fix the encoding issues after dumping the data, but the problem persists. My goal is to have the JSON dump file correctly display all characters. -
Problems with changing the status from pending to rejected/approved
Okay, so I am a django developer but also I am beginner I do not know much about js but I tried to submit the data with clicking on the button The project is about approve or reject orders in the panel of the owner of the shop Things in django admin went well and I can change it through the admin interface, but I also want it to be user friendly so the owner of the shop can approve the request by clicking on approve and reject it by clicking on the cancel button. In conclusion, i want to make a logic that whenever the owner click on approve button the pending in the database changes to approved and the same for reject When I click on the button(reject or approval) it gives me 405 error My views.py: def update_appointment_status(request: HttpRequest): timeslice_id = request.GET.get('timeslice_id') status = request.GET.get('status') timeslice = get_object_or_404(TimeSlice, id=timeslice_id) if status == 'approve': timeslice.approve() elif status == 'refuse': timeslice.refuse() return JsonResponse({'success': True}) My js codes: $(document).ready(function() { // Approve button click handler $('.approve-btn').click(function(event) { event.preventDefault(); var timesliceId = $(this).data('id'); $.ajax({ url: '/approve/', // Adjust the URL to your specific endpoint type: 'POST', data: { 'timeslice_id': timesliceId, 'csrfmiddlewaretoken': … -
How to Upload songs in python/django MYsql or Sqlite .?
I want to upload a Media like Song , Video , and other media file on my music player app how can store in my django project file called "model.py" what data type should i give to store that king of files i want to store the file in my database in backend to store the songs comming or requesting from user how can i upload the songs -
Prevent duplicates when filtering on prefetch_related
I have two models: Seller and Product. Each product has a foreignKey to a seller. So each product only has one seller, but a seller can be related to many products. This is the ForeignKey in my Product-Class: seller = models.ForeignKey( Seller, on_delete=SET_NULL, null=True, related_name="products", ) Now I try to query all Sellers and have the related products for each seller with them. sellers = ( Seller.objects.filter( ..doing some filtering ).prefetch_related("products").filter(products__branch=current_branch) ) By doing this, my sellers has multiple entries for many sellers as I am filtering on the prefetche_related products resulting in a join inside the database-query. What would be the best way to end up with a List of Sellers, each of them having their list of products with them? Without duplicates. I still need to filter on the products as I don't want all the products to be queried. -
Django - get value of a form textinput on onchange event
I am using this to get the ID and the value of a select item in a form in django with the onchange event: class forms_bdc(forms.ModelForm): [...] bdc_description_1 = forms.ModelChoiceField( widget=forms.Select(attrs={'id': 'editable-select-2','onchange': 'populate_selected_product(this.id,this.value)'}),empty_label=None ) I am trying to do the same with a TextInput widget. The ID is returned as expected but I don't know how to get the value : bdc_quantity_1 = forms.CharField( widget=forms.widgets.TextInput(attrs={'onchange':'calculate_price_of_product(this.id,this.value)'})) I also tried with this.text instead of this.value but no success. Thanks -
How to show/hide a button by comparing if logged by asset owner check database privilege asset owner whether add asset value is 'on' or 'off'
My asset_list html is like this {% if user_role == 'admin' %} {% include 'asset_mng/admin_sidebar.html' %} {% elif user_role == 'asset_owner' %} {% include 'asset_mng/asset_owner_sidebar.html' %} {% endif %} <div class="right"> <div class="search-container"> <input type="text" id="searchInput" placeholder="Search by AssetName..." aria-label="Search"> <button class="add-button" aria-label="Add Asset" id="addUserButton"><i class="fas fa-plus"></i> Add</button> </div> login database is like this , with roles admin and user class UserDetails(models.Model): username = models.CharField(max_length=100, unique=True) password = models.CharField(max_length=100) # Ideally, this should be hashed role = models.CharField(max_length=45) login view.py def asset_login(request): if request.method == 'POST': username = request.POST['username'] password = request.POST['password'] user = authenticate(request,username=username,password=password) try: user = UserDetails.objects.get(username=username, password=password) if user is not None: request.session['username'] = user.username request.session['role'] = user.role #pass the user's role to the template if user.role == 'admin': return redirect('admin_dashboard') elif user.role == 'head': return redirect('head_dashboard') elif user.role == 'asset_owner': return redirect('asset_owner_dashboard') elif user.role == 'ciso': return redirect('ciso_dashboard') else: messages.error(request, 'Unknown user role') else: messages.error(request, 'Invalid username or password') except UserDetails.DoesNotExist: messages.error(request, 'Invalid username or password') return render(request, 'asset_mng/asset_mng.html') views for asset list def asset_list(request): users = Asset_Table.objects.all() return render(request, 'asset_mng/asset_pro.html', {'users': users}) I have 2 roles Admin and User , when Admin is logged in, I want to show admin side bar and if user …