Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
React: how to pass a string into a body request
I have this method: export const createProject = async (project) => { fetch(`/api/projects/new/`, { method: "POST", headers: { 'Content-Type': 'application/json' }, body: { 'name': project } }) } which calls a django backend that creates a new project with the given name. The problem is that when the api is called, django outputs BadRequest /api/projects/new/ The backend works for sure, as I tested it with postman. What is wrong with the request made by the front end? -
dj-rest-auth sending invalid password rest links
In my Django Rest Framework, the users request to reset the password and when the email is received everytime the link is clicked it shows a message Password reset unsuccessful The password reset link was invalid, possibly because it has already been used. Please request a new password reset. here is what I have tried API urls.py app_name = 'api' router = routers.DefaultRouter() router.register(r'users', UserViewSet, basename='user') urlpatterns = [ path('', include(router.urls)), path('dj-rest-auth/', include('dj_rest_auth.urls')), path('dj-rest-auth/registration/', include('dj_rest_auth.registration.urls')), path('token/', TokenObtainPairView.as_view(), name='token_obtain_pair'), path('token/refresh/', TokenRefreshView.as_view(), name='token_refresh'), # path('password_reset/',PasswordResetView.as_view(), name='password_reset'), # path('password_reset_confirm/<uidb64>/<token>/', PasswordResetConfirmView.as_view(), name='password_reset_confirm'), ] here is the users app urls.py if required: 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 is: Why do I keep receiving invalid links and how can I fix it? In different questions I got answers to add the commented paths but still did not work. Any suggestions on how to fix it ? -
django show pagination links First , Previous , Next , Last on edit page that uses UpdateView or DetailView
I am using django 3.2 along with datatables and bootstrap 5. it shows pagination correctly using datatables. I want to show Links/buttons like First, previous,Next and Last on edit productstatus form using datatables pagination or django pagination django.core.paginator whose details as shown below class ProductStatus(models.Model): ProductID = models.CharField(max_length=512, verbose_name="ProductID", null=False, blank=False) Description = models.CharField(max_length=512, verbose_name="Description", null=True, blank=True) CreateDate = models.DateTimeField(verbose_name=_("CreateDate"), blank=True) modificationtime = models.DateTimeField(verbose_name="modificationtime", null=True, blank=True, ) . . . . def __str__(self): return self.ProductID def get_absolute_url(self): return reverse('productdetail', args=[str(self.id)]) urls.py has entry path('editproduct/int:pk/edit/', EditProductView.as_view(), name='editproduct'), views,py contains following class EditProductView(LoginRequiredMixin, UpdateView): model = ProductStatus template_name = 'editproduct.html' form_class = EditProductStatusForm login_url = 'login' def form_valid(self, form): editedproduct = form.save(commit=False) editedproduct.modificationtime = timezone.now() editedproduct.save() # self.object = editedproduct return super().form_valid(form) Forms.py contains class EditProductStatusForm(forms.ModelForm): class Meta: model = ProductStatus editproduct html looks as below {% extends 'base.html' %} {% load crispy_forms_tags %} {% block content %} <br> <!-- show 4 links in bootstrap navigation bar --> <nav class="navbar navbar-expand-lg navbar-light"> <div class="container-fluid "> <div class="nav navbar-left"> <ul class="nav navbar-nav"> <li><a class="btn btn-info btn-sm" style="padding-left:0px;margin-left:10px" href="#" role="button">&laquo; First</a></li> <li><a class="btn btn-info btn-sm" style="padding-left:0px;margin-left:10px" href="#" role="button">&#8249; Previous</a></li> </ul> </div> <div class="nav navbar-right"> <ul class="nav navbar-nav"> <li> <a class="btn btn-info btn-sm" style="padding-left:0px;margin-left:10px" href="#" … -
Trying to restric a queryset in Django base on foreign key relationship
I am trying to make a form in Django that gives the user a limited selection based on a foreign key. To be more exact, the form has 2 fields, a ModelChoiceField and a simple text field. This form's purpose is to allow a user to add a Riddle to a previously created Room. So the goal is to limit the ModelChoiceField to only allow the currently logged-in user to add riddles to just their own rooms. forms.py: from django import forms from .models import Project, Riddle class ProjectForm(forms.ModelForm): class Meta: model = Project fields = ['title', 'max_players', 'has_actor', 'scenario'] class RiddleForm(forms.ModelForm): project = forms.ModelChoiceField(queryset=Project.objects.all(), empty_label=None, widget=forms.Select(attrs={'class': 'form-control'}), label='Project') class Meta: model = Riddle fields = ['project','description'] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['project'].queryset = Project.objects.all() self.fields['project'].label_from_instance = lambda obj: obj.title models.py: from django.db import models from django.contrib.auth import get_user_model from django.urls import reverse User = get_user_model() class Project(models.Model): title = models.CharField(max_length=255, unique=True) max_players = models.PositiveIntegerField(default=0) has_actor = models.BooleanField(default=False) scenario = models.TextField(blank=True, null=True) #number_of_riddles = models.PositiveIntegerField(default=0) user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='rooms') def get_absolute_url(self): return reverse( "rooms:project_list", kwargs={ "username": self.user.username, #"pk": self.pk } ) class Riddle(models.Model): project = models.ForeignKey(Project, on_delete=models.CASCADE) description = models.TextField() urls.py: from django.urls import path from .views import … -
How to display images accourding to choise from dropdown?
I'm creating a Django website where I want to implement such functionality. There will be one Dropdown list and one submit button. When user selects any item from dropdown list - An image according to user selection will be displayed. ie. There's drop-down list containing names of animals and one submit button. When user selects any animal from list, photo/details of that animal should appear before pressing submit button. I don't know how to create link between them. Any reference to such work or advice would be appreciate. Thank you :) -
Django MySQL Table already exists
I have django running on ubuntu, and I am trying to set it up with mysql as db. I followed these (1, 2, 3) guides, but when I run python manage.py migrate --run-syncdb I get the error django.db.utils.OperationalError: (1050, "Table 'app_mymodel' already exists"). How do I fix this (I am using MySQL version 5.7.41, Ubuntu 18.04, Python 3.6, Django 3.2)? -
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.