Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
GET /student HTTP/1.1" 200 2 Django
i am beginner to django i have created new project project. when i run the project yesterday worked successfully. if i tried today i ran into the problem with i attached complete stacktrace below. when view the records type api http://127.0.0.1:8000/student then Api display as [] just black see the error on console look like this System check identified no issues (0 silenced). May 04, 2023 - 13:39:40 Django version 3.2, using settings 'SchoolProject.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. [04/May/2023 13:39:46] "GET /student HTTP/1.1" 200 2 [04/May/2023 13:39:46] "GET /student HTTP/1.1" 200 2 [04/May/2023 13:39:47] "GET /student HTTP/1.1" 200 2 [04/May/2023 13:39:47] "GET /student HTTP/1.1" 200 2 [04/May/2023 13:39:47] "GET /student HTTP/1.1" 200 2 [04/May/2023 13:39:47] "GET /student HTTP/1.1" 200 2 -
Why does my React website open in Safari but not in Chrome. The IP address works on both browsers, however the domain only works on one
I pointed a domain (www.mynacode.com) to my AWS instance IP address (34.228.112.169) running my django+react website. The IP address works fine and my website loads on all browsers. However, when I use the domain mynacode.com, my website only opens up on Safari and Mozilla, but not on Chrome. On Chrome, it gives an error: This site can't be reached. Is there a reason why it doesn't work on Chrome. I've cleared the cache, tried opening in incognito mode and even tried it on another laptop but it still won't open in Chrome. -
get all values of same row name in a list in django
[img2] img1 what i want is Apple-[Jessica,mathewo,Anthony] etc etc for each company queryset1 = (Company.objects.values('name',).annotate(total=Count('employeename'),).order_by()) gives me image1, it gives me total number of employee each company has but not values in detail. companies = Company.objects.all() img2 gives me id of company which i need, and all informaton but in seprate rows, not as a list {% for company in companies %} <tr> <td>{{ company.name }} <a href="{% url 'api:form_view' company.id %}">(Add Employee)</a></td> <td>{{ company.id }}</td> <td>{{ company.employeename }}</td> </tr> {% endfor class Employee(models.Model): first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) comment = models.TextField() #companyname=models.OneToOneField(Insert, on_delete=models.CASCADE) def __str__(self): return f"{self.first_name} {self.last_name}" class Company(models.Model): name = models.CharField(max_length=100) #newuser= models.ForeignKey(Employee, on_delete=models.CASCADE) employeename = models.OneToOneField(Employee, on_delete=models.CASCADE,null=True) -
Can't import app in project URL in Django
I can't import app in project (Django rest framework) URL (urls.py) in a Django project. I have done this same scenario in one of my projects in past. from appname import views This is what I need. When I trying to provide the first letter of my app name in previous project (like from a) it is giving full app name (from appname) but in new project it won't getting. I know there have other options to overcome this. But I need to know the reason behind this. making the project directory as source directory is the only solution for this? If we doing like this if there any problem, while hosting the project in server? Please someone help. I need to import app view in my project URL. -
Drawing polylines on OSM near edges is tricky, How can I get rid of these horizontal lines?
enter image description here I am trying to draw a track that satellite follows when revolving around earth. I used Open Street Maps for it and Leafletjs to integrate it with my web app. Snippet of the JS. var trackList15 = [] for (let trackPoint of tracks ) { trackList15.push([trackPoint.latitude, trackPoint.longitude]) } When it is close to the edges of the map a horizontal line is drawn to connect the visually apart points on the map. I want to discontinue the line at the edge and draw new one from the other edge. I haven't been able to find a way to detect edges of the map to discontinue the polyline when it is near edges -
Include with tags dynamic value in django
I'm confused about how can I assign dynamic value to custom_variable using include with in Django based on the click button it is possible? I just want to show the modal based on the clicked button {% include "modal_main.html" with custom_variable="dynamic_variable" %} <button type="button" class="btn btn-label-primary button_orange">Orange</button> <button type="button" class="btn btn-label-primary button_mango">Mango</button> <script> $(document).ready(function(){ $('.button_orange').click(function (event) { //pass data to custom_variable which is value of orange }); $('.button_mango').click(function (event) { //pass data to custom_variable which is value of mango }); }); -
created_by and updated_by fields in Models.py
how to implement created_by and updated_by fields in my models.py and also when do i pass models.created_by and updated_by == request.user in my views.py? please can anyone help me to do from scratch -
Django basic form submits successfully, but it doesn't update the datebase
As a test run after reading through Django for Beginners, I am trying to make a server with custom D&D character sheets. Here is my the relevant fields in my model (keep in mind that I have other fields, I just didn't list them for simplicity): from django.db import models from django.urls import reverse from django.conf import settings from django.core.exceptions import ValidationError from django.utils.translation import gettext_lazy as gtl import json class charSheet(models.Model): # character's name char_name = models.CharField(max_length=45) # player's name which is the key that will # group together different character sheets # together author = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, ) Here is my forms.py: from django import forms from .models import charSheet class CharacterForm(forms.ModelForm): class Meta: model = charSheet # fields = [field.name for field in charSheet._meta.get_fields() if field.name != "author"] # fields = "__all__" fields = ["char_name", "author"] and the relevant part of my views.py class CharacterCreateView(LoginRequiredMixin, UserPassesTestMixin, CreateView): model = charSheet template_name = "character_new.html" fields = [ field.name for field in charSheet._meta.get_fields() if field.name != "author" ] def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) def test_func(self): obj = self.get_object() return obj.author == self.request.user Here is my urls.py rom django.urls import path from .views import ( CharacterListView, … -
How to call api(post method) into html template using Vue Js? Is this right way to pass data? [closed]
created(){ this.sku= '{{sku}}' axios.post('http://url/api/'+ this.sku +'/reports/report', {headers: { Authorization: 'Bearer '+token}}, {data:{from_date: '2023-05-01', to_date: '2023-05-30'}}) .then(response =>{ console.log(response.data.data) this.total_sale = response.data.total_sale, this.total_purchases = response.data.total_purchases, this.total_expenses = response.data.total_expenses, this.sales_total_profit = response.data.sales_total_profit }) } I am getting API(get method) data using the same way into html template on the script tag but post-method API data can't. Is there any wrong with my code? -
How to build bulk E-mail sender web application
I am trying to create bulk E-mail sender web application like SendGrid, but I am confused about how I can do this without using any APIs. I would like to create my own API, so please help me if anyone knows how to do it. Specifically, I am interested in creating a bulk E-mail sender web application in Python/Django. I am trying to create web application like SendGrid Without any APIs. -
Django project prectice
As a college student practicing Django and DRF, i have theoretical knowledge but lack industrial experience. While internships can be a great way to gain practical experience, is there any other ways to practice solving DRF problems. to participate python there are lots of online coding challenges or competitions focused on Websites such as HackerRank, LeetCode, and CodeSignal offer coding challenges in a variety of programming languages, is there any for Django & DRF ? i have watched tutorials and alots of stuff , i need raal probles facing in real problems -
How can I change numbers in a url parameter in Django Template?
I'm trying to make a pagination system. I want to change a number in a url parameter. The URL is like this; https://example.com?page=1 What I'm trying in a template is below, but it doesn't work. <a class="next_page" rel="next" href="{{request.build_absolute_uri|cut:'&page={{current_page}}'}}page={{current_page|add:1}}">Next</a> I'm passing current_page variable from view.py and remove the old page number from the url parameter and then giving the new number. The problem is I can't use current_page variable in the cut filter. How should I resolve the problem? -
django Baseserializer remove certain fields from validated_data
I need to validate a payload json based on, say, fields A, B. But I don't want these to show in serializer.validated_data I tried to override validated_data base class method. class MySerializer(serializers.Serializer): fieldA = ... fieldB = ... fieldC = ... def validate_fieldA(self, fieldA): # validate def validate_fieldB(self, fieldB): # validate def validated_data(self): data = super().validated_data() exclude_fields = self.context.get('exclude_fields', []) for field in exclude_fields: # providing a default prevents a KeyError # if the field does not exist data.pop(field, default=None) return data Now when I try to access serializer.validated_data dict, it returns a method instead of deserialized dictionary. <bound method MySerializer.validated_data of .... How do I accomplish this correctly? -
How can I configure my Django application to use separate databases for different superusers?
How can I create multiple databases in my Django project, where each superuser has access to their own separate database . so when I called or login with superuser only their data should be visible in the dashboard or database I have tried to create multiple database in setting.py and models.py but it is not working -
Django running with apache2 cannot find app.settings module
Django works when running with python manage.py. When I run with apache I get a 500 internal server error, the apache error log file states: AH01215: ModuleNotFoundError: /var/www/app/myproject/wsgi.py AH01215: : : /var/www/app/myproject/wsgi.py AH01215: No module named 'myproject': /var/www/app/myproject/wsgi.py AH01215: : /var/www/app/myproject/wsgi.py So I checked to my wsgi.py file to see if sys.path was looking in the correct location (removed the exit statement after the check): #!/usr/bin/env python3 import os import sys exit(sys.path) from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myproject.settings') application = get_wsgi_application() Note the shebang, I had to add that to fix an earlier error. The apache error log file now shows: AH01215: ['/var/www/app/myproject', '/usr/lib/python310.zip', '/usr/lib/python3.10', '/usr/lib/python3.10/lib-dynload', '/usr/local/lib/python3.10/dist-packages', '/usr/lib/python3/dist-packages']: /var/www/app/myproject/wsgi.py sys.path is not including /var/www/app so I look in the relevant sites-available file and also check there are no other conf files with the same ServerName: <VirtualHost *:80> ServerName example.com ServerAlias www.example.com ServerAdmin webmaster@localhost DocumentRoot /var/www/app Alias /static /var/www/app/static <Directory /var/www/app/static> Require all granted </Directory> WSGIDaemonProcess myproject python-path=/var/www/app:/var/www/app/myprojectenv/lib/python3.10/site-packages WSGIProcessGroup myproject WSGIScriptAlias / /var/www/app/myproject/wsgi.py <Directory /var/www/app> <Files wsgi.py> Require all granted </Files> </Directory> ErrorLog ${APACHE_LOG_DIR}/your-project-name-error.log CustomLog ${APACHE_LOG_DIR}/your-project-name-access.log combined </VirtualHost> I can see that the python-path variable is set to /var/www/app, but this does not appear in sys.path in wsgi.py. So I go … -
Python Django Error: TemplateSyntaxError: Could not parse the remainder
What is the solution for following problem? Error is on line 10! I do not know what is wrong with the code! Error during template rendering In template C:\Users\farib\Desktop\Python\classProject\signup\templates\services.html, error at line 10 Could not parse the remainder: '(airquality' from '(airquality' 1 {% extends "layout.html" %} 2 {% block content %} 3 <h1 style="color:rgb(51, 48, 51)">Services</h1> 4 <form id="contactForm" method="post" action="services" class="needs-validation"> 5 {% csrf_token %} 6 {{ servicesform }} 7 <input id="sendBtn" type="submit" class="btn btn-primary" value="Analyze"> 8 </form> 9 <h3>Address: {{ address }}, City: {{ city }}, Country: {{ country }}, Latitude: {{ latitude }}, Longitude: {{ longitude }}</h3> 10 {% if airquality < 50 %} 11 <h3 style="background-color: green;">Air Quality: {{ airquality }}</h3> 12 {% elif (airquality >= 51) and (airquality < 100) %} 13 <h3 style="background-color: yellow;">Air Quality: {{ airquality }}</h3> 14 {% elif (airquality >= 101) and (airquality < 150) %} 15 <h3 style="background-color: orange;">Air Quality: {{ airquality }}</h3> 16 {% elif (airquality >= 151) and (airquality < 200) %} 17 <h3 style="background-color: red;">Air Quality: {{ airquality }}</h3> 18 {% elif (airquality >= 201) and (airquality < 300) %} 19 <h3 style="background-color: purple;">Air Quality: {{ airquality }}</h3> 20 {% elif airquality >= 301 %} I tried … -
django problem when i start an application
When I start an application like (pages) then I link it with the project in settings => INSTALLED_APPS: INSTALLED_APPS = [ 'pages.app.PagesConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] Then i made a url for it in urls: `from django.contrib import admin from django.urls import path,include urlpatterns = [ path('admin/', admin.site.urls), path('pages',include('pages.urls')) ]` This Error appear after running the server : ModuleNotFoundError: No module named 'pages.app' i searched for the solution and i founed that the problem may be in the installed apps but i made it right -
Operational problem to connect Postgres db
When trying to migrate, I receive the below error message. This means that my project cannot connect to my local PostgreSQL. My project is on django. I work with Windows 11. I googled and nearly all similar errors where linked somehow to Docker and docker-compose. While the current project isn't dockerized. I previously run a similar docker project through docker desktop, with postgres database. While I don't know if that is relevant to my problem, I note in case it's relevant. I also removed all docker container, images, volumes that could conflict with the current file, just in case. I updated PostgreSQL and restart its settings. Any return would be highly appreciated. settings/base.py: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'my_db_user', 'USER': 'postgres', 'PASSWORD': 'my_db_password', 'HOST': 'localhost', 'PORT': '5432', } } command: python manage.py migrate: error message: File "C:\Users\anica\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\db\backends\base\base.py", line 263, in connect self.connection = self.get_new_connection(conn_params) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\anica\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\utils\asyncio.py", line 26, in inner return func(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\anica\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\db\backends\postgresql\base.py", line 215, in get_new_connection connection = Database.connect(**conn_params) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\anica\AppData\Local\Programs\Python\Python311\Lib\site-packages\psycopg2\__init__.py", line 122, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ django.db.utils.OperationalError -
python socket multi-threading with docker issue
I've encountered this issue for 2 days. Hope someone can get me out of this. The program I am write is quite simple, just use python struct to create an ICMP ping packet, then use socket to send out, measure the latency. I don't want to use the system level command because I am trying to make this independent beyond whichever OS is deploying the code. Here is part of the code: def _icmp_ping(host, packet_size, interval, timeout, packet_num): # Sends ICMP echo requests to the specified host and returns the average latency and success rate as a tuple if packet_size < 8: packet_size = 8 payload = b'\x00' * (packet_size-8) icmp_protocol = socket.getprotobyname("icmp") icmp_echo = 8 packet_id = random.randint(1, 0xffff) packet = struct.pack("!BBHHH", icmp_echo, 0, 0, packet_id, 1) + payload # Adds the ICMP checksum to the packet packet = struct.pack("!BBHHH", icmp_echo, 0, socket.htons(NetPack._calculate_checksum(packet)), packet_id, 1) + payload sent_count = 0 received_count = 0 total_latency = 0 # Sends 10 ICMP echo requests for _ in range(packet_num): # Creates a raw socket for sending ICMP packets with closing(socket.socket(socket.AF_INET, socket.SOCK_RAW, icmp_protocol)) as sock: # Sets the timeout for the socket sock.settimeout(timeout) # Sends the ICMP packet to the specified host sock.sendto(packet, … -
For loop catch Exception before called function do it's job
I got a code that connects to Binance api/url and sometime has ConnectionError. My code is like: def initial_connect(self): try: client = Spot(key=self.api_key, secret=self.secret_key, base_url='https://api4.binance.com') except: client = Spot(key=self.api_key, secret=self.secret_key, base_url='https://api2.binance.com') finally: return client And I use this function in another file in a for loop with try block, to log the errors: for trade in trades: try: initial_connect() except Exception as e: error_log(str(e)) So in this case when first connections fails, doesn't go to function (initial_connect) except block and try other url, then in for loop except block get the Exception and write the error log. The question is, How can I edit my code so after a connection failure checks another one, if second fails the for loop try block catch the exception? I just tried with try block in serveral orders and the result was the same. -
swagger with django, can't find module drf_spectacular
I have a django app and I try to implement swagger. But I am stuck on the drf_spectacular.views in the urls.py file. So I installed drf_spectacular. and I am using django version: 3.2.16. I edited the settings.py file: 'drf_spectacular' in the installed_apps and REST_FRAMEWORK={ 'DEFAULT_SCHEMA_CLASS':'drf_spectacular.openapi.AutoSchema', } And I try to import drf_spectacular.views in the urls.py file: from drf_spectacular.views import SpectacularAPIView But I get this error: Unable to import 'drf_spectacular.views'Pylint(E0401:import-error) Question: how to resolve this? Thank you -
Can Django channels receive 30fps video recording from a React Client ? or should I switch another library
I am building a room monitoring app, and I was thinking of sending data using WebSockets and Django channels, but I am not sure if it's a good approach or if Websockets can send/handle 30fps video/image data to the server. -
Best-fit Free Database Choice for small project / Django
I am building a small application that will envolve user authentication and user account info (picture and CV included). I am currently in the early stages, still thinking about the architecture of my system, but I was thinking about using Django in the backend, since it has many authentication features. But owing to the fact I will be storing user info, such as their picture and their CV (which should take up to 200kb per user), I was dubious if the integrated SQLite by Django would be enough. The application is expected to have at max a few hundreds of users. (Is SQLite enough for that?) I was looking for the best free permanent solution for my database, I would appreciate any recommendations given as well as feedback in case my choices of architecture have not been the best. -
Foreign keys in model
I am creating a form to catch registration information into Competitors database. From that database, I want to create group where competitors can be organized and compete again each other. Models.py class Group1(models.Model): flname = models.CharField(max_length=255) Weight = models.IntegerField(validators=[MinValueValidator(50), MaxValueValidator(300)], default= 0) rank = models.CharField(max_length=255) point = models.IntegerField class Competitors(models.Model): flname = models.CharField(max_length=255) Weight = models.IntegerField(validators=[MinValueValidator(50), MaxValueValidator(300)]) rank = models.CharField(max_length=255) Group = models.ForeignKey(Group1, blank=True, null=True, on_delete=models.CASCADE) Traceback: Exception Type: OperationalError at /admin/appbjjtournament/competitors/ Exception Value: no such column: appbjjtournament_competitors.Group_id I deleted, makemigration, and migrate, but the error still persists. -
How to implement composite primary keys in Django?
Currently, I am using Django version 3.2.3 I have created this model where columns c1,c2 and c3 form composite primary keys class myModel(models.Model): _DATABASE = "my_db" c1 = models.CharField(db_column='c1', primary_key=True, max_length=20) c2 = models.CharField(db_column='c2', max_length=20) c3 = models.CharField(db_column='c3', max_length=20) c4 = models.CharField(db_column='c4', max_length=50) c5 = models.CharField(db_column='c5', max_length=1024) class Meta: managed = False db_table = 'my_table' unique_together = (('c1', 'c2', 'c3'),) ` unique_together is not working Django is considering only c1 as primary key