Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Replacechild on a paragraph javascript
I am trying to edit a post and dynamicaly update the Dom with my editPost function (The posts are created with another Javascript function). function editPost(post_id){ // get the post text const post_element = document.getElementById(post_id); const post_text_element = post_element.querySelector('p.card-text'); const post_text = post_text_element.textContent.trim(); console.log(post_text_element) // create the textarea and populate it with the content of the post const textarea = document.createElement('textarea'); textarea.setAttribute('rows', 3); textarea.setAttribute('cols', 50); textarea.setAttribute('id', `edit-post-${post_id}`); textarea.value = post_text; // create the save button and add Event Listener const save_button = document.createElement('button'); save_button.textContent = 'Save'; save_button.addEventListener('click', () => { const new_post_text = textarea.value; fetch('/update_post/' + post_id, { method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ new_text: new_post_text }) }) .then(response => response.json()) .then(data => { const updated_post_text = data.new_text; const updated_post_element = document.createElement('p'); updated_post_element.className = "card-text"; updated_post_element.textContent = updated_post_text; post_element.replaceChild(updated_post_element, textarea); post_element.removeChild(save_button); }); }); post_element.replaceChild(textarea, post_text_element); post_element.appendChild(save_button); } but when clicking the Edit button I get an error in the console pointing to the post_element.replaceChild at the bottom saying: Uncaught DOMException: Failed to execute 'replaceChild' on 'Node': The node to be replaced is not a child of this node. at editPost (http://127.0.0.1:8000/static/network/index.js:214:18) at HTMLButtonElement.onclick (http://127.0.0.1:8000/:75:9) editPost @ index.js:214 onclick @ (index):75 dont really get it... Post_text_element is a … -
Windows 403 Forbidden Apache
Forbidden You don't have permission to access this resource. Apache/2.4.54 (Win64) OpenSSL/1.1.1p PHP/8.1.12 mod_wsgi/4.9.4 Python/3.11 Server at localhost Port 80 Iam trying to run my django project on my windows machine.. in apache this the configuration i have added in httpd.conf file . i have installed mod_wsgi. and everything is correct . but iam getting the error error 403 forbidden LoadFile "C:/Program Files/Python311/python311.dll" LoadModule wsgi_module "C:/Program Files/Python311/Lib/site-packages/mod_wsgi/server/mod_wsgi.cp311-win_amd64.pyd" WSGIPythonHome "C:/Program Files/Python311" WSGIScriptAlias / "D:\TeNWyn\@tenwyn.media.dev\TENWYN\TENWYN\wsgi.py" WSGIPythonPath "D:\TeNWyn\@tenwyn.media.dev\TENWYN" <Directory "D:\TeNWyn\@tenwyn.media.dev\TENWYN\TENWYN"> <Files wsgi.py> Require all granted </Files> </Directory> Alias /static "D:\TeNWyn\@tenwyn.media.dev\TENWYN\TENWYNMEDIA\static" <Directory "D:\TeNWyn\@tenwyn.media.dev\TENWYN\TENWYNMEDIA\static"> Require all granted </Directory> -
Debugging stops automatically in my django app in vscode
Im learning django currently and when I started to debug the application using debugging and run section in vs code, it starts and is going off within 2 seconds. I have done all the things followed by the tutor. He's on mac, he created a launch.json and set Django debugger for web apps. I did the same. I have installed the python intellisense and Don jayamanne python package extensions too. Then I started the run in debugger, debugger started and gone in 2 seconds. And Im working in a virtual env, will there be anything I need to configure in .vscode/settings.json path. I didn't get anything in settings.json file after setting virtual env python path in the pallette. What should I do to run debugging? Clear explanation about why debugging isn't running and why I didn't get a pythonPath in settings.json file. What to do to run debugging? -
How to update all the objects in a set one by one?
I have a simple Django project with some minor HTMX here and there, where I can perform a search and it returns results on the page without refreshing. There is a delete button on each result, which when pressed, deletes that element from the database and the view is immediately updated with the remaining results with no refresh. I have added a universal delete button up top, which when clicked, loops through the database queryset and deletes all the elements and returns the view. As a result, the view has all the results one moment and the next it's suddenly empty. I want to change the implementation such that when this delete all button is pressed, it deletes every element one by one while updating the view after each delete. How can I go about this? -
'No module named 'ms_identity_web' - Try to implement Azure Active Directory for Microsoft Login in Django App
Relevant Part in Microsoft Tutorial https://learn.microsoft.com/en-us/training/modules/msid-django-web-app-sign-in/3-exercise-register-django-web-app I installed tha package using a bash file and running bash file in my workflow file executed in GitHub: workflow.yml - name: Create and start virtual environment run: | python -m venv venv source venv/bin/activate - name: install MSIdentity run : | chmod +x MSIdent.sh ./MSIdent.sh - name: Install dependencies run: pip install -r requirements.txt During Building I get the following notification: run chmod +x MSIdent.sh chmod +x MSIdent.sh ./MSIdent.sh shell: /usr/bin/bash -e {0} env: pythonLocation: /opt/hostedtoolcache/Python/3.9.16/x64 Collecting git+https://github.com/azure-samples/ms-identity-python-utilities@main Cloning https://github.com/azure-samples/ms-identity-python-utilities (to revision main) to /tmp/pip-req-build-d_rgygaw Running command git clone --filter=blob:none --quiet https://github.com/azure-samples/ms-identity-python-utilities /tmp/pip-req-build-d_rgygaw Resolved https://github.com/azure-samples/ms-identity-python-utilities to commit 9b32cef36c6c0b73c1b3237fdd66128d89f90a62 Preparing metadata (setup.py): started Preparing metadata (setup.py): finished with status 'done' Collecting msal<2,>=1.6.0 Downloading msal-1.21.0-py2.py3-none-any.whl (89 kB) ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 89.9/89.9 kB 2.1 MB/s eta 0:00:00 Collecting cryptography<41,>=0.6 Downloading cryptography-40.0.2-cp36-abi3-manylinux_2_28_x86_64.whl (3.7 MB) ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 3.7/3.7 MB 44.4 MB/s eta 0:00:00 Collecting requests<3,>=2.0.0 Downloading requests-2.28.2-py3-none-any.whl (62 kB) ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 62.8/62.8 kB 16.2 MB/s eta 0:00:00 Collecting PyJWT[crypto]<3,>=1.0.0 Downloading PyJWT-2.6.0-py3-none-any.whl (20 kB) Collecting cffi>=1.12 Downloading cffi-1.15.1-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (441 kB) ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 441.2/441.2 kB 69.6 MB/s eta 0:00:00 Collecting urllib3<1.27,>=1.21.1 Downloading urllib3-1.26.15-py2.py3-none-any.whl (140 kB) ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 140.9/140.9 kB 37.0 MB/s eta 0:00:00 Collecting idna<4,>=2.5 Downloading idna-3.4-py3-none-any.whl (61 kB) ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 61.5/61.5 kB 16.8 MB/s eta 0:00:00 … -
OpenID being outdated and using python 2 code
I have a Django project and discord OAuth2 requires openID for some reason and it automatically got installed among some packages, now when I try to run the server I always get type errors and such from the package file because OpenID uses Python 2, I tried to uninstall but it says the package isn't installed, I tried to upgrade but it said I have the latest version, also when I tried to delete the openID folder in packages of my virtual environment the auth thing doesn't work and gives an error... -
I can’t normally make a regu via django-allauth, how to fix the error?
In general, I've been messing around with VK all day. I created an application in it, got all the keys, inserted them. From my site you can even go to authorization, but it asks if I allow access to the application, I say yes, and then this thing: enter image description here I can't find any information on the internet about this. There are no errors in the logs. Here are my connection settings Aplications INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.steam', 'allauth.socialaccount.providers.google', 'allauth.socialaccount.providers.telegram', 'allauth.socialaccount.providers.vk', django-allauth settings SOCIALACCOUNT_ADAPTER = "users.adapter.CustomAccountAdapter" ACCOUNT_DEFAULT_HTTP_PROTOCOL = "http" LOGIN_REDIRECT_URL = "/" LOGOUT_REDIRECT_URL = "/" ACCOUNT_USER_MODEL_USERNAME_FIELD = None ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_USERNAME_REQUIRED = False ACCOUNT_AUTHENTICATION_METHOD = "email" SOCIALACCOUNT_LOGIN_ON_GET = True ACCOUNT_CONFIRM_EMAIL_ON_GET = True ACCOUNT_LOGIN_ATTEMPTS_LIMIT = 10 ACCOUNT_LOGIN_ON_EMAIL_CONFIRMATION = True ACCOUNT_USERNAME_MIN_LENGTH = 3 SOCIALACCOUNT_EMAIL_VERIFICATION = False SOCIALACCOUNT_PROVIDERS = { 'google': { 'SCOPE': [ 'profile', 'email', ], 'AUTH_PARAMS': { 'access_type': 'online', }, 'OAUTH_PKCE_ENABLED': True, }, 'steam': { "APP": { "client_id": '', "secret": 'my_sret', "SCOPE": ["email"], } }, 'telegram': { 'TOKEN': 'my_token' }, 'vk': { 'APP': { 'client_id': 'my_client_id', 'secret': 'my_secret', 'key': 'my_key' }, "SCOPE": ["email"], "FIELDS": ['id', 'email', 'first_name', 'last_name'] } } AUTH_BACKENDS AUTHENTICATION_BACKENDS = ( "django.contrib.auth.backends.ModelBackend", "allauth.account.auth_backends.AuthenticationBackend", ) My custom … -
Django Template render problems
I'm a novice in learning django and I've come across rendering dynamic and static pages in django using jinja. I've made a SQLite table and I'm trying to make it render it's values. my views.py file looks like this: from django.shortcuts import render from django.http import HttpResponse from app1.models import Merch # Create your views here. def index(request): return HttpResponse("Index page!") def hello(request): return HttpResponse("Hello World!") def store(request): context = {"stuff": Merch} return render(request, 'app1/store.html', context) and inside my app1/templates/app1, I have an HTML file containing the following: <!DOCTYPE html> <html> <body> <h1>TEMPLATE</h1> <p>{{ stuff }}</p> </body> </html> the HTML part renders fine (big TEMPLATE text visible) but the django template for "stuff" is not. any idea how to get this working? -
How to display the result of the http response related to web scraping in the html page as a table? Django
I wrote a web scraping in Django and I want to display the fetched data in a table in a web page. Thank you in advance for your help. My code example is as follows: views.py : def index(request): return render(request,"index.html") def page4(request): searchWord = request.POST.get('search','') url=searchWord page=requests.get(url) htm=page.text soup=BeautifulSoup(htm,'html.parser') val=soup.find_all('div',attrs={'class':'kt-post-card__body'}) return HttpResponse(val) templates/index.html <!DOCTYPE html> <html> <head> <title> Home page ..! </title> </head> <body> <h1>come on..! </h1> <div> <form action="{% url 'page4' %}" method="post"> {% csrf_token %} <input id="search" name="search" type="text" class="query-search" placeholder="Search..."> <input class="btn btn-primary" type="submit" value="submit"> </form> </div> </body> </html> I want the data to be show as a table in an HTML page. Thanks a lot -
To add a button that autofills a random password on the password field which I created using py-script
I created a form in html which returns to a function in views.py in django framework. I wanted to add a button which autofills the password field with a random password. I used pyscript for creating a random password. But the button seems to be returning to the views.py instead of autofilling. <body bgcolor="white"> <py-script> import random password = '' def mypass(): length = random.randint(8,16) list1=[] for i in range(0,length): list1.append(chr(random.randint(32,126))) password = ''.join(list1) pyscript.write('python', password) </py-script> <script> function myfun(){ var a = document.getElementById("password1").value; var b = document.getElementById("password2").value; if(a!=b){ document.getElementById("messages").innerHTML="Passwords do not match"; return false; } } </script> <script> function myfunction(){ var password = PyScript.interpreter.globals.get('password'); document.getElementById("password1").value = password; } </script> <form onsubmit="return myfun();" action="register" method="post" > {% csrf_token %} <p> <label for="user_name">User Name</label> <input type="text" name="user_name" id="user_name" placeholder="Antman56." autocomplete="on" > </p> <p> <label for="f_name">First Name</label> <input type="text" name="f_name" id="f_name" placeholder="Dave" autocomplete="on" > </p> <p> <label for="l_name">Last Name</label> <input type="text" name="l_name" id="l_name" placeholder="Lee" autocomplete="on" value="keyan" > </p> <p> <label for="email">Email ID</label> <input type="email" name="email" id="email" placeholder="davelee@gmail.com" autocomplete="on" > </p> <p> <label for="password1">Password</label> <input type="password" name="password1" id="password1" placeholder="123$aBc" > </p> <p> <label for="password2">Confirm Password</label> <input type="password" name="password2" id="password2" placeholder="123$aBc" ><span id="messages" style="color:red"></span> </p> <div id="python"></div> <button onclick="mypass()">create random password</button> <button onclick="myfunction()">fill the … -
Want to make it obvious that I can reverse reference by related_name in Django
My Environment IDE: VSCode Extensions of VSCode Python Pylance Ruff Python Type Hint isort djLint Django Black Formatter What's my problem I am working on a quiz submission site with Django. I created a models.py file for a quiz and a user as follows: class User(AbstractUser): pass class Quiz(models.model): title = models.CharField(max_length=50) content = models.TextField() user = models.ForeignKey( User, on_delete=models.CASCADE, related_name="posted_quizzes" ) correct_answer = models.CharField(max_length=50) The above code adds the property posted_quizzes to the user class due to Django's related_name reverse querying functionality. This is a very useful function, but it is not obvious just by looking at the User class, even though it is a property of the User class. I often define new methods, forgetting that they are accessible via related_name. Is there any way that properties added via related_name can be seen directly from the User class? What I tried I tried adding directly as an unimplemented property as follows: import abc class User(AbstractUser): @abc.abstractproperty def posted_quizzes(self): """ defined by related_name of Quiz model posts the user posted """ pass class Quiz(models.model): title = models.CharField(max_length=50) content = models.TextField() user = models.ForeignKey( User, on_delete=models.CASCADE, related_name="posted_quizzes" ) correct_answer = models.CharField(max_length=50) This method is good in that it does not … -
DRF - Got KeyError when attempting to get a value for field `username` on serializer `SignupSerializer`
I am building an API using Django 4.2 and Django Rest Framework 3.14.0 and I am getting an error when I send a POST request to my signup endpoint. { "email": "johndoe@email.com", "username": "johnd", "first_name": "john", "last_name": "doe", "password": "2334.secret@", "password_confirm": "2334.secret@" } The error I receive is: File "C:\Users\alan\Documents\builds\pixaflow\.venv\Lib\site-packages\rest_framework\fields.py", line 479, in get_attribute raise type(exc)(msg) KeyError: "Got KeyError when attempting to get a value for field `username` on serializer `SignupSerializer`.\nThe serializer field might be named incorrectly and not match any attribute or key on the `dict` instance.\nOriginal exception text was: 'username'." However, the user is still being created in the database. Here is my code: models.py # imports here class AuthenticationUser(AbstractBaseUser, PermissionsMixin): email = models.CharField(max_length=200, unique=True) username = models.CharField(max_length=50, unique=True) # other fields here USERNAME_FIELD = "email" REQUIRED_FIELDS = [ "username", ] objects = UserManager() class Meta: # model metadata here def __str__(self): return self.username serializers.py # imports here class SignupSerializer(serializers.ModelSerializer): email = serializers.EmailField(required=True, validators=[UniqueValidator(queryset=User.objects.all())]) username = serializers.CharField(required=True, validators=[UniqueValidator(queryset=User.objects.all())]) password = serializers.CharField(required=True, write_only=True, validators=[validate_password]) password_confirm = serializers.CharField(required=True, write_only=True) class Meta: model = User fields = ( "id", "email", "username", "first_name", "last_name", "password", "password_confirm", ) read_only_fields = ("id",) def validate(self, attrs): if attrs['password'] != attrs['password_confirm']: raise serializers.ValidationError({'password': 'The passwords you … -
AssertionError: @api_view expected a list of strings, received str when passing slug
I get this error when I try to pass slug in the url can anyone please assist or if there's any other way to implement this. Below are the screenshots of urls.py | views.py | and models.py I am using Django Rest Framework Urs.py Screenshot Views.py Screenshot Models.py Screenshot Error Which I am Getting!! Please help! Thanks in Advance. incase the screenshot doesn't work below is the code of views def blog(request): blog = Blog.objects.all() serializer = BlogSerializer(blog, many=True ) return Response(serializer.data) @api_view('GET') def blogPost(request, slug): blogpost = Blog.objects.get(slug=slug) serializer = BlogSerializer(blogpost, many=False) return Response(serializer.data) Below is the code of urls.py from django.urls import path from . import views urlpatterns = [ path('blog', views.blog, name='blog'), path('blog/<str:slug>/', views.blogPost, name='blogpost') ] Below is the code of models.py class Blog(models.Model): sno = models.AutoField(primary_key=True) title = models.CharField(max_length=255) slug = models.SlugField(unique=True, allow_unicode=True, blank=True) author = models.CharField(max_length=255) read_time = models.IntegerField() publish_time = models.DateTimeField(default=timezone.now) hero_image = models.ImageField(blank=True,) content = models.TextField() tags = models.CharField(max_length=100) status = models.BooleanField(default=True) category = models.CharField(max_length=100) def save(self,*args,**kwargs): self.slug=slugify(self.title) super(Blog,self).save(*args,**kwargs) def __str__(self): return self.title -
Most Useful Language for Back-End to get a job with?
**Hello everyone my Question is : 👇 At this moment that i'm talking to you i'm newbie in both Python and Django and my goal is to become a Back-End Dev , and i wanna know which languages I must learn next ? Which one is more Useful to get job with ? P.S 👉 sorry if my question have an issue ! ** ⚪ I am newbie in python and Django and total newbie in Java Script -
Architecture and implementation of user achievements in django
I have a Django Rest framework application where a user performs set of tasks, my question is how to add achievement feature in a Django application based on the task set performed by the user. below are few examples of achievements: User performed 5 tasks in a row User finished 3 tasks in a day User performed is top 1% task performer for the week. These are just some few examples, my question is how to structure the achivements in term of Models, views, and how these achievemnts are calculated ? -
raise ValueError("Cannot use None as a query value") ValueError: Cannot use None as a query value
views.py def search_available_rooms(request): if request.method == 'GET': check_in_date = request.GET.get('check_in_date') check_out_date = request.GET.get('check_out_date') if check_in_date and check_out_date: overlapping_bookings = Booking.objects.filter(start_date__lte=check_out_date, end_date__gte=check_in_date) booked_rooms = [booking.room for booking in overlapping_bookings] available_rooms = Room.objects.exclude(id__in=[room.id for room in booked_rooms]) context = { 'available_rooms': available_rooms, 'check_in_date': check_in_date, 'check_out_date': check_out_date } return render(request, 'cat_hotel/cat_hotels.html', context=context) else: # Handle the case where one or both dates are missing return render(request, 'cat_hotel/cat_hotels.html', context={}) urls.py path('cat_hotels/', views.search_available_rooms, name='search_available_rooms'), raise ValueError("Cannot use None as a query value") ValueError: Cannot use None as a query value How do I solve this? -
Django React App, when inspecting the webpage it shows different code than in VSCode. It calls a get request, when my code references a post
It is a library management system with books and eventually users. The books hold simple information like title, author, genre, number of pages, and the ISBN number. Code from VSCode import React, { Component } from "react"; import Button from "@material-ui/core/Button"; import Grid from "@material-ui/core/Grid"; import Typography from "@material-ui/core/Typography"; import TextField from "@material-ui/core/TextField"; import FormHelperText from "@material-ui/core/FormHelperText"; import FormControl from "@material-ui/core/FormControl"; import { Link } from "react-router-dom"; export default class Book extends Component { constructor(props) { super(props); this.state = { title: null, author: null, genre: null, pages: null, }; this.isbn = this.props.match.params.isbn; this.getBookDetails(); } getBookDetails() { fetch("/api/get-book" + "?isbn=" + this.isbn) .then((response) => { if (!response.ok) { this.props.history.push("/"); } return response.json(); }).then((data) => { this.setState({ title: data.title, author: data.author, genre: data.genre, pages: data.pages, }); }); } render() { return ( <Grid container spacing={1}> <Grid item xs={12} align="center"> <Typography component="h2" variant="h2"> {this.state.title} </Typography> </Grid> <Grid item xs={12} align="center"> <Typography component="h5" variant="h5"> {this.state.author} </Typography> <Typography component="h5" variant="h5"> {this.state.genre} </Typography> <Typography component="h5" variant="h5"> Pages: {this.state.pages} </Typography> <Typography component="h5" variant="h5"> ISBN: {this.isbn} </Typography> </Grid> <Grid item xs={12} align="center"> <Button color="secondary" variant="contained" to="/" component={Link} > Back </Button> </Grid> </Grid> ); } } Code in browser inspect class Book extends react__WEBPACK_IMPORTED_MODULE_0__.Component { constructor(props) { super(props); this.state … -
Setting similarity threshold for trigram_similar Django PostgreSQL lookups?
We're using Django's trigram similarity __trigram_similar lookup and it works nicely, except we want to adjust the similarity threshold and don't know how. Queries are currently filtered like so: class MarkerViewSet(viewsets.ReadOnlyModelViewSet): queryset = tablename.objects.all() def filter_queryset(self, queryset): queryset = super().filter_queryset(queryset) queryset = queryset.filter(colname__trigram_similar= search_value) We thought we could add something like similarity__gt=0.1 to the args for filter() like this answer does, but it throws the error "django.core.exceptions.FieldError: Cannot resolve keyword 'similarity_gt' into field". They are using the .filter() function in a different way we don't understand which might be the problem. What's the argument and how can we supply it? Seems we might be able to adjust it manually in PostgreSQL with set_limit (previously SET pg_trgm.similarity_threshold), but we'd prefer to set this in Django. -
Django app failing on Vercel even when following tutorial video
I am trying to get a very basic Django app running on Vercel. I am following this tutorial and am following it almost exactly. https://www.youtube.com/watch?v=ZjVzHcXCeMU&t=930s But I just get that the serverless function crashed and a 500 error. You can see it here: https://django-vercel-exmaple.vercel.app/ When I check the logs in Vercel, it says: Unknown application error occurred Runtime.Unknown I tried changing the install command to pip install -r requirements.txt (which the tutorial video didn't have to do it seems). -
Error Invalid block tag on line 4: 'else'. Did you forget to register or load this tag? django
I'm doing a basic webpage with Django for a tutorial and when adding the following code to my base.html file i get the 'Invalid block tag on line 4: 'else'. Did you forget to register or load this tag?'. What might be the reason? <p> <a href="{% url 'learning_logs:index' %}">Learning Log</a>- <a href="{% url 'learning_logs:topics' %}">Topics</a>- {% if user.is_authenticated %} Hello, {{user.username}} {% else %} <a href="{% url 'accounts:login' %}">Log in</a> {% endif %} </p> {% block content %}{% endblock content %} Invalid block tag on line 4: 'else'. Did you forget to register or load this tag? -
Django could not perform queries on Postgres when request sent from fastapi
I use Django as ORM and fastapi as endpoint layer. Here is my Docker-compose file: version: "3" services: db: image: postgres volumes: - ./data/db:/var/lib/postgresql/data environment: - POSTGRES_DB=postgres - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres web: build: . env_file: - .env.dev command: bash -c "python manage.py makemigrations && python manage.py migrate && python manage.py runserver 0.0.0.0:8000" volumes: - .:/code ports: - "8000:8000" depends_on: - db api: build: . volumes: - .:/code environment: - POSTGRES_DB=postgres - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres command: bash -c "uvicorn contlika.asgi:celestial --host 0.0.0.0 --port 8001" ports: - "8001:8001" depends_on: - db the connections between web (Django Backend) and db (Postgres) is ok. So when I do queries within web container after the below command: python manage.py shell the object is created successfully and record is set in db tables. But when I send request from fastapi - through swagger interface - I get this error: django.db.utils.OperationalError: could not connect to server: No such file or directory Is the server running locally and accepting connections on Unix domain socket "/var/run/postgresql/.s.PGSQL.5432"? I have included the user and pass correctly in setting.py. Again the objects are being created successfully through Django command line utility. It's worth nothing to say, everything was working fine when I … -
Appending quantity of shopping cart with Jquery and DRF
I am trying to get my API to work on the front end of my django app, I have got to the point at which it successfully creates a new cart and adds the initial item to it, but once the button is clicked again it creates a brand new cart. I am getting zero errors so I think this is just down to lack of knowledge, any guidance and advice would be great. <script> const updateBtns = document.querySelectorAll('.update-cart'); const user = '{{request.user}}'; for(let i = 0; i < updateBtns.length; i++) { updateBtns[i].addEventListener('click', function(){ event.preventDefault(); // prevent page from refreshing const productId = this.dataset.product; const action = this.dataset.action; console.log('productId:', productId, 'action:', action); console.log('USER:', user); createCart(productId, action); addCartItem(productId, action); }); } function addCartItem(productId, action){ if(action === 'add'){ if(cart[productId] === undefined){ cart[productId] = {'quantity':1}; }else{ cart[productId]['quantity'] += 1; } } if(action === 'remove'){ cart[productId]['quantity'] -= 1; if(cart[productId]['quantity'] <= 0){ console.log('Remove Item'); delete cart[productId]; } } console.log('Cart:', cart); document.cookie = `cart=${JSON.stringify(cart)};domain=;path=/`; location.reload(); } function createCart(productId, action){ var csrftoken = getCookie('csrftoken'); console.log('User is logged in, sending data...'); const url = `http://127.0.0.1:8000/api/carts/`; fetch(url, { method: 'POST', headers:{ 'Content-Type':'application/json', 'X-CSRFToken':csrftoken, }, body:JSON.stringify({'productId':productId, 'action':action}), mode: 'same-origin', }) .then((response) =>{ return response.json(); }) .then((data) =>{ console.log('CartDATA', data); const … -
How to call django view onclick then redirect
I'm trying to make a searchbar in my django app. When I click on a result from the searchbar I want it to call my view. I want the view to keep the context from what was clicked, perform a function, and then redirect me. In my views.py def search(request): query = request.GET.get('q', '') if query: sp = SpotipyConnection(client_id=sp_client_id, client_secret=sp_client_secret) #context = {'search': sp.searchbar(query)} context = {'search': sp.songSearch(query)} return render(request,'main/search.html',context=context) return render(request,'main/search.html',{}) def search_results(request): if request.method == 'POST': #TODO how do i get the context of what was clicked songName = None songArtist = None context = openAISearch(artist=songArtist,song=songName) return render(request,'main/search_results.html',context=context) In my search.html: {% block title %} Search {% endblock %} {% block content %} <script> function redirectToHome(songName, songArtist) { <!-- TODO how do I call my search_results function then return the redirect --> } </script> <form method="GET" action="{% url 'search' %}"> <input type="text" name="q" id="search-input"> <button type="submit">Search</button> </form> </form> {% if search %} {% for result in search %} <p onclick="redirectToHome({{ result.name }},{{ result.artists.0.name }})"> {{result.name}} by {{ result.artists.0.name }} <img src="{{ result.album.images.0.url }}" alt="{{result.name}} image" style="width: 200px; height: 200px;"> </p> {% endfor %} {% endif %} {% endblock %}``` -
How to call variable processed in forloop function (views) in django template?
I am trying to refer a variable p in my django template after some logic was applied to it. Since it seems templates are only a place for making a page look nice, there must be a way to assign a value to a variable in a forloop and refer it into the template. views def function(request): q = Model.objects.all p = None for model in q : for in_model in ... if something: p = 1 return render(request,"template.html", {'q ':q , 'p':p}) template {%for model in q %} {% for in_model in ... %} {% if p == 1 %} P=1 {%else%} {%endif%} {%endfor%} {%endfor%} Following an example like this, how do I can I test if p=1? It seems whatever I try p=None because this is where the variable is first mentioned in the view. I tried to keep my example as generic as possible, I am hoping it wont affect the clarity of my question. Happy to provide more code if necessary. -
How can i only send and verify Tokens only in Djoser Django and not a pair of Token and Uid
I am trying to make a mobile app, and I only want to use Djoser to send the token once a user registers on the app. The most significant issue I have is that Djoser sends both a UID and a token, which I don't want. I only want it to send the Token a user can enter into the verify email field on the mobile app. How can I do that using Djoser in Django? DJOSER = { 'LOGIN_FIELD': 'email', 'USER_CREATE_PASSWORD_RETYPE': True, 'USERNAME_CHANGED_EMAIL_CONFIRMATION': True, 'PASSWORD_CHANGED_EMAIL_CONFIRMATION': True, 'SEND_CONFIRMATION_EMAIL': True, 'SET_USERNAME_RETYPE': True, 'SET_PASSWORD_RETYPE': True, 'PASSWORD_RESET_CONFIRM_URL': 'password/reset/confirm/{uid}/{token}', 'USERNAME_RESET_CONFIRM_URL': 'email/reset/confirm/{uid}/{token}', 'ACTIVATION_URL': 'activate/{uid}/{token}', 'SEND_ACTIVATION_EMAIL': True, 'SERIALIZERS': { 'user_create': 'users.serializers.UserCreateSerializer', 'user': 'users.serializers.UserCreateSerializer', 'user_delete': 'djoser.serializers.UserDeleteSerializer', } }