Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
"detail": "Authentication credentials were not provided." drf
I'm doing a pet project. And I need to make that only authorized users can make POST/PATCH requests, and that only the owners of items can change/delete them. views.py(item_app) class CreateItemView(APIView): serializer_class = CreateItemSerializer authentication_classes=[OwnAuthentication] permission_classes=[IsAuthenticatedOrReadOnly, IsOnwerOrReadOnly] ... code ... permissions.py(item_app) from rest_framework import permissions class IsOnwerOrReadOnly(permissions.BasePermission): def has_object_permission(self, request, view, obj): if request.method in permissions.SAFE_METHODS: return True return obj.owner == request.user authentication.py(auth_app) from django.contrib.auth.models import User from rest_framework import authentication from rest_framework import exceptions class OwnAuthentication(authentication.BaseAuthentication): def authenticate(self, request): username = request.data.get('username') if not username: return None try: user= User.object.get(username=username) except User.DoesNotExist: raise exceptions.AuthenticationFailed('No such user') return (user, None) settings.py AUTH_USER_MODEL = "auth_app.Users" REST_FRAMEWORK = { 'DEFAULT_PARSER_CLASSES':[ 'rest_framework.parsers.JSONParser', ], 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework_simplejwt.authentication.JWTAuthentication', ], } [Authorization is done via JWT tokens, at login I get access token and copy it and paste it into header “Authorization” in postman, and when I enable this header there is still an errorenter image description here]1 -
How to handle custom error message for Django Admin panel save_model method?
I've overwritten a save_model method for ModelAdmin. Let's say like below: def save_model( self, request, obj, form, change, ): if not change: try: if True: raise exceptions.ValidationError( _(f"Oh no, record can't be created for serious reason!") ) except exceptions.ValidationError as err: messages.set_level(request, messages.ERROR) self.message_user(request, err.message, level=messages.ERROR) return super().save_model(request, obj, form, change) I can't use Form, since I need database access to validate business logic. This almost worked, nevertheless I get redirect to main admin panel screen with I don't really like. Moreover, there is ADDITIONAL message displayed, that object does not exist (of course it doesn't exist, since it wasn't created). I will appreciate any tips how to stay on current screen and display just a custom message or at least be redirect to main admin panel screen, but without displaying additional message (just my custom one). -
Trying to run django for the first time
I can't access files in my app hello in my template, rendering them does not work. Here is my github repo to understand the issue https://github.com/Firiceee/Bug_django . I tryed to understand where does the problem come from as u can see with the exept, and effectively it triggers the except, furthermore, the last render, simpler does already not work, it's like , I can't access my directory "templates"... -
Session ID Returns None After Setting Session Data in Django with React Frontend
I'm working on a Django backend with a React frontend and using sessions to manage user authentication. After successfully logging in a user, I'm setting session data (e.g., user_id, name, email, etc.), but the session ID is returning as None despite the session data being correctly stored. I've configured SESSION_ENGINE to use the database and set SESSION_SAVE_EVERY_REQUEST = True. CORS headers are properly configured with CORS_ALLOW_CREDENTIALS = True. Despite these settings, the session ID isn't being generated or returned correctly, which is causing issues with session management on the client side. How can I resolve this issue and ensure the session ID is properly generated and accessible after login?(https://i.sstatic.net/EawnCfZP.png) I configured Django's session settings to use database-backed sessions, set SESSION_SAVE_EVERY_REQUEST = True, and enabled CORS with credentials. I expected the session ID to be generated and returned after a user logs in, allowing for proper session management. However, the session ID is returning as None, even though the session data is correctly stored and accessible. I’ve also verified that CORS and session settings are properly configured but still face the issue.enter image description here -
Integrating Strapi with existing backend and database
I’m working on a website that uses a Django backend with NextJS frontend. The database used is PostgreSQL. The website can be considered as an affiliate marketing platform. So a lot of features involving brands and products are present. Now a new Strapi CMS was decided to be added to the website for handling brand and products. So the django backend will be used for all the other functions while the direct CRUD of the brands and products will be handled by Strapi. But strapi flushes the entire connected database and I don’t want to set the entire database schema in strapi since it uses only brands and products - two tables. While the current backend has about 50 tables. So this means that Strapi would require a new database instance. Now, product and brand data is also needed by the existing django backend for some functions. So is there a way that I can just use Strapi for its frontend and further plugins while I can continue to use Django as the backend. -
the runserver command don't show url
I wanted to execute the runserver command, but it show lot's of non useful texts/codes I expected the url to adminstration site, but it just showed this: Watching for file changes with StatReloader Exception in thread django-main-thread: -
What libraries do programmers often use? And is it necessary to learn PyGame and Tkinter?
I am a beginner programmer and I want to understand what to do after learning the basics of Python. What libraries to learn and where to go?I want experienced python developers to answer. Thanks for your attention. I tried to learn tkinter but then I thought why do I need it and do programmers use the tkinter library -
How can I send an image inside a form in a state variable in react to a django backend
I am trying to send an image to be stored in the backend. The image is stored in a react useState that is updated when the user changes the the input form and is sent to its django backend api. The api accepts other inputs, not just the image, that are strings. So to send the request I store everything in an useState and make the request in an async function. The api has been tested to work on postman, the problem is I don't know too well how to make the request. The image is an optional parameter and therefore it works perfect just with the other inputs, without the image. Previously, I ignored the image and went along with the other inputs to make the request, which worked perfectly. I did this by putting everything in an object. Although when I put the image in the same object it stops working. I looked around and I found out to send images I need to use the FormData constructor and so I did, but I encountered a few problems. This is how my form component looks like: export default function Component() { const [ image, setImage ] = useState<File>(); … -
about useing photo in django
enter image description here from django.db import models # Create your models here. class Food (models.Model): name=models.CharField(max_length=100) tozih=models.CharField(("tozih"), max_length= 50) rate=models.IntegerField(("score")) price=models.IntegerField() pub=models.DateField(("when"), auto_now= False , auto_now_add= True) p2hoto=models.ImageField(upload_to='foods/' , max_length= 20000 ) i want to in my admin page upload a image but is giving me this -
Is there a ModelAdmin method that runs after Model.clean()?
I'm raising ValidationError in my model's clean() method from django.core.exceptions import ValidationError class PosDetail(models.Model, PosDetailChecksMixin): self._errors = set() ... def clean(self, *args, **kwargs): if PosDetail.objects.filter(username=self.username).exists(): # example ValidationError self._errors.add('check_duplicates') raise ValidationError("This username is already in use.", code="invalid") return super().clean(*args, **kwargs) the ValidationError then is shown in the admin change view form after a POST request. i want to show a button in the admin change view after form submission i tried the save_model method but i dose not execute if a ValidationError is raised. i also tried to override the change_view method of the ModelAdmin but it executes before the Model clean method so it misses the validations. @admin.register(PosDetail) class BddDetailAdmin(admin.ModelAdmin): ... def change_view(self, request, object_id, form_url="", extra_context=None): extra_context = extra_context or {} pos_detail = self.get_object(request, object_id) if request.POST: if pos_detail and 'check_duplicates' in pos_detail._errors: extra_context['show_save_anyway'] = True else: extra_context['show_save_anyway'] = False return super().change_view(request, object_id, form_url, extra_context) Is there a ModelAdmin method that runs after Model.clean() ? so i can catch the ValidationError that accur in the Model.clean method. -
Django makemigrations not making migrations for my app
Full disclosure. This is for my github project warehauser which can be found at: https://github.com/warehauser/warehauser If you download it and follow the INSTALL file instructions it says to python manage.py makemigrations But when that is done it does not make the migrations for the core app. 'core' is included in the warehauser/settings.oy INSTALLED_APPS setting. The 'core' app/directory is in the project base directory. If I go: python manage.py makemigrations core It picks up the core app and makes the migrations. But I want to know why it is not working without specifying the core app explicitly. I attempted: (venv) D:\project\warehauser\>python manage.py makemigrations And expected that to include making migrations for core app. I attempted: (venv) D:\project\warehauser\>python manage.py makemigrations core And that worked. But I need the first command to work for the core app. -
What are the steps involved in Django API creation? [closed]
I'm currently learning Django. All the online resources have been teaching the concepts or uploaded their own created apps or API? What are the steps involved in creating an API in Django? From Scratch, How an individual can create an API using Django? The prerequisites, basic steps or How to partition the project for creating an API and proceed with that? -
How to accept cryptocurrency payments on your Django site?
I am creating a site in Python/Dajngo, which will be completely paid. To use the site, the user will have to pay for a monthly subscription. I want to accept payments in crypto to my wallet. If you give users a wallet address, it will be impossible to understand which user paid for the subscription. We need to somehow differentiate this. How can I implement such functionality without using third-party services? Perhaps, using the API of the exchange where I am going to accept payments, I can somehow implement this, but I am not yet so familiar with the API, for example, Bybit or Binance. Maybe there are some libraries in Python. I don't know any exchange API for creating such functionality. -
how to hash a password in django while creating a user
here is my views from django project. how do i hash my password @api_view(['POST']) def register(request): data = request.data serializer = SignUpSerializers(data=data) if serializer.is_valid(): if not CustomUser.objects.filter(email=data['email']).exists(): user = CustomUser.objects.create( first_name = data['first_name'], last_name = data['last_name'], email = data['email'], username = data['username'], password = data['password'] ) return Response({ 'details':"User registered sucessfully." }, status.HTTP_201_CREATED) return Response({ 'error':"Email already exists." }, status.HTTP_400_BAD_REQUEST) return Response(serializer.errors) hasing while creating a user is better or while saving in model -
i got an error in python anywhere for wrong password or username
emote: Invalid username or password. fatal: Authentication failed for 'https://github.com/PixelXl81/django_starter.git/' Traceback (most recent call last): File "/home/Pixel/.local/bin/pa_autoconfigure_django.py", line 49, in main( File "/home/Pixel/.local/bin/pa_autoconfigure_django.py", line 31, in main project.download_repo(repo_url, nuke=nuke), File "/home/Pixel/.local/lib/python3.10/site-packages/pythonanywhere/django_project.py", line 20, in download_repo subprocess.check_call(['git', 'clone', repo, str(self.project_path)]) File "/usr/local/lib/python3.10/subprocess.py", line 369, in check_call raise CalledProcessError(retcode, cmd) subprocess.CalledProcessError: Command '['git', 'clone', 'https://github.com/PixelXl81/django_starter.git', '/home/Pixel/pixel.pythonanywher e.com']' returned non-zero exit status 128. i tried api token that i get from python anywhere too but again i getting this error -
"detail": "Authentication credentials were not provided." django-rest_framaework
I`m making my own pet project, and i need do permissions for users. When user register and create item, only he/she can delete/change item. But when i make a permissions, next login from user account and try to create item, i get error (get method works). views.py from .permissions import IsOnwerOrReadOnly class CreateItemView(APIView): serializer_class = CreateItemSerializer permission_classes = [permissions.IsAuthenticatedOrReadOnly, IsOnwerOrReadOnly] def post(self, request): serializer = self.serializer_class(data=request.data) serializer.is_valid(raise_exception=True) serializer.save(owner=self.request.user) return Response(_('item created successfully'), status=status.HTTP_201_CREATED) def get(self, request, pk, format=None): item = [item.name for item in CreateItem.object.all()] description = [item.description for item in CreateItem.object.all()] type_item = [item.type_item for item in CreateItem.object.all()] price = [item.price for item in CreateItem.object.all()] return Response({'name':item[pk], 'description':description[pk], 'type_item':type_item[pk], 'price':price[pk]}, status=status.HTTP_200_OK) def patch(self, request, pk): instance = get_object_or_404(CreateItem, id=pk) serializer = CreateItemSerializer(instance, data=request.data, partial=True) serializer.is_valid(raise_exception=True) serializer.save() return Response(_("item updated successfully"), status=status.HTTP_200_OK) def delete(self, request, pk): item = CreateItem.object.get(id=pk) item.delete() return Response(_("item deleted successfully"), status=status.HTTP_204_NO_CONTENT) permissions.py from rest_framework import permissions class IsOnwerOrReadOnly(permissions.BasePermission): def has_object_permission(self, request, view, obj): if request.method in permissions.SAFE_METHODS: return True return obj.owner == request.user urls.py(items_app) from .views import CreateItemView from django.urls import path urlpatterns = [ path('item-create/', CreateItemView.as_view(), name='item-create'), path('item-create/<int:pk>', CreateItemView.as_view(), name='item-create'), ] urls.py(auth_app) from django.urls import path from .views import (RegisterUserView, VerifyUserEmail, LoginUserView, PasswordResetRequestView, PasswordResetConfirmView, SetNewPasswordView, … -
Cant activate virtual enviroment with DJango Windows
I'm new to django and following this tutorial: https://www.youtube.com/watch?app=desktop&v=c-QsfbznSXI At 6:15 he showed command to how to activate virtual env(im using Windows) but it doesnt working for me Command in tutorial: env/Scripts/activate.bat nothing happens (https://i.sstatic.net/oTQorh9A.png) i tried this commands: venv\Scripts\activate venv/bin/activate doesnt work -
create content page - filter queryset by foreignkey and render the result to Django templates -
Trying to render this structure (tree structure): Book_1 Books_1's Chapters Book_2 Books_2's Chapters book:To Kill a Mockingbird itschapter:Chapter 1 - The Beginning of the Finch's itschapter:Chapter 2 - The Adventures of Education ... book:The Sweet Hereafter itschapter:Chapter 1 - Dolores Driscoll itschapter:Chapter 2 - Billy Ansel ... I have two Django models(tables) for just that: two tables with id and name columns. # myApp/models.py from django.db import models # books table # class books_DB(models.Model): #pk is book_id book_id = models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID') book_name = models.CharField(max_length=100) # chapters table # class chapters_DB(models.Model): #pk is chapter_id chapter_id = models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID') #foreign key 'book_id' from 'books_DB' book_id = models.ForeignKey(textbooks_DB, on_delete=models.CASCADE, default=None) chapter_name = models.CharField(max_length=100) I tested how to get this structure in python shell from .models import * for x in books_DB.objects.all(): print(x.book_name) for y in x.chapters_db_set.all(): print(' ' + y.chapter_name) To Kill a Mockingbird The Beginning of the Finch's The Adventures of Education The Sweet Hereafter Dolores Driscoll Billy Ansel Now I wish to render the result to a page like this <ul class="books"> <li class="book">To Kill a Mockingbird</li> <ol class="chapters"> <li class="chapter">The Beginning of the Finch's</li> <li class="chapter">The Adventures of Education</li> </ol> <li class="book">The Sweet Hereafter</li> <ol class="chapters"> … -
Django venv finding old version of PostgreSQL -> django.db.utils.NotSupportedError: PostgreSQL 13 or later is required
I'm resurrecting my local environment for a Django project that I haven't run locally in 2 years, working through issues around things that have gone stale. But I have one a little different: it looks like Django is finding/using an older version of PostgreSQL than the version I see in the venv itself. (Same symptom using pycharm where I used to run my local environment, and VSCode venv where I'm trying fresh). What's a good approach for tracking down old versions so I can remove them? When I run python mysite/manage.py runserver, I get django.db.utils.NotSupportedError: PostgreSQL 13 or later is required (found 10.13). BUT when I check package versions in the venv I'm running, most packages are current, and PostgreSQL is 3.12.5 (not 13 or later like we'll ultimately need, but also not 10.13). (from pip list) Django 5.1 (from pip list) psycopg2 2.9.9 (from pip list) psycopg2-binary 2.9.9 (from pip list) psycopg2-pool 1.2 psql -V gives: psql (PostgreSQL) 12.3 python -v gives: Python 3.12.5 Unsurprisingly, if I try a naive uninstall from the venv (pip uninstall postgresql-10.13), it says it's not installed. What's a good approach for tracing where that 10.13 could be coming from? Looking in the stack … -
allow insecure authentication in mailtip with django
I'm implementing mailtip in my little django project with docker and when I use docker compose up for mailtip volume it throws this error in docker desktop: time="2024/08/24 12:50:37" level=error msg="[smtp] authentication requires STARTTLS or TLS encryption, run with `--smtp-auth-allow-insecure` to allow insecure authentication" and this is my docker-compose.yml for mailtip: mailpit: image: docker.io/axllent/mailpit:v1.15 container_name: estate_prod_mailpit ports: - "8025:8025" - "1025:1025" volumes: - estate_prod_mailpit_data:/data environment: MP_MAX_MESSAGES: 5000 MP_DATA_FILE: /data/mailpit.db MP_SMTP_AUTH_ACCEPT_ANY: 1 MP_SMTP_AUTH_ACCEPT_INSECURE: 1 networks: - estate_prod_nw -
how do i set django up? and fix this error?
127.0.0.1/:1 Refused to execute script from 'http://127.0.0.1:8000/scripts/scripts.js' because its MIME type ('text/html') is not executable, and strict MIME type checking is enabled. error i got... how do i even fix this? i have generated a template from django and they look messy so i want to organise files like .css files and pages files... i tried to add my .css file and routed the html to use this .css. later i discovered that i gotta add {% load static %} to load static files i have added this too and still not working.... this s the image guys in the image i made a styles folder and wanted to use that but not the site.css file, i think i need to edit some things in the settings.py can you guys instruct me? -
Django database is really slow with PostgreSQL
I've built a simple website using django. Everything was fine with SQLite, but when I started deploying and switched to vercel's PostgreSQL database page load time jumped to around 5-10secs, even if I run django locally and connect to the hosted database. I tried to switch to aiven but it didn't help, so I think problem is not in vercel. My database is pretty small (it's a portfolio project), around 40 books and 2 users so it's probably not an optimization issue either. Also, I wrote a simple script to migrate database from vercel to aiven and it looks to do so with normal speed, but I'm not sure. -
request.user.is_authenticated check not working as expected for routes outside of those provided by Django Allauth
I am having issue where request.user.is_authenticated returns false with a valid X-Session-Token sent in the header whenever a request is sent to other part of the app apart from those url provided by allauth and headless. I am new to Django and in fact, this is my first Django project. I might be missing some things but haven't found solution elsewhere. I used custom user via CustomAccountAdapter which extends allauth.account.adapter.DefaultAccountAdapterby overriding the save_user function based on what I digested from the documentation. I defined custom token strategy to generate access_token and refresh token while copying the implemention of session token from allauth: from allauth.account.adapter import DefaultAccountAdapter from users.models.user_profile import UserProfile from allauth.account.utils import user_email, user_username import json class CustomAccountAdapter(DefaultAccountAdapter): def save_user(self, request, user, form, commit=True): data = json.loads(request.body) email = data.get("email") username = data.get("username") user_email(user, email) user_username(user, username) if "password" in data: user.set_password(data["password"]) else: user.set_unusable_password() self.populate_username(request, user) user.is_creator = data.get('is_creator', False) if commit: # Ability not to commit makes it easier to derive from # this adapter by adding user.save() if data.get('birth_date', False): UserProfile.objects.create(user=user, birth_date=data.get('birth_date', None)) return user I have a custom middleware where I want to block unauthenticated request from accessing some route patterns but the middleware could not … -
how can i make my python django view code logic very efficient or fast or less mysql query execution..?
I'm working on a Django view that handles a lot of data and performs several operations, including filtering, sorting, aggregating, and pagination. However, the current implementation is running a lot of unnecessary queries, making it inefficient, slow, and time-consuming. What I Need Help With: I want to optimize this view logic to make it more efficient, ensuring that no unnecessary queries are executed, and the code runs faster. Ideally, I would like to reduce the number of queries being executed and avoid redundant code execution. How can I refactor this code to achieve these goals? #my views- def LendersPeerCompare(request): lender_filter = LenderCompareFilt(request.GET) if request.method == 'GET': # Get selected lenders Lender1names = request.GET.getlist('Lender1') Lender2names = request.GET.getlist('Lender2') # Get sorting parameters sort_date1 = request.GET.get('sort_date1', 'none') sort_date2 = request.GET.get('sort_date2', 'none') # Fetch data for selected lenders with sorting Lender1_data = lender_filter.qs.filter(charge_holder_name__in=Lender1names) Lender2_data = lender_filter.qs.filter(charge_holder_name__in=Lender2names) # Apply sorting based on parameters if sort_date1 == 'asc': Lender1_data = Lender1_data.order_by('date_of_creation') elif sort_date1 == 'desc': Lender1_data = Lender1_data.order_by('-date_of_creation') if sort_date2 == 'asc': Lender2_data = Lender2_data.order_by('date_of_creation') elif sort_date2 == 'desc': Lender2_data = Lender2_data.order_by('-date_of_creation') # Determine which comparison to perform if request.GET.get('compare_xlsx') == 'true': # Calculate total sum of amount for all data Lender1_total_amount = Lender1_data.aggregate(total_amount=Sum('amount'))['total_amount'] Lender2_total_amount = … -
How can I show my Image in my web site using django
I tried to show image in my web which I uploaded that from admin panel by hand by using django I was expecting to see my image in web site, but instead it only showed the little img icon, and when I debugged the static in urls.py it returned me 'Not Found: /events/event_pictures/7.png' input my models.py file's related model class class Event_Model(models.Model): name = models.CharField(max_length=200) explanation = models.TextField(default="") link = models.CharField(max_length=300, default="") price = models.DecimalField(decimal_places=2, default=0.00, max_digits=10) stock = models.IntegerField(default=-1) release_date = models.DateField() end_date = models.DateField() image = models.ImageField(default="default.jpg", upload_to="event_pictures") is_avaible = models.BooleanField(default=True) # Form Attrs form_id = models.ForeignKey(Form_Model, on_delete=models.CASCADE) form_title = models.CharField(max_length=200) form_explanation = models.TextField(default="") project's urls.py file from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path("admin/", admin.site.urls), path("", include("User_App.urls")), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) project's urls.py file code when I used for debugging from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path("admin/", admin.site.urls), path("", include("User_App.urls")), ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_ROOT, document_root=settings.MEDIA_ROOT) app's urls.py file from django.urls import path from .views import FormView, CreateFormView, MainPage, EventsPage urlpatterns = [ path("", MainPage, name="index"), path("form/", FormView, name="form"), …