Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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"), … -
web app security concerns against XSS and CSRF
I'm building a website using django rest api and reactjs. I'm quite new to this and I've already read some articles and also questions here on different security issues with CSRF and XSS attacks. Currently my design includes jwt bearer authentication header in addition to csrf token and both of them are stored in browser cookies. However the jwt token must be set manually in headers and not automatically by browsers. Is this best practice? Would it be okay to exclude my own front end domain from CSRF check since it's trusted? I realize cookie authentication is a vulnerability to CSRF so I put the token in headers. On the other hand I know that XSS attack can gain access and read cookies so I guess this not the best approach. -
Images are not showing in slider in Django Website
I have completed all the requisite steps to display the images slider of my Django Website Project. But the images are not shown without displaying any error, I think there is a mistake in my home.html file Django code. For this guide me. Thanks for your kind anticipation models.py from django.db import models from datetime import datetime from ckeditor.fields import RichTextField from multiselectfield import MultiSelectField # Create your models here. class Car(models.Model): state_choice=( ('PU', 'Punjab'), ('KPK', 'Khyber PukhtunKha'), ('BL', 'Balochestan'), ('SN', 'Sindh'), ('FD', 'Federal Territory'), ) TRANSMISSION_CHOICES = ( ('M', 'Manual'), ('A', 'Automatic'), ) door_choices = ( ('2', '2'), ('3', '3'), ('4', '4'), ('5', '5'), ('6', '6'), ) features_choices=( ('Cruise Control', 'Cruise Control'), ('Audio Interface', 'Audio Interface'), ('Airbags', 'Airbags'), ('Air Conditioning', 'Air Conditioning'), ('Seat Heating', 'Seat Heating'), ('Alarm System', 'Alarm System'), ('ParkAssist', 'ParkAssist'), ('Power Steering', 'Power Steering'), ('Reversing Camera', 'Reversing Camera'), ('Direct Fuel Injection', 'Direct Fuel Injection'), ('Auto Start/Stop', 'Auto Start/Stop'), ('Wind Deflector', 'Wind Deflector'), ('Bluetooth Handset', 'Bluetooth Handset'), ) year_choice = [] for r in range(2000, (datetime.now().year+1)): year_choice.append((r,r)) car_title = models.CharField(max_length=255) state = models.CharField(choices=state_choice, max_length=100) city = models.CharField(max_length=100) color = models.CharField(max_length=100) model = models.CharField(max_length=100) year = models.IntegerField(('year'), choices=year_choice) condition = models.CharField(max_length=100) price = models.IntegerField() description = RichTextField() car_photo = … -
I am having issue with htmx and django
I am trying to create a social media add friend system with django and htmx. I keep getting 403 Forbbiden which is associated with invalid csrf token. I have tried to fix it but to no avail. views.py def get_friends(current_user): friend_ids = Friend.objects.filter( Q(user=current_user, request_accepted=True) | Q(requests_user=current_user, request_accepted=True) ).values_list('user', 'requests_user') # id of friends of current user in a list friend_ids = set( [user_id for sublist in friend_ids for user_id in sublist if user_id != current_user.id]) # user model of friends of current user friends = User.objects.filter(id__in=friend_ids) return friends def get_users_no_rel(current_user): sent_requests = Friend.objects.filter( user=current_user) list_sent_requests = sent_requests.values_list('requests_user', flat=True) received_requests = Friend.objects.filter( requests_user=current_user) list_received_requests = received_requests.values_list('user', flat=True) excluded_users = list(list_sent_requests) + \ list(list_received_requests) + \ [current_user.id] # list of users that have no relationship with the current user # user model of user in the excluded_users users = User.objects.exclude(id__in=excluded_users) return users def friends_view(request, **kwargs): current_user = request.user sent_requests = Friend.objects.filter( user=current_user) list_sent_requests = sent_requests.values_list('requests_user', flat=True) received_requests = Friend.objects.filter( requests_user=current_user) list_received_requests = received_requests.values_list('user', flat=True) excluded_users = list(list_sent_requests) + \ list(list_received_requests) + \ [current_user.id] # list of users that have no relationship with the current user # user model of user in the excluded_users users = User.objects.exclude(id__in=excluded_users) friends = get_friends(request.user) if request.htmx: … -
Django/Dash - injected script not executed but no errors
I'm trying to create a text area in a dash app which shall function as status window for the user. Updates shall be sent to the window via messaging (ws, channels, redis). html.Div(style={'flex': '0 0 auto', 'padding': '0px', 'boxSizing': 'border-box'}, children=[ dcc.Textarea( id='log-window', style={'width': '100%', 'height': '400px', 'resize': 'none'}, readOnly=True), html.Script(""" console.log('logging script loaded successfully!'); setTimeout(function() { var logWindow = document.getElementById('log-window'); if (logWindow) { var socket = new WebSocket('ws://127.0.0.1:8000/ws/logs/'); socket.onmessage = function (event) { var data = JSON.parse(event.data); logWindow.value += data.message + '\\n'; }; socket.onopen = function () { console.log('WebSocket connection opened'); }; socket.onerror = function (error) { console.error('WebSocket error:', error); }; socket.onclose = function () { console.log('WebSocket connection closed'); }; } else { console.error('logWindow element is null'); }; }); """) ]), The text area is created successfully but the injected script from above for starting the WebSocket connection is not executed. Nevertheless, the script is visible when inspecting the source code in the web browser. The console does not produce any error or hint. The text area is part of an iframe which holds the above dash application and allows scripts. The script was executed when I included it in the view.html but there were diffuclties in obtaining the … -
Microsoft Azure React-Django 403 Forbidden
I have made a react and django web application and it is hosted on Azure. The app works when run on localhost but when I run it on Azure I get a 403 forbidden error on my post requests. But my Get requests are working fine. I have set up django Cors/CSRF and it works fine when done locally. I set this up by following a tutorial but they never had this issue. I have been trying to find a solution to this but have not found one that works. Note: React is a static web app, and django backend is a webapp + database I read azure documentation to try and find the solution. But it appeared lots of the one si find the relate are outdataed. Posted on microsoft questions, no help. Watched many tutorials. Rewrote my django code to see if that was the issue. I just got no idea anymore -
Why does Django still display migrations when none exist?
I'm trying to reset my migrations and start off fresh but I'm getting this really strange issue I can't seem to fix. I started off by deleting the Migrations folder and Deleting every table in Database I'm using (for context it's a MySQL database and I'm using MySQL Workbench to access it). Now after doing so I ran the python manage.py showmigrations command and it keeps showing me all the old migrations even though none should exist. Here is what I tried to do to fix this issue: I tried to restart the server multiple times with every change or action I did I deleted and created the database again with the same name I deleted and created the database again with a different name I created an empty Migrations folder in hopes that maybe it would fill up the folder with the files but it does not, and now I have an empty Migrations folder and still an empty database with no tables I deleted all the __pycache__ folders I could find I know this isn't database-sided because I re-created the database with a different name as mentioned. I know there is something that is keeping all this data … -
How can I implement a Django queryset into an HTML datalist
I am creating my own ERP system and I have it completely operational. I have a problem in which the user cannot seem to find articles which they want to add to the order. So I was looking at trying to do this 100% HTML. My idea is the following: In forms.py I have defined my article queryset like this: self.fields['article'].queryset = Article.objects.filter(deleted=False) Then I have my widgets like this : 'article' : forms.TextInput(attrs={'type': 'input', 'list':articles}) The articles list is : <!-- Datalists --> <datalist id="articles"> {% for article in articles %} <option value='{{article.id}}'>[{{article.articlenumber}}] {{article.name}}</option> {% endfor %} </datalist> Then in the form the articleid is sent as article. So I pick that up and in my views then: article = request.POST.get('article') article = Article.objects.get(id=article) -
Removing custom field default method in Django
I implemented a field in my Django model with a default value that calls a custom class method I wrote. I ran and applied the migrations to my production deployment. Recently, I've found the field is no longer necessary, and I want to remove it and the custom class method from my model: Model code: from django.db import models class OrganizationConfig(models.Model): ... def get_sla_default_value(): # type: ignore return { Priority.STAT: "1:00:00", Priority.ASAP: "2:00:00", Priority.TIMING_CRITICAL: "6:00:00", Priority.PREOPERATIVE: "24:00:00", Priority.ROUTINE: "48:00:00", } ... priority_slas = models.JSONField(default=get_sla_default_value) Migration: class Migration(migrations.Migration): dependencies = [ ("core", "0085_alter_hangingprotocol_modality_and_more"), ] operations = [ migrations.CreateModel( name="OrganizationConfig", fields=[ ... ( "priority_slas", models.JSONField( default=nl_backend.core.models.OrganizationConfig.get_sla_default_value ), ), ... ], ), ] However, the class method is referenced in the migration generated when I first implemented the logic (as shown above) and deleting the method results in an error when I try to apply my migrations: Traceback (most recent call last): File "/app/./manage.py", line 31, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python3.9/site-packages/django/core/management/__init__.py", line 442, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.9/site-packages/django/core/management/__init__.py", line 436, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python3.9/site-packages/django/core/management/base.py", line 412, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python3.9/site-packages/django/core/management/base.py", line 458, in execute output = self.handle(*args, **options) File "/usr/local/lib/python3.9/site-packages/django/core/management/base.py", line 106, in wrapper res = handle_func(*args, **kwargs) File "/usr/local/lib/python3.9/site-packages/django/core/management/commands/migrate.py", … -
Can we change _id to
want to add nested data into mongoDB ,i am working in django, i have tried both the foreign key and EmbedField but unable to get nested data into database , when run migrations i created two models in mongoDB, my models are class Employee(models.Model): id=models.ObjectIdField() name = models.CharField(max_length=255) age = models.IntegerField() email=models.EmailField() phone_number=models.CharField(max_length=20) def __str__(self) -> str: return self.name class Company(models.Model): name = models.CharField(max_length=255) description = models.TextField() location = models.CharField(max_length=255) email=models.EmailField() employees = models.ArrayField( model_container=Employee, null=True, blank=True, ) def __str__(self): return self.name and the data i am getting in Company collection is like { "_id": { "$oid": "66c8b0c7fc77e7422da0e80d" }, "id": 2, "name": "dgdhg", "description": "abhdj", "location": "sdsgh", "email": "xeno@gmail.com" },,,,,i want some thing like this "{ "name": "ganesh", "location": "Guitar", "description": "abhdj", "email": "xeno@gmail.com", "employees": [ { "id": 2, "name": "John", "age": 23, "email": "adeebhassi@gmail.com", "company": 2, "phone_number": "2394820948" } ] }," -
Can`t update data in data base via patch method in django
I have a model of items, and i need to write CRUD operations with data. Post and get works, but patch - no, and i can`t understand why serializers.py class CreateItemSerializer(serializers.ModelSerializer): photo = serializers.ImageField(max_length=None, allow_empty_file=True, allow_null=True) class Meta: model = CreateItem fields = '__all__' def create(self, validated_data): items = CreateItem.object.create_item( name = validated_data.get('name'), description = validated_data.get('description'), type_item = validated_data.get('type_item'), photo=validated_data.get('photo') ) return items def update(self, instance, validated_data): instance.name = validated_data.get('name', instance.name) instance.description = validated_data.get('description', instance.description) instance.type_item = validated_data.get('type_item', instance.type_item) instance.photo = validated_data.get('photo', instance.photo) instance.save() return instance views.py class CreateItemView(APIView): serializer_class = CreateItemSerializer def post(self, request): serializer = self.serializer_class(data=request.data) serializer.is_valid(raise_exception=True) serializer.save() 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()] return Response({'name':item[pk], 'description':description[pk], 'type_item':type_item[pk]}, status=status.HTTP_200_OK) def patch(self, request, pk): serializer = CreateItemSerializer(data=request.data) serializer.is_valid(raise_exception=True) return Response(_("item updated successfully"), status=status.HTTP_200_OK) when i call patch method, "all works" but data doesn`t change -
Celery and Redis Command Overload Despite Optimizations in Django App
I’m facing an issue with my Celery + Redis setup for a Django project where the number of Redis commands being executed is skyrocketing despite having made several optimizations. I’m using Upstash Redis with the free tier, which has a daily limit of 10,000 commands. However, within an hour of starting the app, I’m already hitting thousands of Redis commands, primarily BRPOP, PUBLISH, and PING. This is happening even when the app is idle. Context: Django Version: 4.2 Celery Version: 5.4 Redis Broker: Upstash Redis Free Tier Deployment: DigitalOcean (App platform) App Details: The app is primarily used for scheduling and sending reminder emails using Celery tasks. Here’s a brief overview: I have Celery workers running for email sending tasks. There is no celery.beat setup. Tasks are invoked on-demand by the application logic. The app is relatively idle most of the time, with tasks being triggered only a few times a day. Optimizations I’ve Already Tried: Result Backend Disabled: I set CELERY_RESULT_BACKEND = None to avoid unnecessary reads from Redis. Heartbeat Adjustment: I increased the CELERY_BROKER_TRANSPORT_OPTIONS['heartbeat'] to 120 seconds, hoping it would reduce the command load. Prefetch Multiplier: Set CELERY_WORKER_PREFETCH_MULTIPLIER = 1 to ensure that only one task is fetched … -
How to properly use templates as a variable in django?
In general, I wanted to use TemplateView from Django to provide responses to users. Since my website will have many frames with content blocks as separate sections, I thought it would be very convenient to store them as class objects, each having its own variables and HTML files (templates). The main idea was to include multiple templates within a single TemplateView (in other words, many small TemplateViews within one TemplateView). The main problem I encountered is that the context_object_name variables conflict with names in other templates. How can this be resolved? Ideally, it would be great if the variable could be created locally for a specific template. For example, I will often refer to the rfq-details.html template, and there will be many of them, so it would be perfect if each table value could be enclosed in a variable that doesn't conflict with others. <div class="rfq-details"> <table> <tr><td>Name </td></tr> <tr><td>Main Characteristics of the Product </td></tr> <tr><td>Consumer Characteristics of the Product </td></tr> <tr><td>Type and Volume of Packaging </td></tr> <tr><td>Quantity (volume) Requested </td></tr> <tr><td>Terms of Delivery (INCOTERMS) </td></tr> <tr><td>Terms of Payment </td></tr> <tr><td>Expected Price Per Unit of Goods </td></tr> <tr><td>Compliance with Sanitary and Phytosanitary Standards </td></tr> <tr><td>Transportation Conditions </td></tr> <tr><td>Unloading Area </td></tr> …