Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django not hashing password custom user
i am working on a model which inherits from from django.contrib.auth.models import AbstractBaseUser earlier i was specifying password field like: password = models.Charfield(max_length=150) but then i need to specify it as: create_password = models.CharField(max_length=150) in earlier case i was getting password in hashed format. but after changing password to create_password the value is saving in unhashed format (originally entered value). all other settings are same as before, i am using set_password(create_password) now . but still no hashing. how can i hash create_password field? -
ModuleNotFoundError: No module named 'api_yamdb.wsgi'
When deploying the project, the web container fails with the error No module named 'api_yamdb.wsgi'. Please help!) Dockerfile: `FROM python:3.7-slim WORKDIR /app COPY .. . RUN pip3 install -r ./requirements.txt --no-cache-dir CMD ["gunicorn", "api_yamdb.wsgi:application", "--bind", "0:8000"]` Workflow: `name: Yamdb workflow on: [push] jobs: tests: runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - name: Set up Python uses: actions/setup-python@v2 with: python-version: 3.7 - name: Install dependencies run: | python -m pip install --upgrade pip pip install flake8 pep8-naming flake8-broken-line flake8-return flake8-isort pip install -r api_yamdb/requirements.txt - name: Test with flake8 and django tests run: | python -m flake8 pytest build_and_push_to_docker_hub: name: Push Docker image to Docker Hub runs-on: ubuntu-latest needs: tests if: contains(' refs/heads/master refs/heads/main ', github.ref) steps: - name: Check out the repo uses: actions/checkout@v2 - name: Set up Docker Buildx uses: docker/setup-buildx-action@v1 - name: Login to Docker uses: docker/login-action@v1 with: username: ${{ secrets.DOCKER_USERNAME }} password: ${{ secrets.DOCKER_PASSWORD }} - name: Push to Docker Hub uses: docker/build-push-action@v2 with: push: true tags: porter4ch/yamdb_final:latest file: api_yamdb/Dockerfile deploy: runs-on: ubuntu-latest needs: build_and_push_to_docker_hub steps: - name: executing remote ssh commands to deploy uses: appleboy/ssh-action@master with: host: ${{ secrets.HOST }} username: ${{ secrets.USER }} key: ${{ secrets.SSH_KEY }} passphrase: ${{ secrets.PASSPHRASE }} script: | sudo docker-compose … -
How to python-execute-file a django custom command in emacs
How can I C-c C-c or python-execute-file a django custom command? Currently I get this error (using the emacs settings at the bottom): -*- mode: compilation; default-directory: "~/src/django/" -*- Comint started at Fri Feb 17 16:45:33 /home/user/.local/share/virtualenvs/django-OfUvXXat/bin/python csv_import.py /home/user/.local/share/virtualenvs/django-OfUvXXat/bin/python: can't open file 'csv_import.py': [Errno 2] No such file or directory Inferior Python exited abnormally with code 2 at Fri Feb 17 16:45:33 This works as expected: python manage.py csv_import ~/django/crm/management/commands/csv_import.py: from django.core.management.base import BaseCommand, CommandError from crm.models import Organization,Person class Command(BaseCommand): def handle(self, *args, **options): print(Organization.objects.all()) I tried to no avail many settings e.g. (setq python-shell-interpreter "python" python-shell-interpreter-args "-i /home/user/src/django/manage.py shell") (defun django-shell () (interactive) (let ((python-shell-interpreter (read-file-name "Locate manage.py ")) (python-shell-interpreter-args "shell")) (run-python (python-shell-calculate-command) nil t))) Environment: lsp,pyright,pipenv -
Django-DataFrame constructor not properly called
views.py def preprocessedDatafile(request): dtf = pd.DataFrame(request.POST['myfile']) dtf.to_csv("../static/files/myPreprocessedata.csv") return render(request, "preprocessedDatafile.html") .html <form class="grid" method="POST" action="{% url 'preprocessedDatafile' %}" onSubmit="return empty()"> {% csrf_token %} <div style="border: 1px dashed rgb(148,10,34); width:59%" > <br/><br/> <input type="file" class='upload-box' accept=".csv" name='myfile' onchange='triggerValidation(this)' required='true'/> <br/><br/><br/> </div> <button type="reset" id='clr' ><b>Clear</b></button> <button type="submit" id="btn" ><b>Start</b></button> </form> I am making a web page that take csv file and than store this csv file in a specific location using django. but i do not know why i am getting "DataFrame constructor not properly called!". Is there way to remove this error? -
how to use rest_framework.urls, through /login/
i wanna make my own API through rest_framework.urls (/login/)=> i think /login/ url is provided by this framework. enter image description here as you can see, i wrote my client type of json, but i think that key:values are not "email" and "password". plz let me know the json type when using rest_framework.urls (/login/) Thank you # apps.urls.py urlpatterns = [ path('signup/', UserCreate.as_view()), **path('', include('rest_framework.urls')),** ] # project(root).urls.py urlpatterns = [ path('admin/', admin.site.urls), **path('login/', include('login.urls')),** path('', include('postapp.urls')), ] i want to enter my client to that page(rest_framework/login/) by using json type -
Volume doesn't work in a docker container and forgets data
I'm trying to build Django + Docker + PostgreSQL Dockerfile FROM python:3.10.0-alpine WORKDIR /usr/src/app ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 RUN pip install --upgrade pip RUN apk update RUN apk add postgresql-dev gcc python3-dev musl-dev COPY ./requirements.txt . RUN pip install -r requirements.txt COPY ./entrypoint.sh . RUN sed -i 's/\r$//g' /usr/src/app/entrypoint.sh RUN chmod +x /usr/src/app/entrypoint.sh COPY . . ENTRYPOINT ["/usr/src/app/entrypoint.sh"] docker-compose.yml version: '3.9' services: web: build: . command: gunicorn pets.wsgi:application --bind 0.0.0.0:8000 expose: - 8000 env_file: - .env depends_on: - db db: image: postgres:12.0-alpine volumes: - postgres_data:/var/lib/postgresql/data/ env_file: - .env nginx: build: ./nginx ports: - 1337:80 depends_on: - web volumes: postgres_data: entrypoint.sh #!/bin/sh if [ "$DATABASE" = "postgres" ] then echo "Waiting for postgres..." while ! nc -z $POSTGRES_HOST $POSTGRES_PORT; do sleep 0.1 done echo "PostgreSQL started" fi cd pets python manage.py flush --no-input python manage.py migrate exec "$@" So, when the container starts i use docker exec -it <container_id> python manage.py createsuperuser to create a superuser and then add some data to database. But, when i use docker-compose stop and then running again with the same id the container forgets about the written data and everything has to be repeated. Shouldn't volume solve this issue? -
Why django_session and auth_user have no relations?
The Django authentication system is a great system that can be helpful to develop authentication in apps. However, the django_session table and auth_user have no relation. When we want to fetch all of the active sessions of a user we have to fetch all the active sessions, deserialize the session_data, and then find the users' sessions. This is practically a complete table scan. Is there any special or security reason for that? Can we just create an association between these tables without making any vulnerabilities? -
How to fetch Individual Values from the Queryset in Django Template
How to fetch Individual Values from the Queryset Skill <QuerySet [{'id': 1, 'name': 'Django', 'score': 100, 'is_key_skill': True}, {'id': 2, 'name': 'Python', 'score': 75, 'is_key_skill': True}]> in Django template Here is my views.py : def home(request): value = profile.objects.get(id=1) skills = Skill.objects.filter().values context = { 'value': value, 'Skill': skills, } return render(request, 'home.html', context) I want to fetch individual values like Django and its corresponding values separately. -
Django channels connection failed (nginx + daphne + certbot + docker-compose)
I'm using Django channels using docker-compose and nginx outside it websockets were working just fine but after installing certbot, it stopped working it returns 404 as if it is treated as just normal http request VM253:1 WebSocket connection to 'wss://example.com/ws/results/tjrtudvzanxxqbyt' failed: daphne : "GET /ws/results/tjrtudvzanxxqbyt" 404 2618 my nginx file for the server is upstream language_transcriber{ server localhost:8000; } # the nginx server instance server { listen 443 default_server; server_name example.com; access_log /var/log/nginx/example.com.log; ssl_certificate_key /etc/nginx/ssl/example.com.private_key.pem; ssl_certificate /etc/nginx/ssl/fullchain.crt; root /var/www; ssl on; # pass the request to the node.js server with the correct headers # and much more can be added, see nginx config options location /ws/ { proxy_set_header Host $http_host; proxy_set_header X-Real-IP$remote_addr; proxy_set_header X-Forwarded-For$proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Host $server_name; proxy_set_header X-Forwarded-Proto$scheme; proxy_set_header X-Url-Scheme $scheme; proxy_redirect off; proxy_set_header X-NginX-Proxy true; proxy_http_version 1.1;proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection $connection_upgrade; proxy_pass http://127.0.0.1:8000; } location /static/ { alias /var/www/example.com/static/; autoindex off; } location / { proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_http_version 1.1; proxy_set_header Host $host; proxy_set_header X-Forwarded-Host $server_name; proxy_set_header X-Forwarded-Proto $scheme; proxy_set_header X-Url-Scheme $scheme; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_set_header X-NginX-Proxy true; proxy_pass http://language_transcriber/; proxy_redirect off; } } and here's my docker-compose.yml version: "3.8" services: django: build: . container_name: django command: daphne … -
Validate field input using django serializer
I have a field code in my django model. I have to check if the input string has following properties: Length should be 5 characters 1st & 2nd characters should be alphabets 3rd & 4th characters should be numbers 5th character should be E or N I have a serializer as shown below which satisfies the first condition. class MyModelSerializer(serializers.ModelSerializer): code = serializers.CharField(max_length=5, min_length=5) class Meta: model = MyModel fields = '__all__' How can I fulfil the remaining conditions. Need your help with this. Thanks in advance -
session handling between react django app if user browser cookies blocked
in my react-django app,my scenario is each user has multiple accounts and when user login there will be a session check call and if no data in session then we have to select particular account and store it in session thus django and react passes session cookie in every request.suppose if cookies are blocked in user browser then what to do? how to handle session data then? -
How to display blog post description structured correctly for a Django blog?
I am creating a blog where it displays the post description in a blog post. But the post data is displaying odd or continues text. I want post description to display same in a proper format that is given as an input. In Urls.py path('blog_single/<str:title>/', views.blog_single, name = 'blog_single'), In Views.py def blog_single(request, title): posts = Post.objects.get(title = title) recent_posts = Post.objects.all().order_by('-posted_at')[:5] Categories = Category.objects.all() context = {'posts':posts, 'recent_posts':recent_posts , 'Categories': Categories} return render(request, 'blog-single.html', context) In blog-single.html <div class="entry-img"> <img src="{{posts.thumbnail.url}}" alt="" class="img-fluid"> </div> <h2 class="entry-title"> <a href="#">{{posts.title}}</a> </h2> <div class="entry-meta"> <ul> <li class="d-flex align-items-center"><i class="bi bi-person"></i> <a href="blog-single.html">{{posts.user}}</a></li> <li class="d-flex align-items-center"><i class="bi bi-clock"></i> <a href="blog-single.html"><time datetime="2020-01-01">{{posts.posted_at}}</time></a></li> <!-- <li class="d-flex align-items-center"><i class="bi bi-chat-dots"></i> <a href="blog-single.html">12 Comments</a></li> --> <li class="d-flex align-items-center"><i class="bi bi-list"></i> <a href="blog-single.html">{{posts.category}}</a></li> </ul> </div> <div class="entry-content"> <p class="post__description"> {{posts.description|safe}} </p> </div> <div class="entry-footer"> <i class="bi bi-folder"></i> <ul class="cats"> <li><a href="#">Business</a></li> </ul> <i class="bi bi-tags"></i> <ul class="tags"> <li><a href="#">Creative</a></li> <li><a href="#">Tips</a></li> <li><a href="#">Marketing</a></li> </ul> </div> </article><!-- End blog entry --> In Models.py file class Post(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name = 'categories') user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='users') title = models.CharField(max_length =255) thumbnail = models.ImageField(upload_to = 'post/thumbnail') description = models.TextField() tags = models.CharField(max_length=255) posted_at = models.DateField(default = datetime.now) is_published … -
How to put a warped image on top of another using Python PIL?
Here's an example: (you can test it as a site user in the URL below) https://placeit.net/c/mockups/stages/t-shirt-mockup-of-a-cool-man-posing-in-a-dark-alley-2357-el1?iref=apparel-mockups-best-sellers-output User will upload an image and it will be applied as tshirt design on the mockup. I am not expecting to be able to develop a mega website such as Placeit but I would like to learn if similar to this very webpage in the url above. My initial idea is to use PIL lib of Python and then Django. If not, could you give me Python libraries that are more suitable? or other workaround? I understood that it includes atleast 2 images. First image is the tshirt with guy that I can do in photoshop with transparent layer on the shirt part along with shadows to make it look realistic (the folds in the shirt). Second image is the user's uploaded image. And yeah, the combining of two image is what I would like to know, esp the warped part. Tried PIL in combining the 2 images but it is only one on top of another, the warped part is the hard part. I guess its not only PIL but no idea which API or library to use. -
Convert a List of dict to single dict and it's key and value
data = [{ "January": {"China": 6569.4, "Japan": 49448.61,"Norway": 28000.0,"Poland": 3525.427,"Singapore": 33190.231851,"United States": 25976.4,"Taiwan": 15363.884885}}, {"February": {"Japan": 2540.32,"Poland": 14750.0,"Singapore": 16044.473973}}] Expecting Result data = [{ "January": {"China": 6569.4, "Japan": 49448.61,"Norway": 28000.0,"Poland": 3525.427,"Singapore": 33190.231851,"United States": 25976.4,"Taiwan": 15363.884885}, "February": {"Japan": 2540.32,"Poland": 14750.0,"Singapore": 16044.473973}}] -
get_absolute_url is not changing template?
get_absolute_url is redirecting to the page im already on (forum_list.html instead of thread_list.html)? models.py class Thread(models.Models): (...) def get_absolute_url(self): return reverse('forum:thread_list', args=[self.created.year, self.created.month, self.created.day, self.slug]) urls.py path('<int:year>/<int:month>/<int:day>/<slug:slug>/', views.ThreadListView.as_view(), name='thread_list'), views.py class ThreadListView(ListView): querytext = Thread.published.all() context_object_name = 'threads' paginate_by = 20 template_name = 'forum/thread_list.html' forum_list.html {% extends 'forum/base.html' %} {% block content %} <a href="{{ forum.get_absolute_url }}>Read</a>" {% endblock content %} what am i doing wrong? the url in the adress bar changes but the template doesnt.. It refreshes the same page but the URL changes. -
PermissionError: [Errno 13] Permission denied: 'E:\\SpeechRecongnition\\uploads\\tmpbkl0c5oc.wav' flask
I'm trying to use the Vosk library in Python to extract text from audio files. To do this, I'm using the wave module to read a temporary WAV file created from an MP3 or video file using the pydub and ffmpeg libraries. But it keeps giving me the error permmision denied even after giving the privileges Here is my code: from flask import Flask, render_template, request, send_file from werkzeug.utils import secure_filename import os import wave import json import tempfile import subprocess from pydub import AudioSegment import stat import vosk app = Flask(__name__,template_folder='template') # Set up Vosk model and recognizer model = vosk.Model("\SpeechRecongnition\model\EnglishIN") rec = vosk.KaldiRecognizer(model, 16000) UPLOAD_FOLDER = 'uploads' # Set up app config app.config['MAX_CONTENT_LENGTH'] = 70 * 1024 * 1024 # 70 MB max for audio files app.config['UPLOAD_EXTENSIONS'] = ['.wav', '.mp3', '.mp4', '.avi', '.mkv'] app.config['UPLOAD_PATH'] = UPLOAD_FOLDER @app.route('/') def index(): return render_template('index.html') @app.route('/transcribe', methods=['POST']) def upload_file(): # Check if file was submitted text="" if 'file' not in request.files: return 'No file uploaded' # Get file from request and check if it has a valid extension file = request.files['file'] if not file.filename.lower().endswith(tuple(app.config['UPLOAD_EXTENSIONS'])): return 'Unsupported file format' # Save file to disk filename = secure_filename(file.filename) file.save(os.path.join(app.config['UPLOAD_PATH'], filename)) text = transcribe_audio(os.path.join(app.config['UPLOAD_PATH'], filename)) … -
NoReverseMatch at /reset/done/ 'user' is not a registered namespace
I am trying to finalize the password reset process and after the user changes the password and click on save changes I keep getting this error: NoReverseMatch at /reset/done/ 'user' is not a registered namespace Here is the main urls.py urlpatterns = [ path('', include('django.contrib.auth.urls')), path('users/', include('users.urls'), ), path('admin/', admin.site.urls),] Here is the users urls.py app_name = 'users' urlpatterns = [ path('password-reset/', auth_views.PasswordResetView.as_view(template_name='users/password_reset.html', success_url=reverse_lazy('users:password_reset_done')), name='password_reset'), path('password-reset/done/', auth_views.PasswordResetDoneView.as_view(template_name='users/password_reset_done.html'),name='password_reset_done'), path('password-reset-confirm/<uidb64>/<token>/',auth_views.PasswordResetConfirmView.as_view(template_name='users/password_reset_confirm.html',success_url=reverse_lazy('users:password_reset_done'),post_reset_login=True),name='password_reset_confirm',), path('password-reset-complete/', auth_views.PasswordResetCompleteView.as_view(template_name='users/password_reset_complete.html'),name='password_reset_complete'), ] My question I guess the reason for these new errors showing up is due to Django or python version however when the user clicks on forget password and inserts the email they receives an email and when the click on the email link to reset the password it takes them to a Django Admin page (for some reason I am trying to figure out anyways) and when they insert the new password and click on the save changes it shows this error. The error is Raised during: django.contrib.auth.views.PasswordResetCompleteView here is the traceback: Internal Server Error: /reset/done/ Traceback (most recent call last): File "C:\Users\User\Desktop\Project\venv\lib\site-packages\django\urls\base.py", line 71, in reverse extra, resolver = resolver.namespace_dict[ns] KeyError: 'user' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\User\Desktop\Project\venv\lib\site-packages\django\core\handlers\exception.py", … -
How to use safe filter on custom Django tag?
I'm trying to implement a custom Django tag that will formulate an import statement in Javascript to load my vue3 app as well as its components template html files using a get request in axios. The custom tag in my templatetags directory looks like this: templatetags/vuecomponents.py from django import template from django.templatetags.static import static register = template.Library() @register.simple_tag def v_load_app_component(app_name, script_name, components): components = components.strip("[]").split(", ") app_script = static(f"js/{script_name}.js") comps = [static(f"components/{name}.html") for name in components] return f"import {{{ app_name }}} from \"{app_script}?{components[0]}={comps[0]}\"" Right now it only loads the first component as I just want a prototype. The only issue is when I drop this into a template like so: createpost.html <script type="module"> {% v_load_app_component "creator" "internalpostform" "[internalpostform]" %} // OUTPUTS: // import { creator } from &quot;static/js/internalpostform.js?internalpostform=internalpostform.html&quot; creator.mount("#app") </script> It outputs the relevant import statement as: import { creator } from &quot;static/js/internalpostform.js?internalpostform=internalpostform.html&quot; With the double quotes escaped. Even when I tried to apply the safe filter ({% v_load_app_component "creator" "internalpostform" "[internalpostform]"|safe %}) it still escaped the output of my custom tag function. How can I make it to where the output of my custom tag doesn't automatically have symbols converted to html entities? -
Converting string data to python doctionary is raising exception
I am implementing real time notification feature in my Django project using django channels and web sockets. This is my code for comsumers.py: class MySyncGroupAConsumer(SyncConsumer): def websocket_connect(self,event): print("Web socket connected", event) self.send({ 'type':'websocket.accept' }) print("Channel layer ",self.channel_layer) print("Channel name", self.channel_name) async_to_sync(self.channel_layer.group_add)("notification", self.channel_name) def websocket_receive(self,event): print("Web socket recieved",event['text']) print(event['text']) data = json.loads(event['text']) async_to_sync(self.channel_layer.group_send)( 'notification', { 'type': 'notification.send', 'message': event['text'] } ) #event handler, which is sending data to client def notification_send(self, event): print('Event...', event) print('Actual msg..', event['message']) self.send({ 'type':'websocket.send', 'text':event['message'] }) def websocket_disconnect(self,event): print("Web socket disconnect", event) async_to_sync(self.channel_layer.group_discard)("notification", self.channel_name) raise StopConsumer() In websocket_receive function,I am trying to convert a string data event['text'] to python dictionary using json.loads(event['text']),but it raises following exception: raise JSONDecodeError("Expecting value", s, err.value) from None json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0) WebSocket DISCONNECT /ws/scgg/ [127.0.0.1:57052] I have printed the type and actual data of event["text"]. It is something like this: print(event['text']) prints this: {"msg":"hi"} print(type(event['text'])) prints this: <class 'str'> I can't figure out the problem. Can anyone guide? -
Why does it say "ModuleNotFoundError: No module named 'django'" whn i have django installed, when installing mobsf?
C:\Windows\system32>cd C:\Users\DAS\Desktop\K\Pentesting Android\Mobile-Security-Framework-MobSF-master C:\Users\DAS\Desktop\K\Pentesting Android\Mobile-Security-Framework-MobSF-master>setup.bat [INSTALL] Checking for Python version 3.8+ [INSTALL] Found Python 3.10.4 [INSTALL] Found pip Requirement already satisfied: pip in c:\users\das\appdata\local\programs\python\python310\lib\site-packages (23.0.1) [INSTALL] Found OpenSSL executable [INSTALL] Found Visual Studio Build Tools [INSTALL] Creating venv Requirement already satisfied: pip in c:\users\das\desktop\k\pentesting android\mobile-security-framework-mobsf-master\venv\lib\site-packages (22.0.4) Collecting pip Using cached pip-23.0.1-py3-none-any.whl (2.1 MB) Installing collected packages: pip Attempting uninstall: pip Found existing installation: pip 22.0.4 Uninstalling pip-22.0.4: Successfully uninstalled pip-22.0.4 Successfully installed pip-23.0.1 [INSTALL] Installing Requirements Collecting wheel Downloading wheel-0.38.4-py3-none-any.whl (36 kB) Installing collected packages: wheel Successfully installed wheel-0.38.4 Ignoring gunicorn: markers 'platform_system != "Windows"' don't match your environment Collecting Django>=3.1.5 Downloading Django-4.1.7-py3-none-any.whl (8.1 MB) ---------------------------------------- 8.1/8.1 MB 12.6 MB/s eta 0:00:00 Collecting lxml>=4.6.2 Downloading lxml-4.9.2-cp310-cp310-win_amd64.whl (3.8 MB) ---------------------------------------- 3.8/3.8 MB 12.7 MB/s eta 0:00:00 Collecting rsa>=4.7 Downloading rsa-4.9-py3-none-any.whl (34 kB) Collecting biplist>=1.0.3 Downloading biplist-1.0.3.tar.gz (21 kB) Preparing metadata (setup.py) ... done Collecting requests>=2.25.1 Downloading requests-2.28.2-py3-none-any.whl (62 kB) ---------------------------------------- 62.8/62.8 kB ? eta 0:00:00 Collecting bs4>=0.0.1 Downloading bs4-0.0.1.tar.gz (1.1 kB) Preparing metadata (setup.py) ... done Collecting colorlog>=4.7.2 Downloading colorlog-6.7.0-py2.py3-none-any.whl (11 kB) Collecting macholib>=1.14 Downloading macholib-1.16.2-py2.py3-none-any.whl (38 kB) Collecting whitenoise>=5.2.0 Downloading whitenoise-6.3.0-py3-none-any.whl (19 kB) Collecting waitress>=1.4.4 Downloading waitress-2.1.2-py3-none-any.whl (57 kB) ---------------------------------------- 57.7/57.7 kB ? eta 0:00:00 Collecting psutil>=5.8.0 Downloading psutil-5.9.4-cp36-abi3-win_amd64.whl (252 … -
ModuleNotFoundError: No module named 'django.config' when running test in Django 4.1
I have a django (v4.1) project with no tests defined. Before I started writing tests, I ran python manage.py test, expecting to get something like: Found 0 test(s). System check identified no issues (0 silenced). .... ---------------------------------------------------------------------- Ran 0 tests in 0.000s OK But instead I got this: Found 1 test(s). System check identified no issues (0 silenced). E ====================================================================== ERROR: django.config (unittest.loader._FailedTest.django.config) ---------------------------------------------------------------------- ImportError: Failed to import test module: django.config Traceback (most recent call last): File "/usr/local/lib/python3.11/unittest/loader.py", line 440, in _find_test_path package = self._get_module_from_name(name) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/unittest/loader.py", line 350, in _get_module_from_name __import__(name) ModuleNotFoundError: No module named 'django.config' ---------------------------------------------------------------------- Ran 1 test in 0.000s FAILED (errors=1) I've checked this question but it seems more to do with a migration problem from Django 2 to 3 and how to run tests. Clarifications: When I say there are no tests defined, I mean that there are the auto-generated test.py files created by manage.py startapp in three applications, but I've commented out the standard import statement # from django.test import TestCase. I tried searching for any instances of django.config using grep -r "django.config" . from the repo directory (which is above django's BASE_DIRECTORY and there are no instances of that in any of … -
Django migrate naive DateTimeField
I am very sad: Every time I migrate the database, Django calls me naive: $ python manage.py migrate RuntimeWarning: DateTimeField Book.released received a naive datetime (2023-02-17 22:59:29.126480) while time zone support is active. ...and the worst part is: It's impossible to fix it! Steps to reproduce: $ python -V Python 3.10.6 $ pipenv --version pipenv, version 2022.11.11 $ mkdir naive-django $ cd naive-django $ pipenv install django $ pipenv shell $ python -m django --version 4.1.7 $ django-admin startproject naive_project $ cd naive_project $ python manage.py startapp naive_app $ vim naive_project/settings.py ... INSTALLED_APPS = [ 'naive_app.apps.NaiveAppConfig', ... $ vim naive_app/models.py from django.db import models class Book(models.Model): title = models.CharField(max_length=100) $ python manage.py makemigrations $ python manage.py migrate No problem so far. Let's add a DateTimeField now: $ vim naive_app/models.py from datetime import datetime from django.db import models class Book(models.Model): title = models.CharField(max_length=100) released = models.DateTimeField(default=datetime.now) $ python manage.py makemigrations $ python manage.py migrate RuntimeWarning: DateTimeField Book.released received a naive datetime (2023-02-17 22:59:29.126480) while time zone support is active. Oh no! I made a terrible mistake! If only it was not impossible to fix it... Let's try anyway: $ vim naive_app/models.py from django.utils import timezone # timezone instead of datetime from … -
How to delete one of the items of a field in the table?
I am trying to delete one of the items of a field in the table. For example, I want to remove the 'hadi', shown in the image, from the table. I make query to filter and exclude instanse but in final part, delete() query does not accept input such as id or variable to remove specific thing in one field. models.py class Expense(models.Model): expenser = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, ) debtors = models.ManyToManyField( CustomUser, related_name='debtors', ) amount = models.PositiveIntegerField() text = models.TextField() date = models.DateField(null=True) time = models.TimeField(null=True) def get_debtors(self): return ", ".join([str(d) for d in self.debtors.all()]) def who_has_no_paid(self): return ", ".join([str(d) for d in self.debtors.all() if str(d) != str(self.expenser)]) def debt(self): return int(float(self.amount/self.debtors.all().count())) def get_absolute_url(self): return reverse('expense_detail', args=[self.id]) Now what is the query that should be used in view? -
Decrement/increment for qty and the value field
I am trying to create a cart page with the ability to use the add or minus buttons to decrement or increment the value of the input but the eventlisteners don't seem to be working and I have tried many different solutions online for this and get it to work properly. {% extends "base.min.html" %} {% block body_block %} {% load static %} <div class='container'> <a class='back-link' href="/"> Back to Catalog</a> <h1 class='cart-h1'>Cart </h1> <div class='cart'> <div class='requests'> <div class='request'> <img src='https://developers.elementor.com/docs/assets/img/elementor-placeholder-image.png' alt='request image'> <div class='request-info'> <p class='request-name'>Request: {{ requestName }}</p> <p class='request-details'>Details: {{ requestDetails }}</p> <p class='request-qty'>Qty: {{ requestQty }} <div class='qty-container'> <input type='button' value='+' class='qtyplus' id='plus' field='quantity' /> <input type='text' name='quantity' value='0' class='qty' id='inputQty' /> <input type='button' value='-' class='qtyminus' id='minus' field='quantity' /> </div> </p> <p class='qty-remove'></p> <span class='remove'>Remove</span> </div> </div> </div> </div> </div> </br> <div class='hidden-container'> <p>Checkout Confirmation #: {{confirmNum}}</p> </div> <script type="module" src="{% static '\js\supplyshop\pageload\RequestManagementLoad.min.js' %} " type ="text/javascript"></script> {% endblock %} const plusBtn = document.querySelector('#plus') const minusBtn = document.querySelector('#minus') const inputQty = document.querySelector('#inputQty') // increment/decrement value on input field // add eventlisteners on +/- buttons to update the value field plusBtn.addEventListener('click', e => { e.preventDefault() inputQty.value = parseInt(inputQty.value) + 1 }) minusBtn.addEventListener('click', e => { e.preventDefault() … -
CSRF fails on Route 53 redirect
I have two EC2 instances, which one has main Django-based backend app and another one has separate React-based frontend app using some of backend data. The backend app has its own views and endpoints and some frontend separate from the app in another EC2 instance. I got a new domain in AWS Route 53 which redirects to the frontend app and its location is configured on nginx. The missing thing are session cookies and csrftoken from the backend to make use of database. What may be useful is the frontend app is already reachable from the redirect set up in Django view but from the base server. In the example code below I don't paste the whole config but just the concept what I want to reach. Is there a way to redirect domain traffic to frontend app but through the backend to retrieve the cookies required to reach the backend data? Or should I think about other solution to make use of the domain? server { ... some server data ... $backend = "aws-backend-dns"; $frontend = "aws-frontend-dns"; location @backend { proxy_pass http://$backend; return @frontend; # but with some magic to keep the cookies! } location @frontend { proxy_pass http://$frontend; …