Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to enable partial searches for all fields?
Imagine I ahve the following filters.py: class ActionFilter(django_filters.FilterSet): class Meta: model = Action fields = "__all__" Now, I want to enable partial searches for Charfield fields in my model. How can this be enabled? -
Firefox refresh doesn't update web page after input fileds changed in the form without submit
I just noticed that my django web application doesn't update the input fields changed just in the form (page) after referesh in Firefox. So every press of F5- or refresh-button invokes http GET that returns the contents of the database. But if I have changed some input fields in my web page (wihout submit) in Firefox they won't become updated with the values in database. If I repeat this in Chrome the fields become updated correctly. What can be causing this? And how can I confirm that after every refresh my page would show exactly what has been stored in the database ? -
Django Elastic Beanstalk hosted application server not found
I have a Django application that I'm hosting with Elastic Beanstalk. I have setup a hosted zone & configured it with a new domain name. The site is accessible from the domain I setup & works fine, but for some reason at random times I will run into "We can’t connect to the server at www.***.com" for no apparent reason. The health of my environment says 'Ok' & I can't see any reason that it shouldn't be finding the server. I'm all out of ideas as to why I'm running into this error on occasion. (Note: It's not an internet issue, I have tried on many different devices & connections and the issues still arises after a few refreshes or route changes.) -
set the default selected item as the same for a value get from DB in Django
I have a web app using Django as the backend. In the frontend, there's a selection box. The default selection should be the same as a value get from DB. {% with query_results_book_discard_reason=query_results_book_discard_reason|index:forloop.parentloop.counter0 %} <select style="display: none" name="discard_reason" class="MySelect"> <option value="">--Select--</option> <option value="Change edition">Change edition</option> <option value="Change to eTextbook">Change to eTextbook</option> <option value="Change title">Change title</option> <option value="No material required">No material required</option> </select> {% endwith %} {{ query_results_book_discard_reason.discard_reason }} is the value from DB that would match the selection box. If {{ query_results_book_discard_reason.discard_reason }} is equal to "Change edition", the default selected item should be "Change edition" in the selection box. If {{ query_results_book_discard_reason.discard_reason }} is equal to "Change to eTextbook", the default selected item should be "Change to eTextbook" in the selection box. ... If {{ query_results_book_discard_reason.discard_reason }} is equal to None, the selection box should be original. How could managed to do that? -
Django - Raw query to ORM
models.py class Employees(models.Model): emp_no = models.IntegerField(primary_key=True) birth_date = models.DateField() first_name = models.CharField(max_length=14) last_name = models.CharField(max_length=16) gender = models.CharField(max_length=1) hire_date = models.DateField() class Meta: managed = False db_table = 'employees' class Salaries(models.Model): emp_no = models.ForeignKey(Employees, models.DO_NOTHING, db_column='emp_no',related_name='salaries', primary_key=True) salary = models.IntegerField() from_date = models.DateField() to_date = models.DateField() class Meta: managed = False db_table = 'salaries' unique_together = (('emp_no', 'from_date'),) Mysql raw query: SELECT `employees`.`emp_no`, `employees`.`birth_date`, `employees`.`first_name`, `employees`.`last_name`, `employees`.`gender`, `employees`.`hire_date`, ( SELECT JSON_ARRAYAGG( JSON_OBJECT( 'salary', `salaries`.`salary`, 'from_date', `salaries`.`from_date`, 'to_date', `salaries`.`to_date` ) ) FROM `salaries` WHERE (`employees`.`emp_no` = `salaries`.`emp_no`) ) as salaries FROM `employees` INNER JOIN `salaries` root_salaries ON `root_salaries`.`salary` > 60000 WHERE `employees`.`emp_no` = `root_salaries`.`emp_no` LIMIT 100 OFFSET 100 My question is how to generate the above raw query using Django ORM. Thanks. -
How do i let user know their active login sessions like the one we get in telegram?
I want to add a feature where user can see from how many devices they are logged in. All devices like operating system, the time they logged in , last time they were active from that device etc. -
how to submit order form and get redirect to the user's page to see all others made by the user
i am developing an app where customers can make orders and get redirected to a page to see all the orders requested but i am getting error here. below is the error message.All i want is for a user who's registered to make order and get redirected to a page where all his orders will be displayed . i will appreciate if someone could help me out here . i am developing an app where customers can make orders and get redirected to a page to see all the orders requested but i am getting error here. below is the error message.All i want is for a user who's registered to make order and get redirected to a page where all his orders will be displayed . i will appreciate if someone could help me out here . here is the error message: IntegrityError at /clients/add_item/ null value in column "location_id" of relation "clients_clientjob" violates not-null constraint DETAIL: Failing row contains (2, , null, , , , 2021-07-14 12:10:05.555719+00, Pending, 2, null). Request Method: POST Request URL: https://canwork.herokuapp.com/clients/add_item/ Django Version: 3.1 Exception Type: IntegrityError Exception Value: null value in column "location_id" of relation "clients_clientjob" violates not-null constraint DETAIL: Failing row … -
Django template variable default value not working
I am using Django 3.2 I am passing a boolean flag to a Javascript function in my base template. However, when the variable is set, it seems the default value is still being used in my template logic. Here is my code snippet: /path/to/urls.py urlpatterns = [ # ... path('foo', TemplateView.as_view(template_name="foo.html", extra_context={'show_subscription_popup':0}), name='blog'), path('admin/', admin.site.urls), ] /path/to/foo.html {% block content %} <span>{{ show_subscription_popup}}</span> {% endblock content %} {% block body_js %} <script type="text/js"> $().ready(function() { let popDisplayed = '0'; if ({{ show_subscription_popup|default:1 }}){ popDisplayed = getCookie('popDisplayed'); } /* remaining logic ... */ }); </script> When I render the page, I see that the variable show_subscription_popup has the correct value of 0, which it is passed to the TemplateView, however, in the javascript, the code reads like this: if (1){ /* do something */ } Why is the default value overwriting the value I passed to the template, and how do I resolve this issue? -
account activation email in django giving error
i got the issue with sending email for account activation in django. all email was sending including activation when the project was on development, since i took the project to the server running on nginx the activation email, after user account registration is not sending and giving this error SMTPDataError at /users/register/ (550, b'5.7.1 Reject for policy reason') i thought is the email settings but all other sending emails from the project are working , expect the one in registration. -
I setup multiple category product like ecommerce but my view showing per category just 1 item. I want to view per category 10 iteams
This is my view.py code This is my index.html code -
How do we define Django Rest Framework project apps & folder structure
Currently, I'm building an Affiliate system API using DRF. This project has 2 API directions: Internal API for front-end External API for tracking affiliate links And that's how I define my Django APP: Internal_API namely api External_API namely api_external However, Internal_API app needs to access External_API models, and each of the apps has a very massive list of models, serializers, and views. The main entities are: Affiliate (Player) Enterprise (Campaign creator) Campaign (Where affiliate plays) Order (if someone buys through link) Traffic (tracks affiliate link) and mapping tables. This is the current project structure (simplified): backend ├── api │ ├── admin.py │ ├── apps.py │ ├── models │ │ ├── affiliate.py │ │ ├── affiliateEnterprise.py │ │ ├── campaign.py │ │ ├── enterprise.py │ ├── send_emails.py │ ├── serializers │ │ ├── affiliate.py │ │ ├── affiliateEnterprise.py │ │ ├── campaign.py │ │ ├── campaignAffiliate.py │ │ ├── enterprise.py │ │ ├── order.py │ │ ├── traffic.py │ ├── urls.py │ └── views │ ├── affiliate.py │ ├── affiliateEnterprise.py │ ├── campaign.py │ ├── campaignAffiliate.py │ ├── enterprise.py │ ├── order.py │ ├── traffic.py ├── api_external │ ├── admin.py │ ├── apps.py │ ├── models │ │ ├── order.py │ … -
How to integrate the tradingview charting_library in the django app?
I have customized the tradeview chart and want to use it in my django app both locally and in production. The chart is running on its own server localhost:5000 while the django app is running on localhost:8000. How can I integrate the chart in the django app. Even if I try to serve the library files using Django server, Django is unable to find some of the HTML files in the library. -
Why Cannot call web site Django with sub domain name
I got the trouble for deployment Django app on IIS SErver, it is about the host IP /subdomain for the Django web application on the intranet. This IP has been created record in the DNS server on the intranet already. but this website can’t be requested by subdomain name, Yet I can call web site by IP successfully. IP and domain name mapping is 17x.xxx.xx.48 = es-xxx.xxx.com This is an error, you can see The error on the left-hand side of this screenshot below. ** dial tcp: lookup es-xxx.xxxx.com on 127.0.0.11:53: no such host** I used to develop ASP.NET and deploy on IIS Server, there is no problem with this issue. This is my configuration both in settings.py and IIS server. I already attempted to use nslookup and it is fine as the figure below. -
Django javascript-catalog missing data from .po file
I am trying to set up a javascript-catalog translation for my project, but to me it seems it is not reading the .po/.mo files My url patterns: urlpatterns = i18n_patterns( .... path('jsi18n/', JavaScriptCatalog.as_view(), name='javascript-catalog'), .... ) I have this header in my template: <script type="text/javascript" src="{% url 'javascript-catalog' %}"></script> After checking the source of the rendered template for "Hungarian" language I see a bunch or default translations in the JS catalog file, but not the ones I defined in the .po file: const newcatalog = { "%(sel)s of %(cnt)s selected": [ "%(sel)s/%(cnt)s kijel\u00f6lve", "%(sel)s/%(cnt)s kijel\u00f6lve" ], "6 a.m.": "Reggel 6 \u00f3ra", "6 p.m.": "Este 6 \u00f3ra", "April": "\u00e1prilis", "August": "augusztus", "Available %s": "El\u00e9rhet\u0151 %s", "Cancel": "M\u00e9gsem", "Choose": "V\u00e1laszt\u00e1s", "Choose a Date": "V\u00e1lassza ki a d\u00e1tumot", "Choose a Time": "V\u00e1lassza ki az id\u0151t", "Choose a time": "V\u00e1lassza ki az id\u0151t", "Choose all": "Mindet kijel\u00f6lni", "Chosen %s": "%s kiv\u00e1lasztva", "Click to choose all %s at once.": "Kattintson az \u00f6sszes %s kiv\u00e1laszt\u00e1s\u00e1hoz.", "Click to remove all chosen %s at once.": "Kattintson az \u00f6sszes %s elt\u00e1vol\u00edt\u00e1s\u00e1hoz.", "December": "december", "February": "febru\u00e1r", "Filter": "Sz\u0171r\u0151", "Hide": "Elrejt", ... In my .po file I have: msgid "Routes" msgstr "Utak" Which is compiled into a .mo file, however when … -
Nginx, Django, Gunicorn, working without config file?
I am making a website on django with gunicorn, nginx, on a amazon linux EC2 instance. To deploy the website I use gunicorn --worker-class gevent --bind 0.0.0.0:8000 myapp.wsgi I am using nginx, and everything is working the thing that is weird is that all the static files are working, without me serving them in sudo vi /etc/nginx/nginx.conf. My config file is just the default and its still working. Does django serve static files for you through urls.py in urlpatterns = []+ static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)... here is my config file # For more information on configuration, see: # * Official English Documentation: http://nginx.org/en/docs/ # * Official Russian Documentation: http://nginx.org/ru/docs/ user nginx; worker_processes auto; error_log /var/log/nginx/error.log; pid /run/nginx.pid; # Load dynamic modules. See /usr/share/doc/nginx/README.dynamic. include /usr/share/nginx/modules/*.conf; events { worker_connections 1024; } http { log_format main '$remote_addr - $remote_user [$time_local] "$request" ' '$status $body_bytes_sent "$http_referer" ' '"$http_user_agent" "$http_x_forwarded_for"'; access_log /var/log/nginx/access.log main; sendfile on; tcp_nopush on; tcp_nodelay on; keepalive_timeout 300; types_hash_max_size 4096; include /etc/nginx/mime.types; default_type application/octet-stream; # Load modular configuration files from the /etc/nginx/conf.d directory. # See http://nginx.org/en/docs/ngx_core_module.html#include # for more information. include /etc/nginx/conf.d/*.conf; server { listen 80; listen [::]:80; server_name _; root /usr/share/nginx/html; # Load configuration files for the default server block. include /etc/nginx/default.d/*.conf; … -
Django admin, how to use model to add fields into another
I want to create a class that can be extended by users. I think in something similar to: class User(model.Models): name = models.CharField(max_length=30) class UserAttributes(model.Models): attribute_name = models.CharField(max_length=30) attribute_value = models.CharField(max_length=30) What I want is that when I create an UserAttribute in the admin, it appear in the user admin panel to modify. Ideally, I would don't need to see the attribute value in the UserAttribute form, only in User's one. -
Not able to get flow link in my viewflow application
I'm using viewflow engine in my django project to render the workflow in UI.On running the local server I'm not able to see the "flow" link on left bottom part of the screen which is used to see the graphical representation of workflow.Am I missing any step ? Please help .I can see all the steps of workflow written linearly on dashboard but can't find graphical view of the flow. -
TemplateDoesNotExist atDjango deploy error
Hope, you can help me. I made a django project (just in study) and trying to deploy it with djangogirls tutorial. Okay, it works. But! When i trying to go to my website https://anle93.pythonanywhere.com, I have this: Page not found (404) Request Method: GET Request URL: http://anle93.pythonanywhere.com/ Using the URLconf defined in personal_portfolio.urls, Django tried these URL patterns, in this order: admin/ projects/ The empty path didn’t match any of these. It's okay cause I havent any pages in all project. So. When i go to admin, it works(http://anle93.pythonanywhere.com/admin/login/?next=/admin/), I see username and pswd fields. AND when I try to go to my "projects" (https://anle93.pythonanywhere.com/projects/), i have this error first screen on screen. So, my project have this sctructure like on screenscreen2.2. So the question is: I understand, that django cant find base.html file, that extends project_detail.html and project_index.html, and this is the bs4 styles for all project, not for one this app I made, so, if i wonna make any additions like, for example "project_description.html" in new app, it will extends "base.html" too. Ofc, in localhost in works like as needed. I cant understand why it happens after deploy. -
does not exist error in django when trying to delete a user from the admin panel
I am using Django signals I get this type of error when I try to delete a user from the admin panel These is my signal.py file: from django.db.models.signals import post_save, post_delete from django.contrib.auth.models import User from .models import Profile def createProfile(sender, instance, created, **kwargs): print("Profile signal triggered") if created: user = instance profile = Profile.objects.create( user=user, username=user.username, email=user.email, name=user.first_name, ) def deleteUser(sender, instance, **kwargs): user = instance.user user.delete() post_save.connect(createProfile, sender=User) post_delete.connect(deleteUser, sender=Profile) and here is my models: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, null=True, blank=True) name = models.CharField(max_length=200, blank=True, null=True) email = models.EmailField(max_length=500, blank=True, null=True) username = models.CharField(max_length=200, blank=True, null=True) location = models.CharField(max_length=200, blank=True, null=True) short_intro = models.CharField(max_length=200, blank=True, null=True) bio = models.TextField(blank=True, null=True) profile_image = models.ImageField( null=True, blank=True, upload_to="profiles/", default="profiles/user-default.png", ) social_github = models.URLField( blank=True, null=True, validators=[validate_url_github] ) social_twitter = models.CharField( max_length=200, blank=True, null=True, validators=[validate_url_twitter] ) social_linkedin = models.CharField( max_length=200, blank=True, null=True, validators=[validate_url_linkedin] ) social_youtube = models.CharField( max_length=200, blank=True, null=True, validators=[validate_url_yt] ) social_website = models.CharField(max_length=200, blank=True, null=True) created = models.DateTimeField(auto_now_add=True) id = models.UUIDField( default=uuid.uuid4, unique=True, primary_key=True, editable=False ) def __str__(self): return str(self.username) and here is my app.py file from django.apps import AppConfig class UsersConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'users' def ready(self): import users.signals Please answer why do … -
403 Forbidden - Apache2
when Im typing my DomainName witout www at the beginning, I have SSL certificate and everything is Ok. When Im going with www.(DomainName.com) or putting my elastic IP from AWS im facing: 403 Forbidden You don't have permission to access this resource. Where should I look for the issu.. sites-available, permisions sudo chown :www-data ~/myproject? -
docker container with django gunicorn nginx
I am trying to dockerize django using gunicorn and nginx into a docker image. Running docker-compose up --detach --build Everything builds successfully. But gunicorn is not starting. Error log says: bash: /home/soccer/venv/bin/gunicorn: /Users/Umar/PycharmProjects/soccer/venv/bin/python: bad interpreter: No such file or directory How can I fix this? Dockerfile: # pull official base image FROM python:3.7 # accept arguments ARG PIP_REQUIREMENTS=production.txt # set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # install dependencies RUN pip install --upgrade pip setuptools # create user for the Django project RUN useradd -ms /bin/bash soccer # set current user USER soccer # set work directory WORKDIR /home/soccer # create and activate virtual environment RUN python3 -m venv venv # copy and install pip requirements COPY --chown=soccer ./requirements /home/soccer/requirements/ RUN pip3 install -r /home/soccer/requirements/${PIP_REQUIREMENTS} # copy Django project files COPY --chown=soccer . /home/soccer/ docker-compose.yml: version: "3.8" services: nginx: image: nginx:latest ports: - "80:80" volumes: - ./config/nginx/conf.d:/etc/nginx/conf.d - static_volume:/home/soccer/static - media_volume:/home/soccer/media depends_on: - gunicorn gunicorn: build: context: . args: PIP_REQUIREMENTS: "${PIP_REQUIREMENTS}" command: bash -c "/home/soccer/venv/bin/gunicorn --workers 3 --bind 0.0.0.0:8000 soccer.wsgi:application" depends_on: - db volumes: - static_volume:/home/soccer/static - media_volume:/home/soccer/media expose: - "8000" environment: DJANGO_SETTINGS_MODULE: "${DJANGO_SETTINGS_MODULE}" DJANGO_SECRET_KEY: "${DJANGO_SECRET_KEY}" DATABASE_NAME: "${DATABASE_NAME}" DATABASE_USER: "${DATABASE_USER}" DATABASE_PASSWORD: "${DATABASE_PASSWORD}" db: image: postgres:latest restart: always environment: … -
How to get a random element of the filtered queryset efficiently?
I try to pull a random object from the already filtered queryset this way: Product.objects.filter(active=True).order_by('?').first() Currently it is solved with .order_by('?') but it seems to be very slow. I try to implement the solution of this question to my view. It does not work so I am not sure if I am doing it the right way. products = Product.objects.filter( active=True, ) count = products.aggregate(count=Count('id'))['count'] random_index = randint(0, count - 1) product = products[random_index] This is my code now and it throws the ValueError: ValueError: low >= high Please, help me to speed it up. -
How do u solve django.db.utils.OperationalError: fe_sendauth: no password supplied when you are creating a django super user
django.db.utils.OperationalError: fe_sendauth: no password supplied DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'sobs', 'USER': 'ahmed', 'PASS': str(os.environ.get("PASS")), 'HOST': 'localhost' } } -
Django Serializer always returns the value as null when accessing with foreign key
In models.py class ExamplePublication(models.Model): name=models.CharField(max_length=20) class Meta: managed = False db_table = 'xxx' class ExampleBook(models.Model): publication = models.ForeignKey(ExamplePublication, models.DO_NOTHING, related_name='egpublication') title = models.CharField(max_length=20) class Meta: managed = False db_table = 'xxx' class Example(models.Model): book = models.ForeignKey(ExampleBook, models.DO_NOTHING, related_name='egbook') author = models.ForeignKey(ExampleAuthor, models.DO_NOTHING, related_name='egauthor') city = models.CharField(max_length=20) class Meta: managed = False db_table = 'xxx' In serializer.py, class ExampleSerializer(serializers.ModelSerializer): publicationname = serializers.ReadOnlyField(source='book.publication.name',read_only=True) class Meta: model = Example fields = ('city','publicationname') Here the publicationname always returning null I could not find the exact reason or Is my approach wrong with using foreign keys. Any help would be fine :) Thanks -
How to properly write a Django view for a Patch request
So I am making a view in Django, and I'm trying to use POST for creation, GET for fetching, I wanted to use PATCH for handling updations, but I am struggling to understand how to process an incoming PATCH request's data. I am sending a PATCH request in POSTMAN, with form-data(key-value pairs), but when trying to access the data, request.POST or request.PATCH or request.data dont work. Only thing that works is request.body which is a byte string that I have to decode and I don't want to do something like that just to access the data, is there a better way to do this? My question is, what is the right way to make a PATCH view and how to handle the data from an incoming request? Handling POST data seems so straightforward by doing request.POST, why is PATCH not as straightforward? What do i do? Should I not be using PATCH then? Is it better to use POST for updation as well?