Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
AttributeError: module 'django.db.migrations' has no attribute 'RunPython'
I get this error whenever I try running my server, migrating, or running any Django commands. All my previous Django projects also show the same error, but they were working fine before. I tried updating Django, but it's still showing the same error. This is the error I am getting. Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Python310\lib\threading.py", line 1010, in _bootstrap_inner self.run() File "C:\Python310\lib\threading.py", line 947, in run self._target(*self._args, **self._kwargs) File "C:\Python310\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Python310\lib\site-packages\django\core\management\commands\runserver.py", line 115, in inner_run autoreload.raise_last_exception() File "C:\Python310\lib\site-packages\django\utils\autoreload.py", line 87, in raise_last_exception raise _exception[1] File "C:\Python310\lib\site-packages\django\core\management\__init__.py", line 381, in execute autoreload.check_errors(django.setup)() File "C:\Python310\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Python310\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Python310\lib\site-packages\django\apps\registry.py", line 91, in populate app_config = AppConfig.create(entry) File "C:\Python310\lib\site-packages\django\apps\config.py", line 123, in create mod = import_module(mod_path) File "C:\Python310\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 1006, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 688, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 883, in exec_module File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed File "C:\Python310\lib\site-packages\django\contrib\auth\apps.py", line 8, in … -
django-q task manager is not working correctly if there is no request in system
Anyone using django-q task scheduler: https://github.com/Koed00/django-q (Not the database related Q library) I'm scheduling cron task which will trigger some jobs. But my main problem is, tasks starts working 30-60 mins later than i scheduled if there is no new request in server. After lots time when i refresh page , it's starts running immediately. Even i set timeout low to try if it's gonna work but it didn't. Is there any conf that i can set for this issue ? Q_CLUSTER = { "name": "Cluster", "orm": "default", # Use Django's ORM + database for broker 'workers': 2, 'timeout': 240, 'retry': 300, } -
Getting "IntegrityError FOREIGN KEY constraint failed" when i am trying to generate the invoice from booking table
I am trying to generate an invoice from the booking table. I have created a separate table for invoices and declared a foreign key for the booking table and package too. But whenever I try to generate an invoice it gives a Foreign key constraint. Here is my models file models.py class Invoice(models.Model): photographer = models.ForeignKey(Photographer,on_delete=models.CASCADE) package = models.ForeignKey(Package,on_delete=models.CASCADE) booking = models.ForeignKey(Booking,on_delete=models.CASCADE) extra_amt = models.IntegerField(null=True,blank=True) total_amt = models.IntegerField(null=True,blank=True) payment_status = models.CharField(max_length=100) created_at = models.DateField(auto_now_add=True) updated_at = models.DateField(auto_now=True) Here is the view that I created to generate invoice views.py def generate_invoice(request,id): photographer = Photographer.objects.get(user=request.user) booking = Booking.objects.get(id=id) packages = Package.objects.filter(photographer=photographer) if request.method == "POST": package_get = request.POST.get('package') extra_amt = request.POST.get('extra_amt') payment_status = request.POST.get('payment_status') invoice = Invoice( photographer = photographer, booking = booking, package_id = package_get, extra_amt = extra_amt, payment_status = payment_status, ) invoice.save() messages.success(request,'Invoice generated Successfully') return redirect('view_booking') context = { 'package':packages, } return render(request,'customadmin/photographer/generate_invoice.html',context) When I click on submit button to generate url it shows below error on this url http://localhost:8000/customadmin/bookings/generate-invoice/5/ IntegrityError at /customadmin/bookings/generate-invoice/5/ FOREIGN KEY constraint failed Request Method: POST Request URL: http://localhost:8000/customadmin/bookings/generate-invoice/5/ Django Version: 4.0 Exception Type: IntegrityError Exception Value: FOREIGN KEY constraint failed Exception Location: /home/shreyas/project/mainPhotographer/venv/lib/python3.8/site-packages/django/db/backends/sqlite3/base.py, line 416, in execute Python Executable: /home/shreyas/project/mainPhotographer/venv/bin/python Python Version: 3.8.10 Python … -
Collectstatic fails with Django 4.0 [duplicate]
I am unable to run python manage.py collectstatic with Django 4.0. Error is ....min.js references a file which could not be found .....min.js.map I believe this is due to Django 4.0 collectstatic having added manifest_storage: https://docs.djangoproject.com/en/4.0/ref/contrib/staticfiles/ This leads to error. I try to disable this by WHITENOISE_MANIFEST_STRICT = False but this does not have any affect. I run site on Heroku so I have django_heroku.settings(locals()) at end of settings.py file. Tried to fix this by adding an empty file with touch to location indicated in error message. Error is gone, but next .map-file is missing. No sense to manually fix. The question - how to disable finding .map -files in manage.py collectstatic in Heroku-setup? -
How to close a socket and open it again in tornado
I have a tornado websocket class WSHandler(tornado.websocket.WebSocketHandler): def open(self): print ('new connection') global hr_values_list hr_values_list=[] def on_message(self, message): value=getvalue(message) if value: self.write_message(json_encode(int(value))) hr_values_list.append(value) def on_close(self): avg=int(np.mean(hr_values_list)) print ('connection closed',len(hr_values_list),avg) def check_origin(self, origin): return True application = tornado.web.Application([ (r'/websocket', WSHandler), ]) First i want to write value to browser console or page, when on_close action is taken . Like is there a way write_message as in on_message function. Second, i want to open the connection again after connection is closed function defsocket(){ var socket = new WebSocket('ws://localhost:8888/websocket'); return socket; }; socket= defsocket(); $(document).ready(function () { let video = document.getElementById('video'); let canvas = document.getElementById('canvas'); let context = canvas.getContext('2d'); let draw_canvas = document.getElementById('detect-data'); let draw_context = draw_canvas.getContext('2d'); let image = new Image(); if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) { navigator.mediaDevices.getUserMedia({video: true}).then(function (stream) { video.srcObject = stream; video.play(); }); } function drawCanvas() { context.drawImage(video, 0, 0, 500, 350); sendMessage(canvas.toDataURL('image/png')); } document.getElementById("start-stream").addEventListener("click", function () { drawCanvas(); }); document.getElementById("stop-stream").addEventListener("click", function () { socketClose(); }); function sendMessage(message) { socket.send(message); } function socketClose() { socket.close(); } socket.onmessage = function (e) { console.log(e) document.getElementById("pid").innerHTML = e.data; drawCanvas(); }; }) So what i want is that when i click on start-stream, connection start and value start displaying in html page. This is … -
Cannot install mikasa package in python django using pycharm
I am trying to install mikasa package using pycharm but can't find a solution to my specific problem. I have the msv c++ build tools installed (installed in C://) I have tried using the conda commands and upgrading pip. my python project directory is D:/... (sys env path is properly setup) I am getting the below error log and having a hard time figuring out something. Please help. pip install misaka Collecting misaka Using cached misaka-2.1.1.tar.gz (125 kB) Preparing metadata (setup.py) ... done Requirement already satisfied: cffi>=1.0.0 in d:\new folder\dev\projects\python\lectures\django\social_network_project\venv\lib\site-packages (from mi saka) (1.15.0) Requirement already satisfied: pycparser in d:\new folder\dev\projects\python\lectures\django\social_network_project\venv\lib\site-packages (from cffi >=1.0.0->misaka) (2.21) Using legacy 'setup.py install' for misaka, since package 'wheel' is not installed. Installing collected packages: misaka Running setup.py install for misaka ... error ERROR: Command errored out with exit status 1: command: 'd:\new folder\dev\projects\python\lectures\django\social_network_project\venv\scripts\python.exe' -u -c 'import io, os, sys, setuptools , tokenize; sys.argv[0] = '"'"'C:\\Users\\mmaruf\\AppData\\Local\\Temp\\pip-install-kku9tl3j\\misaka_f73fdbf85a244e3d8b5c5c24be73b7ff\\setup.py'"'"'; __file__='"'"'C:\\Users\\mmaruf\\AppData\\Local\\Temp\\pip-install-kku9tl3j\\misaka_f73fdbf85a244e3d8b5c5c24be73b7ff\\setup.py'"'"';f = getattr(tokeni ze, '"'"'open'"'"', open)(__file__) if os.path.exists(__file__) else io.StringIO('"'"'from setuptools import setup; setup()'"'"');code = f.read().repl ace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record 'C:\Users\mmaruf\AppData\Local\Temp\pip-re cord-p6erxmt6\install-record.txt' --single-version-externally-managed --compile --install-headers 'd:\new folder\dev\projects\python\lectures\django\s ocial_network_project\venv\include\site\python3.10\misaka' cwd: C:\Users\mmaruf\AppData\Local\Temp\pip-install-kku9tl3j\misaka_f73fdbf85a244e3d8b5c5c24be73b7ff\ Complete output (25 lines): running install d:\new folder\dev\projects\python\lectures\django\social_network_project\venv\lib\site-packages\setuptools\command\install.py:34: SetuptoolsDeprec ationWarning: setup.py install is deprecated. Use build and … -
unable to install requirements.txt on new computer
After getting a new pc, with a different user name, I can't install the requirements.txt in my python project, which has now a new path to the project folder because of the new windows user. I am developing on VS code. The project has a virtual environment, venv, that loads without problem. But when trying to load the requirement.txt I am getting this error: Fatal error in launcher: Unable to create process using '"c:\users\olduser\python\project\venv\scripts\python.exe" "C:\Users\newuser\Python\project\venv\Scripts\pip.exe" -m install -r requirements.txt': The system cannot find the file specified. Python and pip are correctly defined in the environmental variables, the problem is (I think) that it is looking the python location from the previous PC -
How do i store order in my database after payment is successful in django
i'm a beginner, i am working on the e-commerce app. i want to do something that if the user payment is successful, an order would be created and stored in the database. i finally have found a way of intergrating the payment gateway and when the transcation is successful, it redirect to a success page. the problem i have here is how to create the order when the payment is successfull here are my codes <script> const API_publicKey = "<ADD YOUR PUBLIC KEY HERE>"; function payWithRave() { var x = getpaidSetup({ PBFPubKey: API_publicKey, customer_email: '{{address.email}}', amount: '{{cart.get_total_price}}', customer_phone: "234099940409", currency: "NGN", txref: "rave-123456", meta: [{ metaname: "flightID", metavalue: "AP1234" }], onclose: function() {}, callback: function(response) { var txref = response.data.txRef; // collect txRef returned and pass to a server page to complete status check. console.log("This is the response returned after a charge", response); if ( response.data.chargeResponseCode == "00" || response.data.chargeResponseCode == "0" ) { "{% url 'checkout:payment_complete' %}" // redirect to a success page } else { // redirect to a failure page. } x.close(); // use this to close the modal immediately after payment. } }); } </script> how do i go about it? like kindly assist me with … -
Django Ajax - Based on first selection set the second select options
I'm new to ajax and a beginner for django. Currently There is two select input 'MF_name' and 'PD_name'. I need to get PD_name options based on MF_name's selection. This is where I required ajax. I need to use onchange and set the queryset for PD_name. Can someone provide a simple guide to this? Really appreciate the help thanks! queryset = Product.objects.only('name').filter(MFID=MFID) #Html <tr id="emptyRow"> <td colspan="6" style="text-align:center;">Please select a Manufacturing Company first.</td> </tr> <tr class="clone_tr displayNone"> <td>{{ prd.PD_name }}</td> <td>{{prd.PDID}}</td> <td>{{rtk_prd.qty}}{{rtk_prd.qty.errors}}</td> <td> <span class="input-group p-0"> <div class="input-group-text">RM</div> {{prd.restock_price}} </span> </td> <td>{{rtk.remark}}</td> <td><button type="button" class="btn" onclick="clone_element(this,'.clone_tr','.my-tbody',word)"><i class="fas fa-plus-square fa-lg"></i></button></td> <td><button type="button" class="btn" onclick="clone_element(this,'.clone_tr','.my-tbody',word)"><i class="fas fa-plus-square fa-lg"></i></button></td> #ajax $('#id_MF_name').on('change', function (e) { e.preventDefault(); var MF_name = $(this).val(); $.ajax({ 'url': '{% url "Restock:Ajax" %}', 'data': { 'MF_name' : MF_name, 'csrfmiddlewaretoken' : '{{csrf_token}}' }, dataType: 'json', success: function (response) { $('#emptyRow').remove(); $('.clone_tr').removeClass("displayNone"); }, }); }); #urls.py path('ajax/', views.is_ajax, name='Ajax'), #views.py #this is the part where I wasn't sure what I'm suppose to do after passing the data from ajax to views. #Please provide explanation on what I'm suppose to do here to set PD_name options. def is_ajax(request): if request.is_ajax(): MFID = request.GET.get('MF_name', None) print(MFID) context = { } return render(request, 'Restock/Restock.html', context) -
Django, How to pass HTML form values to URL upon form submission?
The project have url as follows, path('post/<str:state>/',SearchView.as_view(),name='search-data') I have a HTML form, upon filling and submitting it supposed to pass filled form data to URL. <form action={url 'search-data'} method="get" > {% csrf_token %} <input type="text" name="fname"> </form> But it does not work as supposed to be. -
Setting up Django static with Docker/Nginx
I am Dockerizing my Django/React app but having issues getting the static files to show up on the prod server. Project Directory: . ├── README.md ├── backend │ ├── Dockerfile │ ├── Dockerfile.prod │ ├── backend │ ├── entrypoint.prod.sh │ ├── entrypoint.sh │ ├── manage.py │ ├── requirements.txt │ └── static ├── docker-compose.ci.yml ├── docker-compose.prod.yml ├── docker-compose.yml ├── frontend │ ├── Dockerfile │ ├── Dockerfile.prod │ ├── README.md │ ├── build │ ├── node_modules │ ├── package-lock.json │ ├── package.json │ ├── public │ ├── src │ └── webpack.config.js └── nginx ├── Dockerfile └── nginx.conf nginx.conf upstream backend { server backend:8000; } server { listen 80; location / { root "/var/www/frontend"; } location /api/ { proxy_pass http://backend; proxy_set_header Host $http_host; } location /admin/ { proxy_pass http://backend; proxy_set_header Host $http_host; } location /static/ { alias /backend/static; } } Django static setting: STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') docker-compose.ci.yml (builds the images): version: "3.8" services: backend: build: context: ./backend dockerfile: Dockerfile.prod image: "${BACKEND_IMAGE}" command: gunicorn backend.wsgi:application --bind 0.0.0.0:8000 volumes: - static_volume:/backend/static - media_volume:/backend/media expose: - 8000 env_file: .env frontend: build: context: ./frontend dockerfile: Dockerfile.prod image: "${FRONTEND_IMAGE}" volumes: - frontend_build:/frontend/build nginx: build: context: ./nginx image: "${NGINX_IMAGE}" ports: - 80:80 volumes: - static_volume:/backend/static … -
Same code, same database, different results on testing server and local server
My local environment and my testing environment are both connected to the same database engine (postgresql) and have the same Django settings. In my TableA, I have some duplicate rows and I only want to get the ones that belongs to "category_1" with distinct "field1" values. So I do: result = TableA.objects.filter(category='category_1').distinct('field1').order_by('field1') This creates the query SELECT DISTINCT ON ("TableA"."field1") "TableA"."id", "TableA"."category", "TableA"."field1" FROM "TableA" WHERE "TableA"."category"= "category_1" ORDER BY "TableA"."field1" The result looks correct on the local, but when I test it on my testing server the result still includes the rows that have the same "field1" values. What could possibly go wrong?? -
How to use bootstrap 5 with webpack loader?
I am using react with django with webpack, It is the first time to do this, but I faced a problem with webpack loader it says : ERROR in ./node_modules/bootstrap/dist/css/bootstrap.rtl.min.css 1:0 Module parse failed: Unexpected character '@' (1:0) You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders > @charset "UTF-8";/*! | * Bootstrap v5.1.3 (https://getbootstrap.com/) | * Copyright 2011-2021 The Bootstrap Authors @ ./src/components/siteNavbar.js 4:0-50 @ ./src/App.js 4:0-49 14:40-50 @ ./src/index.js 1:0-28 This is my webpack.config.js file: const path = require("path"); const webpack = require("webpack"); module.exports = { entry: "./src/index.js", output: { path: path.resolve(__dirname, "./static/frontend"), filename: "[name].js", }, module: { rules: [ { test: /\.js$/, exclude: /node_modules/, use: { loader: "babel-loader", }, }, ], }, optimization: { minimize: true, }, plugins: [ new webpack.DefinePlugin({ "process.env": { // This has effect on the react lib size NODE_ENV: JSON.stringify("production"), }, }), ], }; I am also using babel Can you tell me how to configure my webpack file to fit bootstrap, font awesome and many more. -
CSRF verification failed on post request to Django Server
I'd like to post data to an endpoint hosted by Django. I am using cURL in my terminal to do this: curl -X POST -H "Content-Type: application/json" http://127.0.0.1:8000/bucket/create/ --data '{"name":"test2", "description":"hey"}' This returns the following error in an xml message: CSRF verification failed. Request aborted. You are seeing this message because this site requires a CSRF cookie when submitting forms. This cookie is required for security reasons, to ensure that your browser is not being hijacked by third parties. If you have configured your browser to disable cookies, please re-enable them, at least for this site, or for “same-origin” requests. Help Reason given for failure: CSRF cookie not set. In general, this can occur when there is a genuine Cross Site Request Forgery, or when Django’s CSRF mechanism has not been used correctly. For POST forms, you need to ensure: Your browser is accepting cookies. The view function passes a request to the template’s render method. In the template, there is a {% csrf_token %} template tag inside each POST form that targets an internal URL. If you are not using CsrfViewMiddleware, then you must use csrf_protect on any views that use the csrf_token template tag, as well as those … -
Running makemigrations in Django package test case with tox
I've got a Django package, and I want to run makemigrations --check --dry-run --noinput in a test case (not using pytest; standard Django test runner). I tried just running call_command, but, with sqlite, that in turn uses the in memory db. So if there was supposed to be a migration, the db/django wouldn't know about it. I.e., when I do this, the command just says that no changes were detected. If you try doing django-admin makemigrations, you'll get an "apps not loaded" issue. Anyone have an idea of what we can try to do? Maybe threads? Ref this is taking place in django-oauth-toolkit -
Django drag drop help please
I'm looking for help with a drag-n-drop feature for updating a table in my Django model. I need to be able to drag items (a list of model objects) between 3 baskets and update the item's basket type in the model. My model contains food items and the status of these items. So the food.names will be the items dragged and 3 baskets are the food.status: 'don't have', 'have', 'need to buy'. Just like this example: https://www.javascripttutorial.net/sample/webapis/drag-n-drop-basics/. <!DOCTYPE html> <html lang="en"> <head> <style> #div1, #div2, #div3 { float: left; width: 100px; height: 35px; margin: 10px; padding: 10px; border: 1px solid black; } </style> <script> function allowDrop(ev) { ev.preventDefault(); } function drag(ev) { ev.dataTransfer.setData("text", ev.target.id); } function drop(ev) { ev.preventDefault(); var data = ev.dataTransfer.getData("text"); ev.target.appendChild(document.getElementById(data)); } </script> </head> <body> <h2>Drag and Drop</h2> <p>Drag the items back and forth between the three div elements.</p> {% for row in all_food %} <div id="div1" ondrop="drop(event)" ondragover="allowDrop(event)"> {% if row.status_type == 'have'%} <ul> <li><a href="/" draggable="true" ondragstart="drag(event)" id="drag1" width="88" height="31">{{row}}</a> </ul> {% endif %} </div> <div id="div2" ondrop="drop(event)" ondragover="allowDrop(event)"></div> <div id="div3" ondrop="drop(event)" ondragover="allowDrop(event)"></div> {% endfor %} </body> </html> The code above comes out as 33 boxes with the items in the for loop scattered among … -
How to publish changes to Docker images in Github Actions
I am working on a CI/CD pipeline using Docker and GitHub Packages/Actions. I have 2 workflows: build.yml and deploy.yml. The build.yml workflow is supposed to pull the Docker images from GitHub Packages, build them, run automated tests, then push the new images to GitHub Packages. The issue I am having is that my local changes are not being updated on the server. build.yml: name: Build and Test on: push: branches: - development env: BACKEND_IMAGE: ghcr.io/$(echo $GITHUB_REPOSITORY | tr '[:upper:]' '[:lower:]')/backend FRONTEND_IMAGE: ghcr.io/$(echo $GITHUB_REPOSITORY | tr '[:upper:]' '[:lower:]')/frontend NGINX_IMAGE: ghcr.io/$(echo $GITHUB_REPOSITORY | tr '[:upper:]' '[:lower:]')/nginx jobs: test: name: Build Images and Run Automated Tests runs-on: ubuntu-latest steps: - name: Checkout master uses: actions/checkout@v1 - name: Add environment variables to .env run: | echo DEBUG=0 >> .env echo SQL_ENGINE=django.db.backends.postgresql >> .env echo DATABASE=postgres >> .env echo SECRET_KEY=${{ secrets.SECRET_KEY }} >> .env echo SQL_DATABASE=${{ secrets.SQL_DATABASE }} >> .env echo SQL_USER=${{ secrets.SQL_USER }} >> .env echo SQL_PASSWORD=${{ secrets.SQL_PASSWORD }} >> .env echo SQL_HOST=${{ secrets.SQL_HOST }} >> .env echo SQL_PORT=${{ secrets.SQL_PORT }} >> .env - name: Set environment variables run: | echo "BACKEND_IMAGE=$(echo ${{env.BACKEND_IMAGE}} )" >> $GITHUB_ENV echo "FRONTEND_IMAGE=$(echo ${{env.FRONTEND_IMAGE}} )" >> $GITHUB_ENV echo "NGINX_IMAGE=$(echo ${{env.NGINX_IMAGE}} )" >> $GITHUB_ENV - name: Log in to GitHub … -
Does max_retries limit the quantity of "retries" when using acks_late&
I have a task that looks like this (ofcourse the run method if more complex): class SomeTask(celery.Task): max_reries = 3 acks_late = True def run(self): print('some code') I know that celery has acks_late and retry options. I need to use acks_late. So Im wondering: max_reries = 3 limit the quantity of "retries" just for retry() or for acks_late also. I tried to find this in celery docs, but there was no information about that. -
IntegrityError on migration using Geodjango + Spatialite
I have a Model CoordenadasPonto that uses one PointField from django.contrib.gis.db.models in an app called mc. When I try to migrate a modification of this Model, Django raises: django.db.utils.IntegrityError: The row in table 'geometry_columns_statistics' with primary key 'CONSTRAINT' has an invalid foreign key: geometry_columns_statistics.f_table_name contains a value '**new__**mc_coordenadasponto' that does not have a corresponding value in geometry_columns.f_table_name. It doesn't matter if I modify the PointField or other fields. It seems every time I modify the Model, Django try to copy all the data to a new Table in Database using new__ plus original table name. After that, I guess Django would delete/drop the original table and rename new__ to the original name. But due to the IntegrityError, this never happens. It seems the problem is with GIS/Spatialite because some data is linked with the GIS table geometry_columns_statistics not migrated in accordance. I tried to modify directly the geometry_columns_statistics in the sqlite file, but other dependencies problems came out. -
How do I get Django to not add carriage returns in a Textarea in the admin UI?
I am using a Textarea in Django admin with strip=False as outlined here. def formfield_for_dbfield(self, db_field, **kwargs): formfield = super().formfield_for_dbfield(db_field, **kwargs) if db_field.name == 'some_text': formfield.strip = False formfield.widget = forms.Textarea(attrs={'rows': 10, 'cols': 80}) return formfield The DB field comes from an HTML input box, and has newlines in it (\n). After I edit and save in Django, it has carriage-return newlines (\r\n), as seen when I query from the DB. BEFORE: select md5(some_text), some_text from myapp_obj where id = 328; md5 | some_text ----------------------------------+----------------------------------------------------------- adb48a782562ef02801518c4e94ca830 | foo1. + | foo2 + ... AFTER: select md5(some_text), some_text from myapp_obj where id = 328; md5 | some_text ----------------------------------+----------------------------------------------------------- e9e06c1d9764be70fc61f05c5fd6292c | foo1.\r + | foo2\r + ... How do I get the Django admin UI (the Textarea) to save back exactly what was loaded into its UI, without adding or subtracting anything? I'm using Django 3.2.9, Postgres 13. -
I'm a django beginner, and I do not know why this kind of error is ocurring
'carro' Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 3.2.8 Exception Type: KeyError Exception Value: 'carro' Exception Location: :\Users*\Envs\django2\lib\site-packages\django\contrib\sessions\backends\base.py, line 65, in getitem Python Executable: *:\Users******\Envs\django2\Scripts\python.exe Python Version: 3.9.5 Python Path: ['F:\ProjectoWeb', 'c:\python39\python39.zip', 'c:\python39\DLLs', 'c:\python39\lib', 'c:\python39', 'C:\Users\\Envs\django2', 'C:\Users\\Envs\django2\lib\site-packages'] Server time: Wed, 22 Dec 2021 19:06:41 -0300 -
how to access django database on the remote site from a local script?
I have the following code in a script: import django django.setup() This loads my project settings for local development but what I actually want is to load the server's settings (specifically the database access). What I tried? I created another file settinge_remote.py (same folder as settings.py) and setting the DATABASES dictionary to hold the remote server host/ip. but the code: import django django.setup() os.environ.setdefault("DJANGO_SETTINGS_MODULE", "my_project.settings_remote") has no effect (I also moved the setting_remote line in first place). It still reads the my_project.settings and not the my_project.settings_remote. -
All the testcases have assertion error: 401 !=200 django
I have a custom abstract base user and basic login with knox view, I made some simple tests to the register and login process, however all the testcases fail to assertion error:401!=200 and when I use pdb.set_trace to know the sent data it always has that error (Pdb) res <Response status_code=401, "application/json"> (Pdb) res.data {'detail': ErrorDetail(string='Authentication credentials were not provided.', code='not_authenticated')} Here is the test setup from rest_framework.test import APITestCase from django.urls import reverse class TestSetUp(APITestCase): def setUp(self): self.register_url = reverse('knox_register') self.login_url = reverse('knox_login') self.correct_data = { 'email':"user@gmail.com", 'password': "Abc1234#", } self.wrong_email_format = { 'email': "user@gmail", 'password': "Abc1234#", } self.missing_data = { 'email':"user@gmail.com", 'password':"", } self.wrong_password_format = { 'email': "user@gmail.com", 'password': "123", } return super().setUp() def tearDown(self): return super().tearDown() and the test_view from .test_setup import TestSetUp import pdb class TestViews(TestSetUp): #register with no data def test_user_cannot_register_with_no_data(self): res = self.client.post(self.register_url) self.assertEqual(res.status_code,400) #register with correct data def test_user_register(self): self.client.force_authenticate(None) res = self.client.post( self.register_url, self.correct_data, format="json") #pdb.set_trace() self.assertEqual(res.status_code,200) #register with wrong email format def test_register_with_wrong_email_format(self): res = self.client.post( self.register_url, self.wrong_email_format) self.assertEqual(res.status_code, 400) # register with wrong password format def test_register_with_wrong_password_format(self): res = self.client.post( self.register_url, self.wrong_password_format) self.assertEqual(res.status_code, 400) #register with missing_data def test_register_with_missing_data(self): res = self.client.post( self.register_url, self.missing_data) self.assertEqual(res.status_code, 400) #login with correct Credentials … -
Django / app import problem from submodule
I'm writing my own Django app, and trying to import submodule from my core library like that: INSTALLED_APPS = [ 'django.contrib.admin', ... 'core.login', ] And interpreter gives me: django.core.exceptions.ImproperlyConfigured: Cannot import 'login'. Check that 'core.login.apps.CustomloginConfig.name' is correct. So login.apps looks like that from django.apps import AppConfig class CustomloginConfig(AppConfig): name = 'login' Are there any rules how I can edit this files to start Django properly? -
Application error on heroku failed to update heroku config
I have hosted a django project on heroku and I'm trying to update my environment variables through heroku config but, I wrote the following command heroku config:set SECRET_KEY="djang...j*yb13jkqu-+q+l&)#b(g..." And it shows me the following result j*yb13jkqu-+q+l was unexpected at this time.