Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django database object save() fails silently [closed]
I have a bug which is not reproducible and occurs rarely. Get object of the database: db_obj= My_Db_Model.objects.get(ID=id_from_param) # called always with same id_from_param Modify fields like: db_obj.value = 123 db_obj.save() No. 3 is surrounded by try, except (Exception), which means it applies for all exceptions and it should log the exception. Most of the times it works, but sometimes the value is not updated, without having any exception. Could there be some explanation how this could happen and under which circumstances it could fail silently like this? It is a postgresql database and I was also not able to figure out something from the database logs. Maybe there is a way to check if the database works correctly? -
How to display data frame in template page using django
I am trying to populate my data frame in Django, But I am getting a blank page. Here I am sharing my sample code <html> <head> <title>API Display</title> </head> <body> <h1>List of Data </h1> {% for i in d %} <strong>{{i}}</strong> {% endfor %} </body> </html> def index(request): url = "http://153.24.76.45:9000/abc/" response = requests.get(url) z = response.json() # df = z.reset_index().to_json(orient ='records') df = pd.DataFrame(z['Result']['LSData']) context = {'d': df} return render(request,'index.html',context) can anyone help me to solve this problem ? -
Why don't bootstrap codes run on my django website?
Hello I'm having trouble applying bootstrap to my website in django. I copied the bootstrap link in the html page and wrote the navbar codes in the body part, but when I hit runserver, the website page doesn't change at all! where is the problem from? I also installed the bootstrap plugin in Visual studio code, but it still doesn't change anything! Thank you for your guidance The** navbar** should have applied to my page, but it didn't I use visual studio code and django framework -
Trying to render two different views in one template according to their specific url routing
Im trying to render login and register view in a single template using variable assignment and if-else. I'm sorry if its a rookie mistake, Im pretty new to this.. github repo- https://github.com/varundhand/DevSearch my urls.py :- urlpatterns = [ path('login/',views.loginUser,name='login'), path('logout/',views.logoutUser,name='logout'), path('register/',views.registerUser,name='register'), path('',views.profiles,name='profiles'), path('profile/<str:pk>/',views.userProfile,name='user-profile'), ] my views.py :- def loginUser(request): page = "login" if request.user.is_authenticated: return redirect('profiles') if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') try: user = User.objects.get(username=username) except: messages.error(request,'Username doesnt exist') user = authenticate(request,username=username,password=password) if user is not None: login(request,user) return redirect ('profiles') else: messages.error(request,'Username/Password incorrect') context = {page:'page'} return render(request, 'users/login_register.html', context) def logoutUser(request): logout(request) messages.error(request,'User was logged out!') return redirect('login') def registerUser(request): page = "register" context= {page:'page'} return render(request,'users/login_register.html', context) my html template file :- {% extends 'main.html' %} {% block content %} {% if page == "register" %} <h1>Register User</h1> <p>Already have an account? <a href="{% url 'login' %}">Login</a> </p> {% else %} <form action="{% url 'login' %}" method="POST"> {% csrf_token %} <input type="text" name="username" placeholder="Username"> <input type="pass`your text`word" name="password" placeholder="Enter Password"> <input type="submit" value="Login"> <p>Dont have an account? <a href="{% url 'register' %}">Sign Up</a></p> </form> {% endif %} {% endblock content %} My Approach I gave variable assignment of page='login' and page='register' in … -
Error "Expecting value: line 1 column 1 (char 0)" in postman while generating token through a post Api
@api_view(["POST"]) @permission_classes([AllowAny]) def LoginView(request): data = {} details = request.body reqBody = json.loads(details) username = reqBody['username'] password = reqBody['password'] Inside 'details' I am getting a Form-Data instead of string due to which getting above error if any suggestion . How to convert 'form-data' in 'string' Or directly convert 'form-data' to 'string' I tried details = request.body reqBody = json.loads(details.decode('utf-8') But it gives the same error . -
npm dev run generates huge main.js file
I have a Django application and trying to rewrite my JS frontend to React. I found some tutorial how to organize the structure of React app: frontend/ static/frontend/main.js/main.js src/ index.js components/App.js package.json { "name": "frontend", "version": "1.0.0", "description": "", "main": "index.js", "presets": [ "@babel/preset-env", "@babel/preset-react" ], "scripts": { "dev": "webpack --mode development ./src/index.js --output-path ./static/frontend/main.js", "build": "webpack --mode production ./src/index.js --output-path ./static/frontend/main.js", "test": "echo \"Error: no test specified\" && exit 1" }, "keywords": [], "author": "", "license": "ISC", "devDependencies": { "@babel/core": "^7.20.12", "@babel/preset-env": "^7.20.2", "@babel/preset-react": "^7.18.6", "babel-loader": "^9.1.2", "react": "^18.2.0", "react-dom": "^18.2.0", "webpack": "^5.75.0", "webpack-cli": "^5.0.1" }, "dependencies": { "fs-promise": "^2.0.3" } } webpack.config.js module.exports = { devtool: false, module: { rules: [ { test: /\.js$/, exclude: /node_modules/, use: { loader: "babel-loader", options: { presets: ['@babel/env','@babel/preset-react'] }, } } ] } }; index.html <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Django REST with React</title> </head> <body> <h1>Anything</h1> <div id="app"> <!-- React will load here --> </div> </body> {% load static %} <script src="{% static "frontend/main.js/main.js" %}"></script> </html> sample code in App.js import React from 'react'; import ReactDOM from 'react-dom'; function App() { const [value, setValue] = React.useState(0); function increment() { setValue(value + 1); } return ( <div … -
how to run specific test files from tests folder in django?
I'm doing some api testing I have these files in it tests/test_one.py tests/test_two.py how can I test a single file using python manage.py test -
Getting " ValueError: No route found for path 'socket/order' ' " in Django Channels when trying to connect with Angular frontend
I am trying Django Channels for the first time. I am trying to connect it with an existing Angular frontend application. But for some reason the routing isn't working I cannot figure out why. I have written the codes exactly how the Django Channels documentation instructs to. The error message goes as such - Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). January 10, 2023 - 15:34:50 Django version 4.1.3, using settings 'BrokerBackEnd.settings' Starting ASGI/Daphne version 4.0.0 development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. WebSocket HANDSHAKING /socket/order [127.0.0.1:63732] HTTP GET /orders/ 200 [0.07, 127.0.0.1:63731] Exception inside application: No route found for path 'socket/order'. Traceback (most recent call last): File "C:\Users\Neha\Documents\broker-back-end-py\env\lib\site-packages\django\contrib\staticfiles\handlers.py", line 101, in __call__ return await self.application(scope, receive, send) File "C:\Users\Neha\Documents\broker-back-end-py\env\lib\site-packages\channels\routing.py", line 62, in __call__ return await application(scope, receive, send) File "C:\Users\Neha\Documents\broker-back-end-py\env\lib\site-packages\channels\routing.py", line 134, in __call__ raise ValueError("No route found for path %r." % path) ValueError: No route found for path 'socket/order'. WebSocket DISCONNECT /socket/order [127.0.0.1:63732] Would really appreciate if anyone could suggest anything. Thank you. settings.py INSTALLED_APPS = [ 'daphne', 'channels', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'corsheaders', 'rest_framework', 'Orders' ] ASGI_APPLICATION = 'BrokerBackEnd.asgi.application' asgi.py import os from django.core.asgi … -
Is Supervisor needed?
So I've started to use django with SQS to run tasks at a given time where the celery-broker and beat start at deployment. Now Since I'm using autoscaling if an instance fails and gets replaced will the worker and beat start again ? I've seen that a solution could be to have a supervisor . Can anyone shine some lights there ? Not sure what's the best approach . Many Thanks -
Django: Database column not updating from variable, taking it as hardcoded name
I have the following code for updating a database column. def update_itemamadeus(check_flight_differences): for item_id, flight_details in check_flight_differences.items(): for field, value in flight_details.items(): ItemAmadeus.objects \ .filter( Q(id=item_id) ) \ .update( field = value ) return It's taking 'field' not as the variable it should be which is 'code_airport_from_id'. item_id = 130 field = code_airport_from_id value = BCN The dreaded yellow screen error: Can this be achieved? -
I am using Django and I want encrypt my data such us URLs is there any way to do that
I am using Django can someone help me to encrypt my data I want do encrypt my data but I do not know how to do it I am using Django and flutter and I want to encrypt my data to not be readable by any one is there any way to do that I want to get answer please can someone help me -
Count django records and list them
I want to get the list and count of houses under a location How to do it in djano do you have any idea Tables are frontend_property and frontend_locations how to join and get the result in django -
Dynamically add input field with select option tag based on chosen model
<script> $(document).ready(function(){ $("#experienceNo").on("change",function(){ var numInputs = $(this).val(); $('#experienceSection').html(''); for(var i=0; i < numInputs; i++) { var j = i*1; var $section = $('<div class="form-group"><label for="" class="col-4 col-form-label">Company Name '+j+'</label><div class="col-6"><input type="text" name="companyname[]" class="form-control" required></div></div>'); $('#experienceSection').append($section); } }); }); </script> <div class="col-6"> <select name="experienceNo" id="experienceNo" class="custom-select mb-2 mr-sm-2 mb-sm-0"> <option value="">Select Value</option>`enter code here` <option value="0">0</option> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> <option value="4">4</option> <option value="5">5</option> </select> </div> </div> I want to make dynamically add input field with select option tag based on chosen model, but the option didnt appear, even after i was selected the value model How to make options dynamically appear based on chosen model option? -
How to tick those group by fetching groups based on user id in django
In the below image the user is in three groups so I want while updating the user the groups that user in should be checked. how can I achieve this ? I am unable to get how to achieve this in Django for now I fetching the all groups from database. {% for group in groups %} <tr> <td>{{group.name}}</td> <td><input type="checkbox" name="add_group[]" id="group-{{group.id}}" value="{{group.id}}"></td> </tr> {% endfor %} -
Unable to integrate Odoo with Django and getting error "erppeek.Error: Invalid username or password" . Please help me integrate odoo to django
I have followed the below article to integrate Odoo with Django: https://axistechnolabs.medium.com/guideline-for-odoo-integration-in-django-python-8c3bed069c8c My seetings.py configuration ODOO_HOST = { 'USER': 'vishnu', 'PASSWORD': 'password@123', 'HOST': 'http://localhost', 'PORT': 8069, 'DB': 'test1' } INSTALLED_APPS = [ 'djangodoo', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', How can I solve this, please help I have followed the below article to integrate Odoo with Django: https://axistechnolabs.medium.com/guideline-for-odoo-integration-in-django-python-8c3bed069c8c and run odoo server & django server but getting error: "erppeek.Error: Invalid username or password" -
Why do I get an API GET error as an anonymousUser even when using IsAuthenticatedOrReadOnly?
Im learning Django followed a book and tutorials. Anyways I started my own project, where users can create Posts for other to see. My problem comes when someone is not logged in and makes a GET request ie:PostListCreate below, the api crashes even tho I have permissions as IsAuthenticatedOrReadOnly. I get the error TypeError: Field 'id' expected a number but got <django.contrib.auth.models.AnonymousUser object at 0x104d2f760>. Also I have models.ForeignKey(User, on_delete=models.CASCADE) in the model.py for Post model. Saw this might have something to do with it but unsure. Have spent three hours researching it and can't find a solution. What do I need to change or edit to be able to have a successful GET request without authentication. api/views.py from rest_framework import generics, permissions from .serializers import PostSerializer from post.models import Post class PostListCreate(generics.ListCreateAPIView): serializer_class = PostSerializer permission_classes = [permissions.IsAuthenticatedOrReadOnly] def get_queryset(self): user = self.request.user return Post.objects.filter(user=user).order_by('-created') def perform_create(self,serializer): serializer.save(user=self.request.user) class PostRetrieveUpdateDestroy(generics.RetrieveUpdateDestroyAPIView): serializer_class = PostSerializer permission_classes = [permissions.IsAuthenticatedOrReadOnly] def get_queryset(self): user = self.request.user return Post.objects.filter(user=user) model.py from django.db import models from django.contrib.auth.models import User class Post(models.Model): title = models.CharField(max_length=100) description = models.TextField(blank=True) created = models.DateTimeField(auto_now_add=True) sold = models.BooleanField(default=False) user = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.title -
django.db.utils.InterfaceError: ('IM002', '[IM002] [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified (0)
DATABASES = { 'default': { # 'ENGINE': 'sql_server.pyodbc', 'ENGINE': 'mssql', 'NAME': 'DatabaseName', 'HOST': 'ServerName', 'USER': 'LoginId', 'PASSWORD': 'LoginPass' # 'OPTIONS': { # 'DRIVER': 'SQL Server Native Client 11.0' # # 'DRIVER': 'ODBC Driver 13 for SQL Server', # } #, 'Extra_Params':'Trusted_Connection=True'} } } I already have SQL Server 11.0 installed, also ODBC 13 Driver installed Also configured System DSN as well. Please suggest. -
Can't change Latitude and Longitude after creating in GeoDjango
I have a model of store models.py class Store(models.Model): title = models.CharField(max_length = 50) point = models.PointField(null = True, blank = True) deleted = models.BooleanField(default=False) I set a form to create a store where the latitude and longitude can be converted into a point forms.py class StoreForm(forms.ModelForm): latitude = forms.FloatField( min_value = -90, max_value = 90, required = True, ) longitude = forms.FloatField( min_value = -180, max_value = 180, required = True, ) class Meta(object): model = Store exclude = ['deleted'] widgets = {'point': forms.HiddenInput()} def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) coordinates = self.initial.get('point', None) if isinstance(coordinates, Point): self.initial['longitude'], self.initial['latitude'] = coordinates.tuple def clean(self): data = super().clean() latitude = data.get('latitude') longitude = data.get('longitude') point = data.get('point') if latitude and longitude and not point: data['point'] = Point(longitude, latitude) return data I used this form to add Store in my HTML frontend and when I check my backend data is in there. this form helps to show latitude and longitude fields and when I submit it automatically converts into a point When I want to update the store I used the exact same form to update, and I can see the previously added latitude and longitude value in charfield(as usual I used … -
How to make calculation inside annotate?
This one when I run generates error qs = User.objects.annotate(days=(datetime.now() - F("created_at")).days) AttributeError: 'CombinedExpression' object has no attribute 'days' How can I make that calculation as an annotation When I run this code, it wroks fine qs = User.objects.annotate(days=(datetime.now() - F("created_at"))) -
Django models for astra datastax db
I have developed a site on Django. Initially, I used Django's default Database which is Sqlite3. Now I want to use Astra Datastax DB which is Cassandra. I am not able to convert Django.dB - models into Cassandra.cqlengine - columns function. I have suffered on the Internet and didn't find appropriate documents which could help me. -
How to deploy my site ( React, Django, Selery, Selenium ) which is containerized ( Docker, Docker-Compose )?
Here I title it has 'how to deploy' since I have many doubts in this. My Work Overview: I am using React for my Frontend and Django for my Backend. In this, I used Selenium for WebScrapping which will be carried out on Celery. I deployed it in Okteto Problem Overview: I tried to fully containerise this using Docker and Docker-Compose. But, I am facing multiple problems with this. Ideas: I want my backend only accessed by my front end. and also selenium, celery should be accessed only from my backend. My front end should only access my backend, not any other APIs. The frontend request should be handled within the server( like the local host ) so that the request time will be reduced. Codes: Dockerfile in Backend: FROM python:3.10.9-slim-bullseye RUN apt-get update \ && apt-get install -y --no-install-recommends --no-install-suggests \ build-essential default-libmysqlclient-dev \ && pip3 install --no-cache-dir --upgrade pip WORKDIR /Backend COPY ./requirements.txt /Backend/ RUN pip3 install --no-cache-dir -r /Backend/requirements.txt COPY . /Backend/ EXPOSE 8000 RUN python3 manage.py makemigrations && python3 manage.py migrate CMD ["python3", "manage.py", "runserver", "0.0.0.0:8000"] Dockerfile in Frontend: FROM node:19-bullseye-slim RUN apt-get update WORKDIR /Frontend COPY package-lock.json package.json /Frontend/ RUN cd /Frontend/ && npm i … -
Django aggregate calculating incorrectly because of many-to-many join in queryset
We have a model with a many-to-many relationship with another model, and doing a Sum aggregation on it seems to multiply the result by the number of many-to-many relationships. Example models below: class Attendee(models.Model): name = models.TextField() category = models.TextField() class Event(models.Model): start_date = models.DateTimeField() end_date = models.DateTimeField() attendees = models.ManyToManyField(Attendee, related_name="event") class CalendarEvent(models.Model): calendar = models.TextField() event = models.ForeignKey(Event, related_name="calendar_events") We filter out some records based on Attendee, and then aggregate the duration of the events. queryset = queryset.filter(event__attendee__category="Accountant") queryset = queryset.annotate(duration=models.ExpressionWrapper( models.F('event__end_date') - models.F('event__start_date'), output_field=models.fields.DurationField() )) Whenever we run the aggregation at the end, all duration values would be multiplied by the number of Attendees associated with the Event/CalendarEvent. For example, if the event is 15 minutes long and has 4 attendees, we would expect the duration to be 900 seconds, but instead it's 3600 seconds. We noticed in the raw PSQL query that there is a LEFT OUTER JOIN against Attendees, so we tried removing the Attendee filter and it gave us the proper data. Is there any way to aggregate across a relationship like this without the joined results getting mixed in? -
Djoser not sending verification email with Google Workspace
I'm making a Django Webapp following the tutorial here. I have gotten everything to work up to a certain point. When I send the POST request to my djoser endpoint with my user information, I get back the same response he did in the video with status 201 and the name email and id fields presented back. However, I do not get a confirmation email like he does. The salient difference is that I am not using a vanilla gmail account like the demonstrator is. I have a custom domain hosted through Google Domains for which I also have a Google Workspace account. I can access this account's gmail inbox through the gmail website, and I can send and receive emails fine. However, confirmation emails will not send. I additionally followed the steps in this guide and they still would not send. Worth noting is that when I look at the google account's log in history, my app password has no record of being used. Any insight would be helpful. Here is the section of my settings.py that contains the relevant settings: EMAIL_BACKEND = 'django.core.mail.backends.smtp.Emailbackend' EMAIL_HOST = 'smtp-relay.gmail.com' EMAIL_PORT = 587 EMAIL_HOST_USER = 'admin@DOMAINNAME.net' EMAIL_HOST_PASSWORD = '**** **** **** ****' … -
regex_search: could not find match for (?:v=|\/)([0-9A-Za-z_-]{11}). when i add in youtube link (start=seconds) in django
I am currently working on a youtube video-embedded project in Django. I also use javascript but when I add some parameters in a youtube link using javascript for example https://www.youtube.com/embed/T6xslkut6JA?start=4 it's getting an error regex_search: could not find a match for (?:v=|/)([0-9A-Za-z_-]{11}). I spend a lot of time but I can't find any solution here is my javascript code: <script> let H; url = document.getElementById("url").innerHTML;//decleare url that get youtube link vedio = document.getElementById("vedio");// id that declear in <embed > tag function myFunction(value) {//value is in millisecond this function convert millisecond in second console.log("clicked"); console.log(value); var seconds = ((value % 60000) / 1000).toFixed(0); H = url+"?start="+seconds; console.log(url); vedio = document.getElementById("vedio").src = "H"; console.log(H); } </script> this is an error that i get -
direnv cannot find .envrc file even it does exist
I set up a virtual environment for a Django-React project. I have created the .bashrc in the user home directory, and .envrc file in the root folder of the project repo. But when I tried 'direnv allow' it always return '.envrc does not exit' with a weird referenced folder path. Can someone please help? direnv allow error direnv status I'm doing it on Windows 11. I tried to re-install everything and change the position of the folder from E to C driver. I also tried to rename the folder to anything else to see if any of it results in the weird folder path. But the error message remains.