Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Command 'unset VIRTUAL_ENV; poetry run python3 manage.py makemigrations --dry-run' returned non-zero exit status 127
I use pre-commit. models.py: class ProductMixSuggest(Authorable, Publishable, Timestampable, models.Model): first_product = models.ForeignKey( Product, on_delete=models.CASCADE, related_name="first_product_mix_suggestions", null=True, blank=True, verbose_name=_("محصول اول") ) second_product = models.ForeignKey( Product, on_delete=models.CASCADE, related_name="second_product_mix_suggestions", null=True, blank=True, verbose_name=_("محصول دوم") ) persian_name = models.CharField(max_length=64, verbose_name=_("نام فارسی ترکیب")) english_name = models.CharField(max_length=64, verbose_name=_("نام انگلیسی ترکیب")) logo = models.ImageField(upload_to="product_mixes/", verbose_name=_("لوگوی ترکیب")) image = models.ImageField(upload_to="product_mixes/", blank=False, null=False, default=get_lab_logo_url, verbose_name=_("تصویر اصلی ترکیب")) objects = ProductMixSuggestManager() I add two fields in my model: show_in_page_4 = models.BooleanField(default=True, verbose_name=_("نمایش در صفحه چهارم")) show_in_page_5 = models.BooleanField(default=True, verbose_name=_("نمایش در صفحه پنجم")) also i run makemigrations and migrate command. now I want to commit my changes: git add . git commit -m "add two fields" but pre-commit displays an error: Check for added large files..............................................Passed Trim Trailing Whitespace.................................................Passed flake8...................................................................Passed Check migrations created.................................................Failed - hook id: check-migrations-created - exit code: 1 /bin/sh: poetry: command not found Traceback (most recent call last): File "/Users/mahdikhaloei/.cache/pre-commit/repo4s7kd9o0/py_env-python3/bin/check-migrations-created", line 8, in <module> sys.exit(main()) File "/Users/mahdikhaloei/.cache/pre-commit/repo4s7kd9o0/py_env-python3/lib/python3.10/site-packages/check_migrations_created.py", line 17, in main output = subprocess.check_output( File "/Users/mahdikhaloei/.pyenv/versions/3.10.9/lib/python3.10/subprocess.py", line 421, in check_output return run(*popenargs, stdout=PIPE, timeout=timeout, check=True, File "/Users/mahdikhaloei/.pyenv/versions/3.10.9/lib/python3.10/subprocess.py", line 526, in run raise CalledProcessError(retcode, process.args, subprocess.CalledProcessError: Command 'unset VIRTUAL_ENV; poetry run python3 core/manage.py makemigrations --dry-run' returned non-zero exit status 127. -
How to fix Django Rest Framework TypeError: Direct assignment to the forward side of a many-to-many set is prohibited. Use datasets.set() instead
I have 2 models with many to many relationship Simulators Datasets When I try to run a testcase, I get the following error TypeError: Direct assignment to the forward side of a many-to-many set is prohibited. Use datasets.set() instead. Simulator Model: class Simulator(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) label = models.CharField(max_length=50, unique=True) datasets = models.ManyToManyField(Dataset, related_name="simulators", blank=True) Simulator Serializer: class SimulatorSerializer(serializers.ModelSerializer): datasets = serializers.PrimaryKeyRelatedField(queryset=Dataset.objects.all(), many=True, required=False) class Meta: model = Simulator fields = ( "id", "label", "desc", Simulator Factory class SimulatorFactory(factory.django.DjangoModelFactory): class Meta: model = "simulators.Simulator" id = factory.Faker("uuid4") datasets = [DatasetFactory()] owner = "google-oauth2|fdg" Dataset model: class Dataset(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) file = models.FileField(blank=True, null=True) original_file_name = models.TextField(null=True) label = models.CharField(max_length=50, unique=True) Dataset serializer: class DatasetSerializer(serializers.ModelSerializer): is_valid = serializers.SerializerMethodField() file = serializers.FileField(max_length=None, allow_empty_file=False) class Meta: model = Dataset fields = ( "id", "label", "desc", "url", Dataset factory class DatasetFactory(factory.django.DjangoModelFactory): class Meta: model = "datasets.Dataset" id = factory.Faker("uuid4") label = ''.join(random.choices(string.ascii_u size = 1024 owner = "google-oauth2|ffdfs" When I try to create a new Simulator object with the following 2 different methods, I see the exception self.dataset = DatasetFactory(label=fake.name()) self.simulator = SimulatorFactory(owner="google-oauth2|11574423", datasets=[self.dataset.id]) OR self.dataset = DatasetFactory(label=fake.name()) self.simulator = SimulatorFactory(owner="google-oauth2|11574423") Exception ERROR: test_get_request_returns_a_given_sim_model (apps.simulators.test.test_views.TestSimulatorDetailTestCase) ---------------------------------------------------------------------- Traceback (most recent … -
Django Scrapy custom pipeline save images to model
I have a scrapy custom pipeline to save images to django model. I have overide some methods from the Scrapy ImagePipeline but still images don't saved to model.What method i must ovveride to save images to the django model ? class SearchImagesPipeline(ImagesPipeline): def file_path(self, request, response=None, info=None, *, item=None): filename = request.url.split('/')[-1] domain = urlparse(request.url).netloc return f"{domain}/{filename}" #domain = urlparse(request.url).netloc #return f"full/{domain}/{filename}" def file_downloaded(self, response, request, info, *, item=None): return self.image_downloaded(response, request, info, item=item) def image_downloaded(self, response, request, info, *, item=None): checksum = None for path, image, buf in self.get_images(response, request, info, item=item): if checksum is None: buf.seek(0) checksum = md5sum(buf) width, height = image.size self.store.persist_file( path, buf, info, meta={"width": width, "height": height}, headers={"Content-Type": "image/jpeg"}, ) # create the domai model ddomain, d_created = Domain.objects.get_or_create( title=urlparse(request.url).netloc ) # create the page model page_obj, c_created = Page.objects.get_or_create( domain=ddomain, url=request.url, ) # save image to the MediaFile model media_content = ContentFile(path) MediaFile.objects.create( page=page_obj, media_file=media_content ) return checksum -
Nginx error with django staticfiles "no such file or directory"
I'm trying to make nginx process a request for static files in a django application, but it throws an error [error] 20#20: *1 open() "/home/app/web/staticfiles/admin/css/nav_sidebar.css" failed (2: No such file or directory), client: 172.20.0.1, server: , request: "GET /staticfiles/admin/css/nav_sidebar.css HTTP/1.1", host: "127.0.0.1:1337", referrer: "http://127.0.0.1:1337/admin/" What did i do wrong? I understand that the request comes to the right place, but for some reason it is not possible to make a response from this directory nginx.conf upstream hello_django { server web:8000; } server { listen 80; location / { proxy_pass http://hello_django; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; } location /staticfiles/ { alias /home/app/web/staticfiles/; } } docker-compose.yml version: '3.9' services: web: build: . command: gunicorn pets.wsgi:application --bind 0.0.0.0:8000 volumes: - static_volume:/home/app/web/staticfiles 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 volumes: - static_volume:/home/app/web/staticfiles ports: - 1337:80 depends_on: - web volumes: postgres_data: static_volume: 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 … -
I can not see the templates on my page django
I have my first serious project, I am 16 years old and I have a job and I made a page for this job, I already have the domain, I already have the host. I set the debug to False, and several things in the .env, I already put the domain in the allowed host, and other things, but when I upload the files of my project in FilleZilla, once I enter the page, they only appear the directories that are inside the public_html folder, that is, there I can access the files that I uploaded in filezilla, but the idea is to run the templates, and I don't know how to do it, I can't find help anywhere, no tutorial, nothing. I need someone to help me with this, I'm new. -
ValueError: Unable to configure formatter 'django.server'
I am very new to Python and Django. I am using visual studio code, Python 3.9.12 and Django 4.1.7. i started by trying to execute simple commands in the terminal like django-admin startproject web, but each time I get an error which I pasted below.. What did I miss? it is just made a folder web with nothing inside C:\Users\ASUS\Belajar_Django>django-admin startproject web Traceback (most recent call last): File "C:\Users\ASUS\anaconda3\lib\logging\config.py", line 655, in configure_formatter result = self.configure_custom(config) File "C:\Users\ASUS\anaconda3\lib\logging\config.py", line 474, in configure_custom result = c(**kwargs) File "C:\Users\ASUS\anaconda3\lib\site-packages\django\utils\log.py", line 176, in __init__ super().__init__(*args, **kwargs) TypeError: __init__() got an unexpected keyword argument 'format' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\ASUS\anaconda3\lib\logging\config.py", line 543, in configure formatters[name] = self.configure_formatter( File "C:\Users\ASUS\anaconda3\lib\logging\config.py", line 665, in configure_formatter result = self.configure_custom(config) File "C:\Users\ASUS\anaconda3\lib\logging\config.py", line 474, in configure_custom result = c(**kwargs) File "C:\Users\ASUS\anaconda3\lib\site-packages\django\utils\log.py", line 176, in __init__ super().__init__(*args, **kwargs) File "C:\Users\ASUS\anaconda3\lib\logging\__init__.py", line 574, in __init__ self._style.validate() File "C:\Users\ASUS\anaconda3\lib\logging\__init__.py", line 454, in validate for _, fieldname, spec, conversion in _str_formatter.parse(self._fmt): File "C:\Users\ASUS\anaconda3\lib\string.py", line 259, in parse return _string.formatter_parser(format_string) NameError: name '_string' is not defined The above exception was the direct cause of the following exception: Traceback (most recent call last): … -
subprocess.CalledProcessError: Command 'unset VIRTUAL_ENV; poetry run python3 manage.py makemigrations --dry-run' returned non-zero exit status 127
I install pre-commit. I have a function in my models.py for return a default image: def get_lab_logo_url(): return static("menu/images/lab_logo.png") This function is used in models: class Category(Timestampable, Authorable, Publishable, Permalinkable, Sortable, models.Model): name = models.CharField(max_length=64, verbose_name=_("نام دستهبندی")) subtitle = models.CharField(max_length=64, null=True, blank=True, verbose_name=_("نام فرعی دستهبندی")) image = models.ImageField(upload_to="categories/", blank=False, null=False, default=get_lab_logo_url, verbose_name=_("تصویر دستهبندی")) objects = CategoryManager() Now I want to change this file to svg file: def get_lab_logo_url(): return static("menu/images/lab_logo.svg") when I want commit this change: git add . git commit -m "change logo file" I got this error: subprocess.CalledProcessError: Command 'unset VIRTUAL_ENV; poetry run python3 manage.py makemigrations --dry-run' returned non-zero exit status 127. Thanks for your responses. -
Installing psycopg2==2.8.6 throws an error
I have my website deployed in heroku which uses psycopg2 and when I upgrade version 2.8.6 --> 2.9.1 and greater then it throws an error that database connection isn't set to UTC. And when I tried to install packages from my requirements.txt which consist psycopg2==2.8.6 (using python virtualenv in windows) then it throws following error Using cached psycopg2-2.8.6.tar.gz (383 kB) ERROR: Command errored out with exit status 1: command: 'A:\Projects\django\tmp_env\Scripts\python.exe' -c 'import io, os, sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\Amar K\\AppData\\Local\\Temp\\pip-install-ss0ajkyw\\psycopg2_60877ad816f94182b98212026f2b8d09\\setup.py'"'"'; __file__='"'"'C:\\Users\\Amar K\\AppData\\Local\\Temp\\pip-install-ss0ajkyw\\psycopg2_60877ad816f94182b98212026f2b8d09\\setup.py'"'"';f = getattr(tokenize, '"'"'open'"'"', open)(__file__) if os.path.exists(__file__) else io.StringIO('"'"'from setuptools import setup; setup()'"'"');code = f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' egg_info --egg-base 'C:\Users\Amar K\AppData\Local\Temp\pip-pip-egg-info-pwtcfhhf' cwd: C:\Users\Amar K\AppData\Local\Temp\pip-install-ss0ajkyw\psycopg2_60877ad816f94182b98212026f2b8d09\ Complete output (23 lines): running egg_info creating C:\Users\Amar K\AppData\Local\Temp\pip-pip-egg-info-pwtcfhhf\psycopg2.egg-info writing C:\Users\Amar K\AppData\Local\Temp\pip-pip-egg-info-pwtcfhhf\psycopg2.egg-info\PKG-INFO writing dependency_links to C:\Users\Amar K\AppData\Local\Temp\pip-pip-egg-info-pwtcfhhf\psycopg2.egg-info\dependency_links.txt writing top-level names to C:\Users\Amar K\AppData\Local\Temp\pip-pip-egg-info-pwtcfhhf\psycopg2.egg-info\top_level.txt writing manifest file 'C:\Users\Amar K\AppData\Local\Temp\pip-pip-egg-info-pwtcfhhf\psycopg2.egg-info\SOURCES.txt' Error: pg_config executable not found. pg_config is required to build psycopg2 from source. Please add the directory containing pg_config to the $PATH or specify the full executable path with the option: python setup.py build_ext --pg-config /path/to/pg_config build ... For further information please check the 'doc/src/install.rst' file (also at <https://www.psycopg.org/docs/install.html>). ---------------------------------------- WARNING: Discarding https://files.pythonhosted.org/packages/fd/ae/98cb7a0cbb1d748ee547b058b14604bd0e9bf285a8e0cc5d148f8a8a952e/psycopg2-2.8.6.tar.gz#sha256=fb23f6c71107c37fd667cb4ea363ddeb936b348bbd6449278eb92c189699f543 (from https://pypi.org/simple/psycopg2/) (requires-python:>=2.7,!=3.0.*,!=3.1.*,!=3.2.*,!=3.3.*). Command errored out with exit status 1: python setup.py … -
Convert a Pandas's dataframe to a Django QuerySet
I have a model called Job, in this model I store both the original and duplicated jobs. In addition, I have another model called JobStatistics which stores all statistics of both original and duplicated jobs. I want to group the statistics of the duplicated jobs and added them to the statistics of their original jobs. and return only the original jobs with all statistics. suppose a job with the id of id=10001 that has 2 clicks. this job has 3 duplicates, each has 2,4,8 clicks respectively. the result should be job_id clicks 10001 16 one approach is to convert the QuerySet to a Pandas's datafarme and perform and the grouping in the dataframe. but the problem with this approach is that i couldn't find a proper way to convert a dataframe back to a QuerySet. Why I cannot simply return the dataframe, well because I cannot paginate it with a serialzer. What would be a proper way to handle a situation like this? thank you. # models.py class Job(models.Model): title = models.TextField(_("Job Title")) original_job = models.ForeignKey('self',on_delete=models.CASCADE, null=True, blank=True) ... class JobStatistics(models.Model): job = models.ForeignKey("jobs.Job", verbose_name=_("Metric Job") spend = models.FloatField(_("Spend"), default=0) clicks = models.IntegerField(_("Job Clicks"), default=0) impressions = models.IntegerField(_("Job Impressions"), default=0) … -
Django +Nginx+waitress+AWS Elastic Load balancer-504 Error
I have hosted Djano app on Nginx-waitress architecture.Both are running on different ports on same server.There is an AWS ELB which directs requests to Nginx port. I have a functionality which query database based on user input and produces multiple csv files.These files are then zipped and sent to user for download. user gets 504 error after 2-3 minutes even when the file is being generated /has been generated in server .It takes around 4-5 minutes (for the whole process)to generate 500 Mb zipped file.And the file size is normally greater than 100 Mb in most of the cases. I tried diferent perumation and combination of below setting in nginx and waitress but i am not getting any difference. nginx.conf http { include mime.types; default_type application/octet-stream; include C:/nginx-1.23.3/sites-enabled/senginx.conf; charset utf-8; sendfile on; client_max_body_size 500m; send_timeout 15m; } senginx.conf server { listen 6003; server_name rnd.aicofindia.com; location /static/ { alias C:/Users/Administrator/Desktop/Project/sarus-master/static/; } location /media/ { alias C:/Users/Administrator/Desktop/Project/sarus-master/media/; } location / { proxy_read_timeout 15m; proxy_connect_timeout 15m; proxy_send_timeout 15m; keepalive_timeout 15m; keepalive_time 1h; proxy_socket_keepalive on; proxy_pass http://localhost:9090; } } waitress.conf from waitress import serve from sarus_project.wsgi import application if __name__ == '__main__': serve(application, host = 'localhost', port='9090',channel_timeout=900,cleanup_interval=900) -
When the currentTime is changed, its value becomes 0
When the currentTime is changed, its value becomes 0 HTML <audio id="audio" style="display: none"> <source src="" id="audioSource" type="audio/mpeg"> </audio> <div class="time-control" id="progressBar"> <input id="progress" type="range" style="height: 5px; border-radius: 5px;"> </div> JavaScript let audio = document.getElementById('audio'); let progress = document.getElementById('progress'); progress.addEventListener('click', function(e){ audio.currentTime = (e.offsetX / progress.clientWidth) * audio.duration } Values of variables Values of variables -
Reverse for the admin site
urlpatterns: urlpatterns = [ path('wfgdsgx/', admin.site.urls), ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) \ + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Could you tell me how can I get reverse() for the admin site url? -
How can i use two waitress server for django app
I want to have 2 waitress servers for hosting django web application.One for serving statics and media files of django app and other for django on different ports. I tried some thing like this and hit localhost:6003 in browser,but it is serving only static web page at 6003 and is not interacting with app running at 9090. what am i missing? I have successfully deployed this app usig nginx and waitress.But I dont want this now. app.py from flask import Flask from flask_cors import CORS, cross_origin app = Flask(__name__,) CORS(app) main.py from flask import Blueprint, send_from_directory from waitress import serve from app import app @app.route('/stat/<path:filename>') def static_file(filename): return send_from_directory("D:/static/",filename) @app.route('/med/<path:filename>') def media_file(filename): return send_from_directory("D:/media/",filename) serve(app, host='localhost', port=6003) runserver.py from waitress import serve from sarus_project.wsgi import application if __name__ == '__main__': serve(application, host = 'localhost', port='9090') -
Docker Compose with Django and Postgres Fails with "django.db.utils.OperationalError: could not connect to server:"
I am trying to run my django/postgres application with docker compose. When I run docker compose up -d I get the the following logs on my postgres container running on port 5432: 2023-02-18 00:10:25.049 UTC [1] LOG: starting PostgreSQL 13.8 on aarch64-unknown-linux-musl, compiled by gcc (Alpine 11.2.1_git20220219) 11.2.1 20220219, 64-bit 2023-02-18 00:10:25.049 UTC [1] LOG: listening on IPv4 address "0.0.0.0", port 5432 2023-02-18 00:10:25.049 UTC [1] LOG: listening on IPv6 address "::", port 5432 2023-02-18 00:10:25.052 UTC [1] LOG: listening on Unix socket "/var/run/postgresql/.s.PGSQL.5432" 2023-02-18 00:10:25.054 UTC [22] LOG: database system was shut down at 2023-02-18 00:10:06 UTC 2023-02-18 00:10:25.056 UTC [1] LOG: database system is ready to accept connections It appears my postgres container is working properly. However my python/django container has the following logs: django.db.utils.OperationalError: could not connect to server: Connection refused Is the server running on host "127.0.0.1" and accepting TCP/IP connections on port 5432? docker-compose.yml version: '3.8' services: web: build: . command: sh -c "python manage.py runserver 0.0.0.0:8000" volumes: - .:/code ports: - "8000:8000" env_file: - ./xi/.env depends_on: - db db: image: postgres:13-alpine environment: - POSTGRES_DB=*** - POSTGRES_USER=*** - POSTGRES_PASSWORD=*** volumes: - dev-db-data:/var/lib/postgresql/data ports: - 5432:5432 volumes: dev-db-data: Dockerfile: FROM python:3.8 ENV PYTHONDONTWRITEBYTECODE=1 ENV PYTHONUNBUFFERED=1 WORKDIR … -
GET /css/styles.css HTTP/1.1" 404 3609 Python
Im developing a website on python and I found a theme that I like on the internet. It includes the index.html, css folder, js folder and the images. Like in other projects I copies all of the data into the templates folder in my project. I replaced my base.html with this new index.html. The problem is that Django can't find the css and js folders that are being references in the html. I have read some post about this, and everybody mentions taking the index.html outside of templates (doesn't work) or using a static folder to store my css and js files (doesn't work. Can someone give me some clues? thank you!! Project mysite templates assets css js index.html -
Why am I able to insert invalid data into database?
This is my models.py file: from django.db import models # Create your models here. class FxRates(models.Model): business_date = models.DateField() country = models.CharField(max_length=1000) currency_code = models.CharField(max_length=3) exchange_rate = models.FloatField() class Meta: db_table = "FxRates" Using the "migrate" command I am able to create the FxRates database table in the db.sqlite3. Now if I use Pandas to insert data into this database, no errors are thrown if for this line in my data.csv file: 24/01/2023,Bangladesh,BDT,ERR! Shouldn't this have been impossible to insert, considering ERR! is not a number? The Pandas commands I use are: df = pandas.read_csv("/home/data.csv") database_path = "<path_to_db.sqlite3>" connection = sqlite3.connect(database_path) df.to_sql("FxRates", connection, if_exists= "append", index=False) This inserts all the data fine, but why does it let invalid data be inserted? -
django built-in class based view - Where is self.object from?
In the following code, I don't understand something. class SingleObjectMixin(ContextMixin): """ Provide the ability to retrieve a single object for further manipulation. """ model = None queryset = None slug_field = 'slug' context_object_name = None slug_url_kwarg = 'slug' pk_url_kwarg = 'pk' query_pk_and_slug = False ... ... def get_context_data(self, **kwargs): """Insert the single object into the context dict.""" context = {} if self.object: context['object'] = self.object context_object_name = self.get_context_object_name(self.object) if context_object_name: context[context_object_name] = self.object context.update(kwargs) return super().get_context_data(**context) There is an atrribute self.object' in method get_context_data. I would like to figure out where the attribute `object' is created from. -
How to make elided pagination work in django-tables2
I am trying to use django-tables2 v2.5.2 to render a table of products. Pagination renders correctly, it basically looks like: ['prev',1,2,3,4,5,'...',18,'next'] each button is tag with href='?page=x' and after click it updates url with the page parameter but ellpsis button ('...') has href='#' and obviously does nothing when clicked on. Other pages buttons works fine. Do you have any idea how to setup django and/or django-tables2 to make elided pagination work? I am trying to setup simple table with products. I am using function view and RequestConfig, like this: views.py def product_list(request: HttpRequest): all_items = Product.objects.all().order_by("-publish_date") product_filter = ProductFilter(request.GET, queryset=all_items) table = ProductTable(product_filter.qs) RequestConfig(request, paginate={"per_page": 5}).configure(table) return render( request, "product/product_list.html", {"table": table, "filter": product_filter} ) and my tables.py code looks like this: class ProductTable(tables.Table): image_url = ImageColumn(verbose_name="Image") publish_date = tables.DateColumn(format="d M Y", order_by=["publish_date"]) user = tables.Column(verbose_name="Verified by") title = tables.Column(verbose_name="Product") class Meta: model = Product template_name = "django_tables2/bootstrap.html" sequence = ("title", "producer", "user", "status", "publish_date", "image_url") exclude = ("id", "image_url") filterset_class = ProductFilter I tried to read documentation to django-tables2 and django framework but I think I must be missing something. I am expecting the ellipsis button in pagination to load missing page range, so I guess it needs to … -
Creating a user using Djoser authentication is returning a 405 Method Not Allowed Error
I am using django and djoser for authentication. By testing the creation of the user using Postman at http://localhost:8000/auth/users using POST method, I am receiving a 405 Method Not Allowed Error. I am using an SQLite Database and already created a custom user model to use with Djoser: I already added an X-CSRFToken key and it's secret key in the Headers of the request,and made sure that the method is POST. -
why is my Jquery .on(clicked) function not getting clicked correctly?
I am trying to make - and + buttons to add items to shopping cart and I am using internal Jquery .on("click") to execute that. but it is neither performing any task nor is it actually getting clicked, it is not even showing the presence of jquery on inspection I want those button to get clicked and item to be added in cart -
"Authentication details were not provided." Django jwt
I've created a view for getting details of the user's profile. user_views.py @api_view(['GET']) @permission_classes([IsAuthenticated]) def getUserProfile(request): user = request.user serializer = UserSerializer(user, many=False) return Response(serializer.data) urls.py urlpatterns = [ path("/users/profile/", uv.getUserProfile, name="get-user-profile") ] serializers.py class UserSerializer(serializers.ModelSerializer): name = serializers.SerializerMethodField(read_only=True) isAdmin = serializers.SerializerMethodField(read_only=True) class Meta: model = User fields = ['id', 'username', 'email', 'name', 'isAdmin'] def get_id(self, obj): return obj.id def get_isAdmin(self, obj): return obj.is_staff def get_name(self, obj): name = obj.first_name if name == '': name = obj.email return name class UserSerializerWithToken(UserSerializer): token = serializers.SerializerMethodField(read_only=True) class Meta: model = User fields = ['id', 'username', 'email', 'name', 'isAdmin', 'token'] def get_token(self, obj): token = RefreshToken.for_user(obj) return str(token.access_token) I'm sending a get request through post man and sending a authorization header with Bearer <token>. And got { "detail": "Authentication details were not provided." } Using django-rest-framework and django-rest-framework-simplejwt. -
Is it possible to upload a django webapp for free
I followed a course where I made a django app like this https://www.studybud.dev/ and always get error when trying to upload it, I don't even have a solid understanding on how to uplaod my django website. I watched lots of videos but all of them were poor as none of them worked. Tried uploading it for more than a month but with no avail, I tried using heroku,python anywhere and many others but some of them required credit card info and others don't work. I would appreciate any form of help. -
How can I scale up my django app to utilize 4 cores and 8 threads?
I have a Django app. I am about to move this from a single core system to a multi core system. (8 threads because of hyperthreading) I am trying to figure out the changes I need to make to utilize all of the cores and all of the threads. I looked around and found bunch of settings for Rails. I can not find similar settings for Django online. I found an article that says, I don't need to make any changes to Django. I should just use gunicorn to run 8 instances to utilize 8 threads, but this did not make sense to me. What do I need to change to make sure my app utilizes 8 threads without wasting resources. Thanks in advance for your help. -
how to use delete() query in django?
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 instance but in final part, delete() query does not accept input such as id or variable to remove specific thing in one field. image 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? -
selinium slow preformance on realtime Django project
I'm working on a project which I'm getting posts from couple of websites and show it in the main page of my website but with filter and letting users to search for keywords and see the posts with that keywords. this is how the code works : In here with get the customized url of the site with our keyword and city filter def link_gen(city='', Kword='' ): # for example.com urls =[] if Kword != '': if city =='': url = f'https://www.example.com/search/with{Kword}' url = url.strip() url = url.replace(" ", "-") urls.append(url) else: url = f'https://www.example.com/search/with{Kword}in{city}' url = url.strip() url = url.replace(" ", "-") urls.append(url) else: if city != '': url = f'https://www.example.com/search/in{city}' url = url.strip() url = url.replace(" ", "-") urls.append(url) else: urls.append('none') return urls this part is where we crawl for the posts of the target website # function for getting the title, link, icon, desc of all posts def get_cards(urls): data = [] # for example.com if urls[0] != 'none': # we use webdriver to get site with dynamic component and design url = urls[0] options = Options() options.headless = True browser = webdriver.Firefox(options=options) browser.get(url) print ("Headless Firefox Initialized") soup = BeautifulSoup(browser.page_source, 'html.parser') jobs = soup.find_all( 'div', class_="job-list-item", …