Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: Render views in an html/css page
I followed a tutorial on setting up an auth system, using JWT, and a simple oauth2. at some point, at the tutorial he started using Vit/React for the front end. and that's where we separated ways xD. I wanna use a simple html/css code for now. My problem is I can't get the views and my html to be fully compatible, and even if I get it working the redirections don't work at all. basically let's say I registered successfully, I would either render http://127.0.0.1:8000/api/v1/auth/register with debugs and if I get the redirection to work properly I would get redirected to http://127.0.0.1:8000/api/v1/auth/login/ instead of domain/login at some point I got it to work, from signup to verification to login but my code was quite messy and I used a lot of js to get the result, mean while in the tutorial where he used React, he just routed the views through urls.py to his React routes ! so that's when I was like, am sure there is gonna be a way where I shouldn't use a lot of js scripts just to get me to redirect from sign up to verification to login ! I reverted back to my initial … -
Django-redis configuration
I have a Django app. I want to use django-redis to cache the results of my queries so as to improve the app performance. I've implemented this on the local server and it works as intended. When deployed on a live server, I get an Internal Server Error. This is because of the configurations of Redis to the app which forms the basis of my question. How should I go about configuring my app with Redis. I'm deploying using AWS. Below are the cache settings in settings.py CACHES = { "default": { "BACKEND": "django_redis.cache.RedisCache", "LOCATION": "redis://127.0.0.1:6379/1", "OPTIONS": { "CLIENT_CLASS": "django_redis.client.DefaultClient" }, "KEY_PREFIX": "example" } }``` -
What is wrong with my JavaScript for my Django e-commerce project? [closed]
When inputing my javascript for my add to cart functionality, I am getting a redd swiggle error for my url: '{% url 'cart_add' %}',. Despite having this, my code is working as expected. I am not sure what is wrong or how to fix it. I am currently using VSCode as my code editor. My git project for this: https://github.com/mgrassa14/ecom.git -
Django_Huey: Connection failed
I keep getting "connection failed: connection to server at "127.0.0.1", port 5432 failed: FATAL: password authentication failed for user "root" connection to server" when running my task in production. This does not happen in local development. I have tried to add a Postgres db. connection to the supervisor but the error still persists. @db_periodic_task(crontab(minute='*/1'), queue='application') def parcel_expiration_task(): # current date and time current_timestamp = timezone.localtime(timezone.now()) # get all event get_events = Event.objects.order_by('-creation_time').filter( time_ends__lt=current_timestamp ) if get_events.exists(): ... [program:access] command='...' user='...' autostart=true autorestart=true redirect_stderr = true stdout_logfile = /etc/supervisor/realtime.log environment=DATABASE_URL="postgresql://...:...@localhost:5432/..." -
CSRF Cookie Django/React
I have issue with CSRF token in Django and React and i can't find solution. The problem show up when I want to update the product thumbnail This is problem: Forbidden (CSRF cookie not set.): /admin/product/15/api/products/upload/ [23/May/2024 18:36:32] "POST /admin/product/15/api/products/upload/ HTTP/1.1" 403 2960 from rest_framework.response import Response from rest_framework.decorators import api_view, permission_classes from rest_framework.permissions import IsAdminUser from base.models import Product from base.serializers import ProductSerializer @api_view(["GET"]) def get_products(request): products = Product.objects.all() serializer = ProductSerializer(products, many=True) return Response(serializer.data) @api_view(["GET"]) def get_product(request, pk): product = Product.objects.get(id=pk) serializer = ProductSerializer(product, many=False) return Response(serializer.data) @api_view(["POST"]) @permission_classes([IsAdminUser]) def create_product(request): user = request.user product = Product.objects.create( user=user, name="Sample Name", price=0, brand="Sample Brand", count_in_stock=0, category="Sample Category", description="", ) serializer = ProductSerializer(product, many=False) return Response(serializer.data) @api_view(["PUT"]) @permission_classes([IsAdminUser]) def update_product(request, pk): data = request.data product = Product.objects.get(id=pk) product.name = data["name"] product.price = data["price"] product.brand = data["brand"] product.count_in_stock = data["count_in_stock"] product.category = data["category"] product.description = data["description"] product.save() serializer = ProductSerializer(product, many=False) return Response(serializer.data) @api_view(["DELETE"]) @permission_classes([IsAdminUser]) def delete_product(request, pk): product = Product.objects.get(id=pk) product.delete() return Response("Produkt został usunięty.") @api_view(["POST"]) def upload_image(request): data = request.data product_id = data["product_id"] product = Product.objects.get(id=product_id) product.image = request.FILES.get("image") product.save() return Response("Obraz został załadowany") import React, { useState, useEffect } from "react"; import axios from "axios"; import { Link, … -
Newlines with JSON Objects
I have this api that should Translate text,and it is working when using one line text, however, when using multi line text it fails. @api_view(['POST']) @csrf_exempt def translate_english_to_arabic(request): try: data = json.loads(request.body) text = data.get('text', '') if not text: return Response({'error': 'Text field is required.'}, status=status.HTTP_400_BAD_REQUEST) translator = Translator() translated = translator.translate(text, src='en', dest='ar') return Response({'translated_text': translated.text}, status=status.HTTP_200_OK) except Exception as e: return Response({'error': str(e)}, status=status.HTTP_400_BAD_REQUEST) I am using Django, and django rest framework. This is a sample of the text that generates the error: { "text": "This is a multi-line text with several lines and paragraphs." } This is the error that pops to me: "error": "Invalid control character at: line 2 column 37 (char 38)" -
Mobile and Web application Architecture: React Native, Django, Postgres and Supabase
Want to build a side project so let me give you a bit of the scope before diving into my proposed architecture and how I can get them to play nice. It's a market place where partners can create accounts and login only through a website (they are businesses decisions why this is the case). Buyers can only login through a provided mobile application, built in React Native. My primarily server side technology is Django built on a postgres database. This will hold a lot of the server side functionality and host the API the mobile application will be consuming. Now I have been looking at a few BaaS and the two that stick out are FireBase and Supabase. What I want the BaaS to manage is: Authentication across multiple providers (Google, Facebook/Instrgram, iOS,email and phone). Push notification cross platforms. I have quite a constrained budget of about $60 a month. Scenario 1: Host my Django app and database on Digital Ocean it's quite affordable. Then choose supabase to do my Authetication and push notifications. I like this setup also because my API and database can be in the same same datacenter and use an internal IP, significantly reducing my … -
Django inbox messaging functionality not working
So I'm trying to add messaging functionality to my e-commerce website, where buyers can message sellers and sellers can message buyers once the buyer has purchased something from them (haven't written the code for that yet, just want basic messaging functionality out of the way). So this is what I've tried. So about my views, I have two views. Through the message_seller view I can directly message that specific seller, it takes me to the inbox of that seller, and the user_messages_view is like an inbox of that user's messages, sent and received, and the user can select a message to open up the conversation. I can send message to other users, but there is one problem with this. That is when a user receives a message initiated by another user, the inbox shows an incorrect self-conversation rather than the actual message. Even though the unread message counter correctly shows the unread messages for that user. Can anyone please help me solve the issue? Thanks in advance! My models.py: class Business(models.Model): BUSINESS_TYPE_CHOICES = [ ('product', 'Product Business'), ('service', 'Service Business'), ] seller = models.OneToOneField(CustomUser, on_delete=models.CASCADE, related_name='business') business_name = models.CharField(max_length=100) description = models.TextField() business_slug = models.SlugField(unique=True, blank=True) business_type = models.CharField(max_length=20, choices=BUSINESS_TYPE_CHOICES) … -
UnicodeEncodeError at / 'charmap' codec can't encode characters in position 18-37: character maps to <undefined>
urgent question. I am trying to execute model.predict(image) in django, but I get an error here i code def image_predict(image_data): image = image_data image = load_img(image, target_size=(224, 224)) image = img_to_array(image) image = np.array(image) image = preprocess_input(image) image = np.reshape(image, (1, 224, 224, 3)) prediction = np.argmax(nermodel.predict(image)[0]) return prediction prediction should be equal to for example 3 I would be very grateful if you could tell me what to do the error occurs when running the line model.predict(image) I've already tried making changes to the encoding, fast API, and changing the dataset. -
How Can I show just values of the dicitionary on HTML?
I have created a function to get some date from database, make some calculations and show it in HTML files. However I could not to get just values from views. def list_pay(request): item = Pay.objects.all() # Quantidades q_total = Pay.objects.all().count q_open = Pay.objects.filter(status=0).count q_paied = Pay.objects.filter(status=1).count # Soma dos valores v_total = Pay.objects.aggregate(Sum('value')) v_open = Pay.objects.filter(status=0).aggregate(Sum('value')) v_paied = Pay.objects.filter(status=1).aggregate(Sum('value')) data = { 'item':item, 'v_total':v_total, 'v_open':v_open, 'v_paied':v_paied, 'q_total':q_total, 'q_open':q_open, 'q_paied':q_paied } return render(request, 'pay/list_pay.html', data) <div class="row d-flex justify-content-center"> <h3 class="mb-3 mt-3">Lista <span class="text-success">de pagamentos</span></h3> <div class="col m-3 p-3"> <label>Total de boletos</label> <h1 class="text-primary"> {{ q_total }}</h1> <h1 class="text-primary"> {{ v_total }}</h1> </div> <div class="col m-3 p-3"> <span>Quantidade de boletos</span> <h1 class="text-success">{{ q_paied }}</h1> <h1 class="text-success">{{ v_paied }}</h1> </div> <div class="col m-3 p-3"> <span>Quantidade de boletos</span> <h1 class="text-danger">{{ q_open }}</h1> <h1 class="text-danger">{{ v_open }}</h1> </div> </div> The current value loaded = {'value__sum': 1831}. The expected output = 1831 I alredy try .values() and transform the dict in a list and other format. -
Unique constraint violation on auth_user_pkey in Wagtail
I created a user import view (with Django's User model) for a new Wagtail app, which works well. I did a few tests, and ended up with IDs for my test users in the range of 140-150 on my development machine. Afterwards, I transferred the DB to a test machine. When I tried to create a new user via the Wagtail admin interface on the test machine, a unique constraint violation for auth_user_pkey was returned. But the offending new ID was close to the highest existing ID, so after three more tries, I arrived at an unused ID and was able to create the new account. What is going on here? Why does Wagtail try to (re-)use existing IDs, and how can I prevent the issue? -
I am new to python and django, therefore, having encountered this error, I do not know how to solve it TemplateDoesNotExist at /users/login/
settings: enter image description here urls.py - learning_log: enter image description here urls.py - users: enter image description here login.html: enter image description here The way to login.html: enter image description here According to the book, it should look something like this enter image description here But it throws such an error enter image description here -
In django DRF using JWT, why does postman properly block access to some views but they are available from my Angular front-end without authentication?
I’m trying to restrict access to some views of my API using Django Rest Framework and simpleJWT https://django-rest-framework-simplejwt.readthedocs.io/ The issue I’m facing is that postman correctly blocks access to my views when I do not provide a valid JWT to my API but my Angular front-end does not and gives access to all the views of my DRF API. { "detail": "Authentication credentials were not provided." } Here is a beginning of a view with from rest_framework.response import Response from rest_framework.permissions import IsAuthenticated from rest_framework_simplejwt.authentication import JWTAuthentication from ..serializer import General_emission_group_serializer_years from django.db import connection class EmmissionGroup(APIView): authentication_classes = [JWTAuthentication] permission_classes = [IsAuthenticated] def get(self, request): Here is my settings.py from pathlib import Path import os import environ from django.contrib.auth import get_user_model from django.contrib.staticfiles import handlers class CORSStaticFilesHandler(handlers.StaticFilesHandler): def serve(self, request): response = super().serve(request) response['Access-Control-Allow-Origin'] = '*' return response handlers.StaticFilesHandler = CORSStaticFilesHandler # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent env = environ.Env() environ.Env.read_env(os.path.join(BASE_DIR, ".env")) SECRET_KEY = env("SECRET_KEY") DEBUG = True ALLOWED_HOSTS = ["127.0.0.1"] INSTALLED_APPS = [ "corsheaders", 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'rest_framework_simplejwt', #"rest_framework.authtoken", "django_filters", "camping", "admin_honeypot", "axes", ] AUTHENTICATION_BACKENDS = [ 'rest_framework.authentication.TokenAuthentication', # Token-based authentication for API 'django.contrib.auth.backends.ModelBackend', # Default … -
The response content must be rendered before it can be accessed
I am trying to make the custom response format for that i have done below mentioned code middleware from django.utils.deprecation import MiddlewareMixin from rest_framework.response import Response from rest_framework.exceptions import APIException class CustomResponseMiddleware(MiddlewareMixin): def process_response(self, request, response): from adminPanel.serializers import MyCustomException if not isinstance(response, Response): return response response.render() if 'data' in response.data: return response response_data = { 'status': response.status_code, 'message': 'Success', 'error': False, 'data': response.data, 'error_message': None, } if isinstance(response, MyCustomException): error_message = response.detail.get('error_message', None) response_data = { 'status': response.status_code, 'message': 'Error', 'error': True, 'data': None, 'error_message': error_message, } return Response(response_data, status=response.status_code) in setting.py 'adminPanel.middleware.custom_response.CustomResponseMiddleware', serializers.py class LoginSerializer(serializers.Serializer): username_or_email = serializers.CharField() password = serializers.CharField(write_only=True) access_token = serializers.CharField(read_only=True) refresh_token = serializers.CharField(read_only=True) user_type = serializers.CharField(read_only=True) request_source = serializers.CharField(read_only=True, default='mobile') def validate(self, data): username_or_email = data.get('username_or_email') password = data.get('password') if not username_or_email or not password: raise MyCustomException(detail={"error_message": "Must include 'username_or_email' and 'password'."}, status_code=status.HTTP_400_BAD_REQUEST) user = authenticate( request=self.context.get('request'), username=username_or_email, password=password ) if user is None: raise MyCustomException(detail={"error_message": "Invalid username/email or password."}, status_code=status.HTTP_400_BAD_REQUEST) if not user.is_active: raise MyCustomException(detail={"error_message": "User is inactive."}, status_code=status.HTTP_400_BAD_REQUEST) if not user.email_verified: email_otp = ''.join([str(randint(0, 9)) for _ in range(6)]) user.email_otp = email_otp user.save() send_registration_email.delay( 'Welcome to Your Website', 'email.html', {'code': email_otp}, settings.EMAIL_HOST_USER, [user.email], ) raise MyCustomException(detail={"error_message": "Please verify your email first"}, status_code=status.HTTP_400_BAD_REQUEST) … -
How can I use email with django-allauth without mail server?
I'd like to configure django-allauth in such a way that users have to register with email and password but the Django project does not have to provide a mail server and no emails are transmitted (no registration confirmation, no password reset link, etc.). How do I have to configure django-allauth. -
Value is not copying properly in input tag
I am trying to add or edit the form in django by creating customized form using html and css. Now it works fine for add product form but when i trying edit one of field in the form,image url does not passing to input tag and when i submit the form it says image tag is empty. How to recitfy it? ` Cake image {% if Product.product_img %} <img src="{{ Product.product_img }}" alt="Product Image"> {% endif %} <input type="file" name="product_img" accept="image/*" id="product_img"> </div>` -
Is it possible to change the display of a Binaryfield model attribute in the Django admin panel, based on the value of another attribute?
I'm working on a project where I have a model which stores some BinaryField in the database. class Entry(models.Model): ... params = models.JSONField() body = models.BinaryField() ... params will have a tag with the type of the body item. For example it might be html, and the body will be the html text or an image, and the body could be an image etc. Right now, the details of Django admin show something like this: Body: <memory at 0x7355581f0e80> Is it possible to change how django admin displays this info, based on the info I have from the other attributes? Thanks for your time! -
How to change structure of articles in django-wiki?
I am new to django-wiki and want to change the structure of article form. As default has Title, contents and summary. I want to add 2 more fields for "main" and "history". How can do that? Thanks in advance. I tried looking it up on the internet but sources are scarce. -
Render request for html page changes url link to #
I am using Django to render html pages. When it renders, it works fine but it changes link to #. Let me explain views.py def index(request): return render(request, 'index.html') urls.py router = routers.DefaultRouter() router.register(r'users', UserViewSet) .... urlpatterns = [ path('homepage/', views.index, name='homepage'), path('', include(router.urls)), ] When I want to view the html page I go to link named: http://127.0.0.1:8000/api/homepage/ But when it enters the page browser link changes to : http://127.0.0.1:8000/#/ How can I solve this issue? -
unable to decode encrypted bytes data stored in db
I have written 2 functions in python, one for encrypting data and other for decrypting data which are as follows. from app.settings import DATA_KEY import logging from cryptography.hazmat.primitives.ciphers.aead import AESSIV import base64 cipher_suite = AESSIV(DATA_KEY) error_logger = logging.getLogger("error_logger") def encrypt_field(input_text): try: if isinstance(input_text, str): input_text = input_text.encode() enc_text = cipher_suite.encrypt(input_text, associated_data = None) print(f"enc_text is {enc_text}") enc_text_base_64 = base64.b64encode(enc_text) print(f"encrypted_text is {enc_text_base_64}") return enc_text_base_64 except Exception as e: error_logger.error(f"exception in encrypt field {str(e)} on field {input_text}") return input_text def decrypt_field(input_text): try: print(f"input in decrypt field is {input_text} its type is {type(input_text)}") enc_text = base64.b64decode(input_text) print(f"enc text is {enc_text}") decrypted_field = cipher_suite.decrypt(enc_text, associated_data = None) print(f"decrypted_field is {decrypted_field}") return decrypted_field.decode('utf-8') except Exception as e: print(e) error_logger.error(f"exception in decrypt_field {e} on field {input_text}") return input_text I am able to encrypt and store the data in db, however upon reading the data from db and trying to decrypt it, I am getting a utf-8 bytestring instead of original plaintext string back. What am I doing wrong here? My Django version is 5.0, Python version is 3.10.11 and Database is PostgreSQ I have tried storing the data in BinaryField as well TextField of Django models, but to no avail the result is same. I … -
Internal Sever Error 500 and unauthorised 401 error
I am working with Django and NextJS, i keep getting 2 error whenever i try to login: From my AuthContext.js file "500 (Internal Server Error)" From my UseApi.js file "401 (Unauthorised)" whenever i try to login it throws this two errors i have added a authorisation header but still getting the same error Here is how each file are structured: AuthContext.js import { createContext, useState, useEffect } from "react"; import useSWR from "swr"; import { httpWeb } from "../services/http"; import { usePostHog } from "posthog-js/react"; export const AuthContext = createContext(); export default function AuthContextProvider (props) { const [token, setToken] = useState(null); useEffect(() => { // This code runs only on the client side const storedToken = localStorage.getItem('token'); console.log("Token for request:", storedToken); setToken(storedToken); }, []); const posthog = usePostHog() const [ isLoading, setLoading ] = useState(true) const [ isAuthenticated, setAuthenticated ] = useState(false) const [ user, setUser ] = useState(null) const { data: user_data, error: user_err, mutate: refreshUser } = useSWR('/api/auth/user', url => httpWeb.get(url, { headers: { 'Authorization': `Bearer ${token}` } }).then(res => res.data, { errorRetryCount: 0, refreshInterval: 0, shouldRetryOnError: false })) const signOut = () => { httpWeb.post('/api/auth/logout') .then(() => { setAuthenticated(false) setUser(null) setLoading(false) posthog.reset() }) .catch(err => {}) } … -
Connecting problem to another user's PostgreSQL database in Django
I have a question. I'm starting to work on a Django project. I received database credentials for a PostgreSQL database created by a colleague. How can I connect to this database? enter image description here Unfortunately, after starting the Django server, the error shown in the attached screenshot appears in the terminal. Please help. Thank you! -
Migrating to TZ aware datetime in Django, PostgreSQL timestamp
I use Django ORM to access PostgreSQl data. Database is relatively big ~100 tables, some with dozens of millions of records. I'm switching from Django 4.2 to Django 5.0, which has USE_TZ = True by default and I want to keep it that way, so after the migration - hopefully there won't be any naive datetimes in my system. I have models like: class MyExistingModel(BaseModel): name = models.CharField(max_length=100, unique=True, null=False, blank=False) date_created = models.DateTimeField(auto_now_add=True) ...and what I'm witnessing for the most of my models is the following: In [6]: mem = MyExistingModel.objects.create(name="new record") In [7]: mem.date_created Out[7]: datetime.datetime(2024, 5, 23, 6, 15, 25, 885356, tzinfo=datetime.timezone.utc) In [8]: MyExistingModel.objects.get(name="new record").date_created Out[8]: datetime.datetime(2024, 5, 23, 1, 15, 25, 885356) Same record, same field - two different datetime formats: aware vs naive. Whenever those two are mixed I'm of course getting an error like: TypeError: can't compare offset-naive and offset-aware datetimes This is a big problem as I can hardly control every single place where DateTimeField is used. It seems that the reason behind this is the fact that date_created in my PostgreSQL, which was created by Django long time ago, is of timestamp without time zone. That's what I'm seeing with DB … -
Defining test methods in base class which should not be instanciated directly
I am trying to create test cases which only differ by which user is logged in. Therefore I figured defining the tests in a base class and creating sub classes which log in the user during setUp() would be the way to go. However I cannot find an elegant solution to excluding the tests in the base class from running. from django.contrib.auth.models import User from django.test import TestCase class A(TestCase): @classmethod def setUpTestData(cls): cls.user_a = User.objects.create_user("a", "", "a") cls.user_b = User.objects.create_user("b", "", "b") def setUp(self): # global set up stuff here ... def test_1(self): self.assertEqual(self.user_a.username, "a") class SubA(A): def setUp(self): super().setUp() self.client.force_login(self.user_a) class SubB(A): def setUp(self): super().setUp() self.client.force_login(self.user_b) In the code above I'd want only the inherited tests in the classes SubA and SubB to run, but not the one in A. I have tried: extracting the base class to another module, which is not included by the default search pattern. => still runs the tests since the base class must be imported to inherit from it defining a load_tests(...) function in the package which excludes the base class => same result as above raising unittest.SkipTest in the base class setUp() and catching it in the sub classes' setUp => … -
Cache response from a request in python
I'm writing some backend scripts in python that have to be coupled with a web interface that uses django. The web application allows to view layers that comes from different web services. As part of my tasks I developed a tool that request elevation data from a geoserver (a WCS service) and then, based on the a previous line drew by a user in the front end, is able to generate a cross section of the underlying data. So, in short: when a user draws a line over a layer and then clicks draw-profile, my function request the data, intersects the line when the associated raster/layer and returns a figure to the front-end. The problem with that approach is that each time the user clicks draw-profile, the request is made again, which takes some time. When the request is made, the data is stored in a DTM object (class that I made) in a self.raster property. A simplified version of the function that requests the data is shown below. def get_dtm_from_wcs100( self, raster_source: str = "YY", layer: str = "XX", format: str = "image/tiff", version: str = "1.0.0", resx: int = 1, resy: int = 1, ) -> None: """ …