Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Make endpoint that returns a list of strings using Django Rest Framework
I have this Artist model: class Artist(models.Model): name = models.CharField(max_length=100) #songs = models.ManyToManyField('Song', related_name='artists') def __str__(self): return self.name class Meta: ordering = ('name',) I want to make a api endpoint that returns all the Artists row names as a list of string like for example: ["50 Cent", "Eminem", "Snoop Dogg", ...] . i have created this artists/names/ url in my urls.py: path('artists/names/', views.artist_names, name='artist_names'), I have tried two ways already: Using a python list: @api_view(['GET']) def artist_names(request): artists = Artist.objects.values_list('name', flat=True) artist_names_list = list(artists) return Response(artist_names_list) Using ListSerializer in my serializers.py: class ArtistNameSerializer(serializers.Serializer): name = serializers.ListSerializer(child=serializers.CharField()) and in my views.py i created the artist_names method: @api_view(['GET']) def artist_names(request): artists = Artist.objects.values_list('name', flat=True) serializer = ArtistNameSerializer(artists, many=True) return Response(serializer.data) From both of them when i go to the endpoint i get: GET /api/artists/names/ HTTP 404 Not Found Allow: GET, PUT, PATCH, DELETE, HEAD, OPTIONS Content-Type: application/json Vary: Accept { "detail": "Not found." } Can someone help? What am i doing wrong? -
Chart.Js - Chart-geo map is too small
I'm using the module Chart-Geo to make a choropleth map using Chart.Js It actually displays, but for some reason it's too small. I'm not trying to make a zoom option (using scroll) but just make it proper for visualization. I couldn't find a solution since Chart-Geo documentation doesn't enter in zoom topics. Seems like it's rendering the entire world size, but as it lacks data from other countries, it's just rendering Brazil. Observations: I'm using the framework Django. I'm using datamaps's data to get topoJson. Here is my code: home.html {% extends "base.html" %} {% block body %} {% load static %} <link rel="stylesheet" href="{% static 'css/home/home.css' %}"> <body> <div class="banner2Div"> <p>Cadastro por região</p> <canvas id="chart4" width="400" height="400"></canvas> </div> </body> <script src="{% static 'javascript/chart.umd.js' %}"></script> <script src="{% static 'javascript/index.umd.min.js' %}"></script> <script src="{% static 'javascript/d3.js' %}"></script> <script src="{% static 'javascript/bra.topo.json' %}"></script> <script type="module" src="{% static 'javascript/home.js' %}"></script> {% endblock%} Javascript const chart4 = document.getElementById('chart4') import brJSON from './bra.topo.json' assert {type: 'json'} const canvas_width = chart4.width const canvas_height = chart4.height const trlte_shift = [canvas_width / 71, canvas_width / 28.8]; const states = ChartGeo.topojson.feature(brJSON, brJSON.objects.bra).features; const chart = new Chart(chart4, { type: 'choropleth', data: { labels: states.map(d => d.properties.name), datasets: [{ label: 'States', … -
I'm using Django and Postgres on Docker, but I can't connect to the database after reinitialising
IMPORTANT NOTE: Django can't RECONNECT to the database. It works, then I try reinitialising it, and it stops working due to what's described below. I can get it to work if I reboot my PC, though. I'm running Django and PostgreSQL with Docker Compose (one container for Django and the other for PostgreSQL) I was using the container perfectly with no problems. After typing sudo docker compose down -vand sudo docker compose up -d, Firefox won't connect, and will show the message: The connection was reset So I run sudo docker compose logs -f to check the logs and Django says it can't connect to the Postgres database with the following messages: [...]port 5432 failed: Connection refused Is the server running on that host and accepting TCP/IP connections? -
Can't write in input field, I'm using django and generating HTML from JS
I'll show you both my HTML and my JS code. Its simple by now, but this problem might be a challenge to all my project since I have several things that will work like this form. Apologies console.log message is in spanish, but it runs all the script. The problem is when i reach to the form itself i cant write anything, well you can write if you hold de click. Havent used any CSS, rather than the style thing on z i. const fillSection = (option = "user-registration", e ) => { console.log("you are filling section"); console.log(e); const content = document.querySelector('#user-registration') switch (option) { case "user-registration": content.innerHTML = `<form id="user-registration-form" method="post" style="z-index: 1000 !important;"> <div class="input-texts"> <div class="form-field"> <label for="name-user">Nombre</label> <input id="name-user" type="text" name="username" placeholder="Enter your name"> </div> <div class="form-field"> <label for="password-user">Password</label> <input id="password-user" type="text" name="password" placeholder="Enter your password"> </div> <div class="form-field"> <label for="email-user">Email</label> <input id="email-user" type="text" name="email" placeholder="Enter your email"> </div> </div> <button id="submit-button" class="form-btn" type="submit">Register</button> </form>`; const sendDataForm = document.getElementById("submit-button"); console.log("seleccionado el submit"); sendDataForm.addEventListener('submit', (e) => {apiSendDataUser(e)}); break; } }; const apiSendDataUser = (event) => { event.preventDefault(); const formData = new FormData (event.target); fetch('https://127.0.0.1:8000/videoHub/post_user',{ method: 'POST', data: formData }) .then(response => response.json()); } ; const registerSectionButton = … -
TemplateSyntaxError, Could not parse the remainder:
template.html {% with category2Choices=form.category2.field.choices.queryset.values_list("value", "display_name", "parent_id")|list %} <script> var category2Choices = JSON.parse('{{ category2Choices|json_script:"category2Choices" }}'); </script> {% endwith %} I am getting this issue: TemplateSyntaxError at /pages/add_product/ Could not parse the remainder: '("value",' from 'form.category2.field.choices.queryset.values_list("value",' I want to initially populate the main categories in a select field. When the user selects a main category, I want to dynamically fetch and display the subcategories related to that main category. To achieve this, I am using a small JavaScript code. Can you help me? -
How to maintain AnonymousUser session with Django test client
I have a Django TestCase where I would like to test an AnonymousUser visiting the same page twice. I would like to test that an action is only taken on the first visit, which is achieved by storing some data in the session upon the first visit. I can't use TestCase.client, because it uses a new AnonymousUser for each request and they have a new session. from django.test import TestCase class MyTestCase(TestCase): def test_my_test(self): self.client.get(url) response = self.client.get(url) self.assertTrue(...) -
Nginx authenticate iframe
I am running a django app on a server and i am running grafana on a different server with nginx as a reverse proxy (grafana and nginx are on the same server). I can manage to redirect an incoming URL and authenticate it via my backend, but I still get redirected to the grafana login screen, even when my django app sends a 200 response My setup: I am having a grafana server running under https with a nginx proxy. The nginx-setup server { server_name grafana.myserver.com; location / { proxy_set_header Host $host; proxy_pass http://localhost:3000/; proxy_set_header X-Real-IP $remote_addr; } location ~ ^/iframe(.*)$ { auth_request /iframe-auth; set $iframe_url http://localhost:3000$1$is_args$args; proxy_pass $iframe_url; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header Authorization $http_authorization; } location = /iframe-auth { internal; proxy_pass https://blub.de/auth/check/; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_pass_request_body off; proxy_set_header Content-Length ""; proxy_set_header X-Original-URI $request_uri; } } In the above I am using the nginx auth module to redirect the incoming URL from the iframe the my django backend server. Here I do the authentication which works fine. I tested this by printing out the URL and I am authenticating the user and I am returning a 200 response if authenticated. Ok cool. I expected … -
CORES header issue in react django application
we are using django with react and in the settings.py file we have set the "CORS_ORIGIN_ALLOW_ALL" to True. we have also installed the coresheader app. but when the frontend is going to request for an api from 'http://localhost:3000/' but we still get the CORS policy error => Access to XMLHttpRequest at 'https://backend.com/api/v1/Category' from origin 'http://localhost:3000' has been blocked by CORS policy: Request header field authorization is not allowed by Access-Control-Allow-Headers in preflight response. here is the settings.py file configurations: INSTALLED_APPS = [ ..., 'corsheaders', ] MIDDLEWARE = [ ...., 'corsheaders.middleware.CorsMiddleware', ] TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'frontEnd/build'), os.path.join(BASE_DIR, 'templates'), ], 'DIRS': [os.path.join(BASE_DIR, 'templates'), # os.path.join(BASE_DIR, 'venv/lib/site-packages/django/contrib/admin/templates') ], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], 'libraries': { 'staticfiles': 'django.templatetags.static', }, }, }, ] STATIC_URL = '/static/' STATICFILES_DIRS = [os.path.join(BASE_DIR, 'frontEnd/build/static'), ] STATIC_ROOT = os.path.join(BASE_DIR, 'static') MEDIA_URL = '/media/' MEDIA_ROOT = BASE_DIR / 'media/' CKEDITOR_UPLOAD_PATH = 'ck/' CKEDITOR_CONFIGS = { 'default': { 'toolbar': 'full' }, } CORS_ALLOW_CREDENTIALS = True CORS_ORIGIN_ALLOW_ALL = True and blew is how the frontend makes the api call requests using axios: import axios from 'axios' import { readCookie } from 'utils/readCookie' const isProduction = process.env.NODE_ENV === 'production' const csrfToken = readCookie('csrftoken') … -
ORM does not bring all the fields of a custom model of users
I am trying to get a user that I have saved with a custom model as follows: TblUsers.objects.get(id=request.user.id) But this only brings up the "email" field of my record, however I have many more fields in my custom model What brings me: <QuerySet [<TblUsuarios: juan@juan.com>]> My custom model: class TblUsers(AbstractUser): email = models.EmailField("email address", unique=True) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=True) date_joined = models.DateTimeField(default=timezone.now) phone= models.CharField(max_length=11, blank=True, null=True) photo= models.ImageField(upload_to=upload_image, default = '/') USERNAME_FIELD = 'email' REQUIRED_FIELDS=(['username']) objects = UserManager() class Meta: managed=True db_table = 'tbl_users' The manager class of my custom user: class UserManager(UserManager): def create_user(self, email, password, **extra_fields): """ Create a user """ if not email: raise ValueError(_("The email must have info")) email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save() return user def create_superuser(self, email, password, **extra_fields): """ Create a super user """ extra_fields.setdefault("is_staff", True) extra_fields.setdefault("is_superuser", True) extra_fields.setdefault("is_active", True) if extra_fields.get("is_staff") is not True: raise ValueError(_("The superuser should have is_staff=True.")) if extra_fields.get("is_superuser") is not True: raise ValueError(_("The superuser should have is_superuser=True.")) return self.create_user(email, password, **extra_fields) I have tried to get all the information from the table with: TblUsers.objects.all() But this has had the same result, it only fetches the "email" field from all the records -
ImportError: cannot import name 'Employees' from 'EmployeeApp.models'
I am pretty new to Building an application with Django Framework, Python and Flask. I tried to import reference some module and i receive this error. Can someone help? My code is below from django.shortcuts import render from django.views.decorators.csrf import csrf_exempt from rest_framework.parsers import JSONParser from django.http.response import JsonResponse from EmployeeApp.models import Departments,Employees from EmployeeApp.serializers import DepartmentSerializer,EmployeeSerializer The error that i saw ImportError: cannot import name 'Employees' from 'EmployeeApp.models'(/path/to/the/file.py) rest_framework.parsers could not be resolved. Also, it seem that the line of the Employees in line 6 & EmployeeSerializer in line 7 are not able to be imported. Please let me know if you need further information. I expected running python manage.py runserver to pass successfully but with the failed error above, it gives me worries. -
Sending email to a particular user email address in Admin Django
Need help on how to implement send mail to a particular user email address in Admin when logged in. For example, I have multiple registered users with email address in Admin, so if USER alukas logged in then an email will be sent to his email address albertlukasrodriquez@g..com... I attached images to my question based on what I have tried. -
Any recommendations for an smtp or email provider I could use for my Django project. I've tried several none work well with it
I have tried several email providers for my project but they don't seem to work so if you know or use anything not very common and it works well, I'd like to know as well and also I can't stress this point enough it must be free or have a free plan I have tried the popular ones like mailjet,sendgrid,MailChimp,brevo,Gmail outlook and Yahoo didn't even work even after using less secure app settings in Gmail -
Displaying an image saved in a variable in Vue 3
I have an application based on Vue 3 and Django REST. The application displays songs in a database, and is also supposed to display the cover images of the songs' respective albums. I have the cover images in the file system of the server and can access them via Django, and hand them out via a FileResponse when an API request comes in. I receive them in the Frontend and save the image to a variable. However, when I want to then display the image in an tag, it just looks like this: I want the gray boxes to display the album cover art instead. What's weird is that my browser receives the images from the API and displays them correctly: (I know that the cover art is incorrect for the songs, that's not the point here). The API (Django REST): @api_view(['GET']) def img_api(request): if request.method == "GET": if request.GET['id'] == 'undefined': return HttpResponse( HttpResponse(serializers.serialize('json', Song.objects.none()), content_type='application/json')) if 'id' in request.GET: query = request.GET['id'] song = Song.objects.filter(song_id=query).first() try: img = open(os.path.join(SONG_PATH, song.song_image_file), 'rb') if song.song_image_file.endswith(".png"): return FileResponse(img, content_type='image/png') return FileResponse(img, content_type='image/jpeg') # file is closed automatically except FileNotFoundError: return HttpResponse(HttpResponse(serializers.serialize('json', Song.objects.none()), content_type='application/json')) except PermissionError: return HttpResponse(HttpResponse(serializers.serialize('json', Song.objects.none()), content_type='application/json')) return HttpResponse(HttpResponse(serializers.serialize('json', … -
How can i add a message in the screen when receiving a 500 to explain you cannot add duplicates values using django and JS
Hi guys i have a little API created in django and i set some constraints in order to avoid duplicated values, so when you want to add a duplicated value it returns this message in the console is there a way i can add a message in the screen saying something like "this user already exists" right after the POST was denied? -
Has anyone ever used a private email server with Django
I am trying to send an otp to an email address, in my Django application,and so far most of the email providers are not very straight forward so I want to use a private server like hmail server but don't know how to go about it help me. I don't know what to do -
Sensitive data on the client side
Including a sensitive data on the client side how can I include the user id or other sensitive data in the client side ,and retrieve it after that without allows to the costumer to change it in the #clientside for example: name -
"Node" is unknown import symbol
I installed mptt and created some categories and sub categories. Now I want to control under admin page admin.py from django.contrib import admin from zummit.models import Product from zummit.models import ProductImage from mptt.admin import MPTTModelAdmin from zummit.models import Node admin.site.register(Product) admin.site.register(Node, MPTTModelAdmin) I am getting ""Node" is unknown import symbol" error for import Node area views.py class Category(MPTTModel): name = models.CharField(max_length=50, unique=True) parent = TreeForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='children') class MPTTMeta: order_insertion_by = ['name'] What is the problem here? -
Webpack-Nginx-Django - requests do not reach to the backend
I have an application, where frontend is implemented with Webpack, React and the backend with Python, Django. I deployed it to a hosted server and used nginx as a reverse proxy. I use Docker for the deployment and I have 1 container for each (frontend, backend, nginx). When I open the webpage of my app on a browser, it is correctly rendered. However, when I try to call any endpoint afterwards I get HTTP 404 Not Found. Logs for frontend and backend Docker containers are clean and nginx is having: "POST /myendpoint/ HTTP/1.1" 404 146 "https://example.com/" "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/115.0" So I assume that the request cannot reach to the backend from nginx. I have tried different approaches of troubleshooting and solving (like playing around nginx config, webpack config, upgrading webpack version to 5), but no luck so far. However, when I deployed it to a local server of mine with Docker, but without nginx, it was working as expected, but through http (not https) of course. My configs for nginx: worker_processes 1; events { worker_connections 1024; } http { include mime.types; default_type application/octet-stream; sendfile on; upstream backend { server 127.0.0.1:8000; } server { listen … -
deploying issues using heroku for my website
I have deployed my website using heroku but am getting an error when trying to access my website How do i get out of this error An error occurred in the application and your page could not be served. If you are the application owner, check your logs for details. You can do this from the Heroku CLI with the command heroku logs --tail -
Best web development framewok
what are the core languages suitable for web development? I was told the best platform for web development is “django platform” in python so; i just want to know why django is the best plafform for web application because for me, i’d rather use the traditional php and j.s instead of using django in python? -
how to gather delete all() query
for item in items: item.children.all().delete(deleted_by_id=id) how do I combine this into one delete query? where children are prefetch_related. items.values_list("children", flat=True).all().delete() which doesn't work i think it deleted items instead of children -
HTML " not converting to ' in Django
I am creating a django application and was trying to authenticate users on a button click and redirect the users accordingly. I have a button that logs in the user, but I want to redirect the user based on their authentication. The code is as follows: <button type="submit" class="btn btn-primary" value="Login" onclick = "location.href='{% url &quot;auth&quot; %}'">Login</button> While running the code I get the error: TemplateSyntaxError Could not parse the remainder: '&quot;auth&quot;' from '&quot;auth&quot;' Is this because "&quot"; is not working as intended? Could someone please shed some light on this? -
Celery can't launch tasks by schedule despite settings
I have a django project with this code: settings.py CELERY_ENABLE_UTC = False CELERY_TIMEZONE = 'Asia/Omsk' celery.py # -*- coding: utf-8 -*- from __future__ import absolute_import import os from celery import Celery from celery.schedules import crontab os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'sendings.settings') app = Celery('sendings') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() app.conf.beat_schedule = { 'sending_to_emails': { 'task': 'app.tasks.sendings', 'schedule': crontab(minute=36, hour=22) }, } In my docker-container based on alpine image i check datetime and it's correct accordings with my tz settings. I down my docker containers and rebuild them, but this problem still remains. -
Creating Order instance in django/ choose the existing customer or add new customer
I am building an inventory management system. In this template I allowing to either choose an existing customer or add new. However, even though i am able to save orders when creating a new customer instance, i am not able to do so with the existing customer. I used some javascript to disable the fields accordingly, however it is still not working create_order.html {% extends "inventory/layout.html" %} {% block body %} <h1>Create Order</h1> <form method="POST" action="{% url 'create_order' %}"> {% csrf_token %} <!-- Customer form section --> <h4>Customer Information</h4> <div class="form-group"> <input type="radio" id="existing_customer_radio" name="customer_option" value="existing" checked> <label for="existing_customer_radio">Select Existing Customer:</label> <select id="existing_customer" name="existing_customer"> <option value="">---------</option> {% for customer in existing_customers %} <option value="{{ customer.id }}">{{ customer.name }}</option> {% endfor %} </select> </div> <div class="form-group"> <input type="radio" id="new_customer_radio" name="customer_option" value="new"> <label for="new_customer_radio">Create New Customer:</label> <div id="new_customer_form" style="display: none;"> {{ customer_form.as_p }} </div> </div> <!-- Order form section --> <h4>Order Items</h4> {{ formset.management_form }} {% for form in formset.forms %} <div class="order-item-form"> {{ form.as_table }} </div> {% endfor %} {{ order_form.as_p }} <button type="submit">Save Order</button> </form> <script> // Show/hide new customer form based on selected radio button var existingCustomerRadio = document.getElementById("existing_customer_radio"); var newCustomerRadio = document.getElementById("new_customer_radio"); var newCustomerForm = document.getElementById("new_customer_form"); var customerFormFields … -
Allauth with JWT
My project requires JWT authentication, but also allauth is needed. How can i get JWT tokens after login via socials? I have surfed the net completely and tired of seeking the answer, the last hope I have is here, i guess... I tried using simple_jwt but didn`t get any result. Also used dj-rest-auth but it is complicated. I guess the clue in dj-rest-auth, but i cannot find out how to use it. I got an answer from net with this example: class GitHubLogin(SocialLoginView): adapter_class = GitHubOAuth2Adapter callback_url = "http://localhost:8000/" client_class = OAuth2Client but it requires those 3 credentials: access_token, code and id_token. Surfing the net i haven`t found any proper answer(