Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to Edit the Django User Verification Email Link
My Django User Verification Email Link starts "http" below is example http://examplesitexxx.com/accounts/confirm-email/MTA:1poGIh:x7zOj4350ZP6uLhT0wUEp1CRE13jWrvRanofpFgTBkw/ I want to change the Verification URL that starts with 'https'. So I access the file "allauth/templates/account/email/email_confirmation_message.txt" In this file I see "{{ activate_url }}" It should be a source of Verification Email URL but I can't figure out how to change the activate_url that start from "https" from "http" I just mentioned the above settings in this question but still if more code is required then tell me I'll update my question with that information. Thank you -
Database Optimization of a Giveaway Website Using Django
Hello everything is fine? So, the old project that is a "raffle" site has a chronic problem which is the use of up to 1000% of the CPU that is an AMD Ryzen 9 with 16 cores at high peaks of site usage. The total responsible for this enormous use is the database due to its lack of architecture/optimization. The challenge is: Solve this and make the site fast and accessible. For that, I'll use Django and thought of some ways to solve this, among them, here's a possible solution. models.py from the app raffle class Raffle(models.Model): ... amount_of_numbers = models,PositiveInteger(default=100000) The system will define the total number of tickets or the user and with these numbers, in the save method I will create 50-100 .txt files with numbers from 1 to 100000 without repetitions to avoid adding repeated numbers and causing " harmful queries" import fcntl with open('arquivo.txt', 'r') as arquivo: fcntl.flock(arquivo, fcntl.LOCK_EX) ... fcntl.flock(arquivo, fcntl.LOCK_UN) I will use the a lib fcntl to guarantee that only one user has access to that list of numbers (that's why several lists) and avoid having to check repeated numbers in the database and after finishing the process, I will release the … -
cx_Oracle not found in RDP
I am trying to run the django in remote server where Internet access is not avaiable, I have copied the libaries/pacakages from my local to remote server and tried to run it and packages were accepted but cx_Oracle it is module not installed.I have already set the client libary path in environmental path. PS C:\Users\Administrator\Documents\HC_REST\HC_REST> python manage.py runserver Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\Sysadm01\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\db\backends\oracle\base.py", line 52, in <module> import cx_Oracle as Database ModuleNotFoundError: No module named 'cx_Oracle' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\Sysadm01\AppData\Local\Programs\Python\Python311\Lib\threading.py", line 1038, in _bootstrap_inner self.run() File "C:\Users\Sysadm01\AppData\Local\Programs\Python\Python311\Lib\threading.py", line 975, in run self._target(*self._args, **self._kwargs) File "C:\Users\Sysadm01\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\Sysadm01\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\management\commands\runserver.py", line 125, in inner_run autoreload.raise_last_exception() File "C:\Users\Sysadm01\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\utils\autoreload.py", line 87, in raise_last_exception raise _exception[1] File "C:\Users\Sysadm01\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\management\__init__.py", line 398, in execute autoreload.check_errors(django.setup)() File "C:\Users\Sysadm01\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\Sysadm01\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\Sysadm01\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\apps\registry.py", line 116, in populate app_config.import_models() File "C:\Users\Sysadm01\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\apps\config.py", line 269, in import_models self.models_module = import_module(models_module_name) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Sysadm01\AppData\Local\Programs\Python\Python311\Lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "<frozen importlib._bootstrap>", line 1206, in _gcd_import File "<frozen importlib._bootstrap>", … -
Django models and null=True
I am creating an auction website. I have a Django model for Listings. It looks like this: class Listings(models.Model): price = models.FloatField() title = models.CharField(max_length=64) description = models.CharField(max_length=128) imageUrl = models.CharField(max_length=1000, default="") isActive = models.BooleanField(default=True) owner = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, null=True, related_name="user") category = models.ForeignKey(Category, on_delete=models.CASCADE, blank=True, null=True, related_name="category") watchlist = models.ManyToManyField(User, blank=True, null=True, related_name="watchlistListing") def __str__(self): return f"{self.id}: {self.title}, {self.description}, {self.price}, {self.imageUrl}" My problem is that whenever I create a listing and try to access its 'owner' attribute, it returns 'None'. However, I can access the current user perfectly fine by using 'request.user'. I tried removing the null=True and the blank=True parameters from the owner attribute. However this did not work and now whenever I try to access the owner attribute it just says the listing has no owner. type here -
Django: how to create a signal using django?
I have a bidding system and there is an ending date for the bidding, i want users to bid against themselves till the ending of the bidding date. The product creators are the ones to add the ending date which would be some date in the future, how can i write a django signal to check if the date that was added as the ending date is the current date, then i'll perform some operations like mark the highest bidder as winner. This is my model class Product(models.Model): user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) price = models.DecimalField(max_digits=12, decimal_places=2, default=0.00) type = models.CharField(choices=PRODUCT_TYPE, max_length=10, default="regular") ending_date = models.DateTimeField(auto_now_add=False, null=True, blank=True) ... class ProductBidders(models.Model): user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) product = models.ForeignKey(Product, on_delete=models.SET_NULL, null=True, related_name="product_bidders") price = models.DecimalField(max_digits=12, decimal_places=2, default=1.00) date = models.DateTimeField(auto_now_add=True) -
Getting this error in DJANGO when trying to make a record inSQL
Not sure why I am getting this error when I try to call a function within my load_data() django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. However, when I run the crud_ops.py function it works fine and sets the records within the database load_data.py def publisher_data(listt, start): from reviews.models import Publisher check_list = [] query_list = [] for i in range(start + 1, len(listt)): if listt[i].__contains__("publisher"): check_list.append(listt[i]) else: query_list.append(listt[i]) if len(query_list) == len(check_list): print(query_list) publisher = Publisher(name=query_list[0], website=query_list[1], email=query_list[2]) publisher.save() query_list = [] if listt[i].__contains__("content"): break def load_data(): file_read = open("WebDevWithDjangoData.csv", "r") text = file_read.read().split(",") new_list = [x for x in text if x.strip() != ''] list_1 = [] start_index = None end_index = None for x in new_list: list_1.append(x.strip()) file_read.close() for x in range(len(list_1)): #print(list_1[x]) if list_1[x] == "content:Publisher": start_index = x publisher_data(list_1, start_index) crud_ops.py: def crud_ops(): from reviews.models import Publisher, Contributor publisher = Publisher(name='Packt Publishing', website='https://www.packtpub.com', email='info@packtpub.com') publisher.save() publisher.email = 'customersupport@packtpub.com' publisher.save() print(publisher.email) contributor = Contributor.objects.create(first_names="Rowel", last_names="Atienza", email="RowelAtienza@example.com") print(contributor) print('\n>>> END <<<') manage.py: import os import sys from crud_ops import * def main(): """Run administrative tasks.""" os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'bookr.settings') try: from django.core.management import execute_from_command_line … -
Problems with Django structuring when entering models, views and serializers in folders?
Hello I am learning to program in Django and I have a database of 22 tables, as you can see making all the models in a single class would be very cumbersome and messy to find or make corrections, the same thing happens to me with serializers and views. How would it be the right thing to create as separate modules to the base project or to make backend/api/models ... backend/api/views ... backend/api/serializers/init.py? enter image description here I created something basic serializer and view but when I join it to the urls.py I get compilation problems. I was told that inside each folder create the init.py and integrate there the from of what is created in that folder, but when I start to spread it to the other modules it generates error. Example: Folder Models Models/__init__.py from . import Service Folder Serializers Serializers/__init__.py from . import ServiceSerializer The default models, serializers and views files that are created by default are blank, is that the problem? Views/__init__.py from . import service_view Views/service_view.py from models.Service import Service from rest_framework import generics from rest_framework.response import Response from rest_framework.decorators import api_view from serializers.service_serializer import ServiceSerializer # Listar servicios class ServiceListApiView(generics.ListCreateAPIView): queryset = Service.objects.all() serializer_class … -
Does apply_async(retry=False) disable the task level retry
I have a task like such @shared_task(bind=True, max_retries=150) def payout_reconciliation_single_task(self, txn_id): try: txn = Transaction.objects.filter(pk=txn_id).select_for_update().get() except Transaction.DoesNotExist: self.retry(throw=False, countdown=10 * 60) return Now if I call the task like payout_reconciliation_single_task.apply_async((123,), countdown=10, retry=False) Will the self.retry inside the try-catch block inside the except block in the task still be honored? -
How to deal with the error "Lists are not currently supported in HTML input"?
I have an nested sterilizer: class LinkSerializer(serializers.ModelSerializer): class Meta: model = Link fields = [ 'linkname', 'linkurl' ] class WorkSerializer(serializers.ModelSerializer): links = LinkSerializer( many=True, # queryset = Link.objects.all() ) class Meta: model = Work fields = [ 'firstname', 'lastname', 'links' ] The django models look like this: class Work(models.Model): firstname = models.CharField("Имя", max_length=10, blank=True) lastname = models.CharField("Фамилия", max_length=30, blank=True) class Link(models.Model): links = models.ForeignKey(Work, related_name='links', on_delete=models.CASCADE, blank=True) linkname = models.CharField("linkname", max_length=100, blank=True) linkurl = models.CharField("linkurl", max_length=100, blank=True) The django rest framework outputs the following about Links: Links: Lists are not currently supported in HTML input. I realized that I need to work towards json For nested serializers, but it doesn't work out, so I ask for help, how would you deal with this problem. Thanks in advance to the one who will help please take another look at the screenshot attached to the question Json ?? -
Error during template rendering in Django framework
Error during template rendering, I used for loop to iterate categories in home page,home page isn't loading after I put this code: <a href="{% url 'ProductPage' catg=d.CategoryName %}"> home page : <div class="row"> <!-- single product --> {% for d in data %} <div class="col-lg-3 col-md-6"> <div class="single-product"> <img class="img-fluid" src="{{d.CategoryImage.url}}" alt=""> <div class="product-details"> <a href="{% url 'ProductPage' catg=d.CategoryName %}"> <h6>{{d.CategoryName}}</h6> </a> <div class="price"> <h6>$150.00</h6> <h6 class="l-through">$210.00</h6> </div> <div class="prd-bottom"> <a href="" class="social-info"> <span class="ti-bag"></span> <p class="hover-text">add to bag</p> </a> <a href="" class="social-info"> <span class="lnr lnr-heart"></span> <p class="hover-text">Wishlist</p> </a> <a href="" class="social-info"> <span class="lnr lnr-sync"></span> <p class="hover-text">compare</p> </a> <a href="" class="social-info"> <span class="lnr lnr-move"></span> <p class="hover-text">view more</p> </a> </div> </div> </div> </div> {% endfor %} views.py from django.shortcuts import render from MyApp.models import CategoryDB, ProductDB # Create your views here. def homepage(request): data = CategoryDB.objects.all() return render(request,"home.html",{'data':data}) def aboutpage(request): return render(request,"about.html") def ProductPage(request,catg): prod = ProductDB.objects.filter(Category_Name=catg) return render(request,"products.html", {'prod':prod}) urls.py from django.urls import path from webapp import views urlpatterns=[ path('homepage/',views.homepage, name="homepage"), path('aboutpage/', views.aboutpage, name="aboutpage"), path('ProductPage/<catg>/', views.ProductPage, name="ProductPage"), models.py from django.db import models # Create your models here. class CategoryDB(models.Model): CategoryName = models.CharField(max_length=50, null=True, blank= True) Description = models.CharField(max_length=200, null=True, blank= True) CategoryImage = models.ImageField(upload_to="CategoryImages", null=True, blank=True) class ProductDB(models.Model): Category_Name= models.CharField(max_length=100,null=True,blank=True) … -
why is request.user.is_authenticated printing out false even when user is logged in and rendering template
I am fairly new to Django and I use Django 4.2. I am building a website and I have run into this error. I have created my login function like this def loginUsers(request): context = {} if request.method == 'POST': email = request.POST['email'] upass = request.POST['password'] user = authenticate(request, email=email, password=upass) if user is not None: login(request, user) messages.success(request, 'Login successful') time.sleep(2) return redirect(reverse('index')) else: messages.error(request, 'Invalid user') return redirect(reverse('login')) return render(request, 'auth_pages/login.html', context) But my logout function is not in this contact app views.py. It is in my index app views.py because the logout button in my template is in the navbar. Here it is: def loadIndexPage(request): context = {} print(request.user.is_authenticated) return render(request, 'pages/index.html', context) def logoutUser(request): if request.method == 'POST': logout(request) messages.success(request, 'You are logged out') return redirect(reverse('login')) The problem The problem is that the logout function is not logging out the user, it instead, is creating a csrftokenmiddleware in the browser search bar and when I print the request.user.is_authenticated it prints false. In the template: {% if request.user.is_authenticated %} <p>Hey there user</p> {% else %} <p>Not working</p> {% endif %} This is not working. It is only showing Not working. I have tried to add a @login_required … -
How to Add bulk delete by ids in Django Rest Framework
I'm trying to add Bulk delete by ids in my Django rest framework project but stucked in views .py anyone knows how to implement this feature in my project? here is my class in views.py : class AssignmentViewSet(viewsets.ModelViewSet): """View for manage assignment APIs.""" serializer_class = serializers.AssignmentSerializer queryset = Assgnment.objects.all() authentication_classes = [TokenAuthentication] permission_classes = [IsAuthenticated] def get_queryset(self): """Retrieve recipes for authenticated user.""" return self.queryset.filter(user=self.request.user).order_by('-id') def get_serializer_class(self): """Return the serializer class for request.""" if self.action == 'list': return serializers.AssignmentSerializer return self.serializer_class def perform_create(self, serializer): """Create a Assignment.""" serializer.save(user=self.request.user) here is my URLs : from rest_framework.routers import DefaultRouter from assignment import views router = DefaultRouter() router.register('assignment', views.AssignmentViewSet) router.register('tags', views.TagViewSet) app_name = 'assignment' urlpatterns = [ path('', include(router.urls)), ] please let me know if you need more details about my project -
Error during template rendering | Could not parse the remainder: '(pandas.NaT)' from 'pandas.isnull(pandas.NaT)'
I'm trying to display a dictionary via html in django app and that each value of dictionary is a dataframe. I'm able to print key but not dataframe for which I've tried many different approaches. Either I get key value pair printed which is not very human readable or I get Could not parse the remainder error Here's snippet of views.py context = {'rail': rail} return render(request, 'sample_output.html', context) where rail is my dictionary Here's snippet of html <table> <thead> <tr> {% for key in rail.keys %} <th>{{ key }}</th> {% endfor %} </tr> </thead> <tbody style="height: 400px; overflow-y: scroll;"> {% for key, value in rail.items %} <tr> <td>{{ key }}</td> <td> <ul> {% for index, row in value.iterrows %} <tr> {% for cell in row %} <td> {% if cell is not pandas.isnull(pandas.NaT) %} {{ cell }} {% else %} NaT {% endif %} </td> {% endfor %} </tr> {% endfor %} </ul> </td> </tr> {% endfor %} </tbody> </table> -
Where is `.objects` attribute is added to an instance namespace in django's models.Model class?
When in views.py we code something like any_model_name.objects.all() this thing brings us all the objects ever initiated from any_model_name class-model. I've just read all code in models.Model class (the one any model should inherit from) and I just can't find the place where .objects attribute appears there is nothing like that as well as .all() method attribute. My pycharm has the same opinion, it underlines .objects in red and says "Unresolved attribute reference 'objects' for class 'any_model_name'". What the magic prevents me from finding the place in django code where .objects thing appears for the first time? -
Using javascript in for loops of django
<style> .gal-wrapper{ position: relative; } .gal-img.active{ width: 100%; max-width: 30rem; position: absolute; top: 0; left: 0; right: 0; margin-inline: auto; object-fit: contain; } </style> <div class="gal-wrapper"> {% for i in img %} <figure class="gal-figure"> <img src="{{i.image.url}}" alt="" id="img{{i.id}}" class="gal-img"> <figcaption>Lorem ipsum, dolor.</figcaption> </figure> <script> const newBtn = document.querySelector(".gal-figure"); newBtn.addEventListener("click", ()=>{ const imgBtn = document.querySelector("#img{{i.id}}"); imgBtn.classList.toggle("active"); }) </script> {% endfor %} </div> I want to increase the width of the image when clicked, as I'm not much comfortable with javascript I approached this method to get what I want. But is there a better code of javascript to achieve the same result? Thank you -
Django : User models with different roles
I started to learn build class model using Django. Before I create any class model.py, I want to know whether admin user (created thru py manage.py createsuperuser) can give permission to other users. My project is building a cinema booking system and there are 4 different user types with different users. For example, as a staff, I want to create a movie session. This user story can be implemented by giving a permission to staff to create a cinema session by admin? I am not sure whether I need to create user models by : model.py on landing page OR create 'User' by py manage.py startapp User (I researched this way is called customizing user) Please let me know whether I can just build class model at model.py or customize user ..... hope my explanation is clear to you all.. -
How to display both data and image/pdf received from API in the Django template
I am receiving data and a file from REST APIs. I want to display data and the file in the same HTML template. This file could be an image(jpg/jpeg) or a pdf file. I am able to display the data in the template. However I am not able to display the pdf/image file in the template. Please help how system can detect the type of file (image or pdf) and then display the same in the template. Below is my current code : def get_invoice_details(request,myid=''): try: mark_url = urlDataApiEndpoint data = { "myId":myid } response = requests.post(url=mark_url, headers=header, json=data) inv_data = response.json() ) mark_url1 = urlFileApiEndPoint data1 = { "myid":myid, } response1 = requests.request("POST", mark_url1, headers=header, json=data) inv_img = response1.content return render(request, 'myTemplate.html',{'inv_data':inv_data} , {'inv_img':inv_img}) except KeyError: print(KeyError) myTemplate.html <div> {{inv_data.invno}} </div> <div> <iframe src="{{inv_img}}#view=fitH" title="PDF file" height="100%" width="200px" /> </div> -
Can't convert object to 'str' for 'filename'
I am working on app where react-native as a frontend and django-rest-framework as a backend. From frontend I am sending Image using formdata in backend. But I am getting this error Can't convert object to 'str' for 'filename'. frontend code const estPrice = async () => { const formData = new FormData(); console.log(Page1) formData.append("book_page1", { name: "page1.jpg", uri: Page1, type: "image/jpg", }); formData.append("book_page2", { name: "page2.jpg", uri: Page2, type: "image/jpg", }); formData.append("book_page3", { name: "page3.jpg", uri: Page3, type: "image/jpg", }); try { const result = await authAxios.post("/sell/estprice", formData); console.log(result) } catch (error) { console.log(error); } }; backend code class BookEstimatedPriceView(GenericAPIView): def post(self, request): data = request.data print(data) img1 = data.get('book_page1', ''); img2 = data.get('book_page2', ''); img3 = data.get('book_page3', ''); print(img1) def rgb_to_hex(rgb_color): hex_color = "#" for i in rgb_color: i = int(i) hex_color += ("{:02x}".format(i)) return hex_color # img1 = 'C:/Users/Aditya Pandit/Desktop/Image/Aditya@123/photo1.jpg' # img2 = 'C:/Users/Aditya Pandit/Desktop/Image/Aditya@123/photo2.jpg' # img3 = 'C:/Users/Aditya Pandit/Desktop/Image/Aditya@123/photo3.jpg' img1 = cv2.imread(img1) img2 = cv2.imread(img2) img3 = cv2.imread(img3) img1 = cv2.cvtColor(img1, cv2.COLOR_BGR2GRAY) img2 = cv2.cvtColor(img2, cv2.COLOR_BGR2GRAY) img3 = cv2.cvtColor(img3, cv2.COLOR_BGR2GRAY) n_clusters = 1 list_hex = [] img_list = [img1, img2, img3] for item in img_list: kmeans = KMeans(n_clusters) kmeans.fit(item) colors = kmeans.cluster_centers_ labels = kmeans.labels_ label_count = … -
Django celery task using selenium. WebDriverException()
I use selenium to login instagram account and getting follower information. In the homepage i have form for adding new instagram account. When i add new account, view of that page return follower and following informations of that account. I also have a celery task for updating a follower count of every instagram account in the database. And i use almost same codes in the tasks.py file. But when celery task is working error happen. Everything work perfectly in view. Application running in docker containers ERROR instagram-celery-beat-1 | [2023-04-16 16:52:17,964: INFO/MainProcess] Scheduler: Sending due task update_instagram_stats (users.tasks.update_instagram_stats) instagram-rabbitmq-1 | 2023-04-16 16:52:17.964 [info] <0.1127.0> connection <0.1127.0> (172.27.0.4:56174 -> 172.27.0.2:5672): user 'rabbitmq' authenticated and granted access to vhost '/' instagram-celery-1 | [2023-04-16 16:52:17,994: INFO/MainProcess] Task users.tasks.update_instagram_stats[ba9ece0d-18d9-44f4-96ff-32cde8f6d1b0] received instagram-rabbitmq-1 | 2023-04-16 16:52:18.005 [info] <0.1143.0> accepting AMQP connection <0.1143.0> (172.27.0.3:54132 -> 172.27.0.2:5672) instagram-rabbitmq-1 | 2023-04-16 16:52:18.010 [info] <0.1143.0> connection <0.1143.0> (172.27.0.3:54132 -> 172.27.0.2:5672): user 'rabbitmq' authenticated and granted access to vhost '/' instagram-celery-1 | [2023-04-16 16:52:18,014: WARNING/ForkPoolWorker-4] 00000000000000000000000000 instagram-celery-1 | [2023-04-16 16:52:19,832: WARNING/ForkPoolWorker-4] hhhhhhhhhhhhhhhhhhhhhhh instagram-celery-1 | [2023-04-16 16:52:22,288: ERROR/ForkPoolWorker-4] Task users.tasks.update_instagram_stats[ba9ece0d-18d9-44f4-96ff-32cde8f6d1b0] raised unexpected: WebDriverException() instagram-celery-1 | Traceback (most recent call last): instagram-celery-1 | File "/usr/local/lib/python3.8/site-packages/celery/app/trace.py", line 451, in trace_task instagram-celery-1 | R = retval … -
How to show profile picture (the picture that I chose to update) before clicking on update button in Django
I am working on a project where user can update profile information(username, bio, url, profile picture). In the user_update.html file, I used bootstrap modal for the profile picture where in the modal dialog, there will be a button "upload photo". So by clicking on this button in the dialog, user can change profile picture. User can also edit username, bio, url etc information. The problem is whenever user wants to change profile picture, it changes the profile picture and redirect to the timeline page. But there can be a case where user not only wants to update profile picture but also wants username, bio or url. In my code that I attached below, user can not update other info such as bio or url or username when they change their profile picture because the system redirects them to the timeline page before changing other information and clicking on the update button. So, what I want is to show profile picture in the user_update.html that I chose and not redirect to the timeline page before clicking on the update button. Also, if the user clicks on the cancel button, the system will redirect them to the timeline page so if user … -
How to manage message status in one to one chat while using django channels
I am trying to create a chat application Which is working fine with one consumer but I want to add message status like sent, delivered and read like a normal chat application How do we achieve that in django Should we create a new consumer which keep track of all the live users? And when we emit a message we check if a user is live in that socket it will mange status accordingly? I tried creating a second consumer which will keep track of all the connected user by storing all the users in a variable or something and when we emit a message to socket we will check if user is online or not and mange status accordingly and front end will not have to call api to change message status -
Error when deploying Django on vercel, Build Failed Command "./build_files.sh" exited with 127
I need to deploy DRF on vercel, and get this error Build Failed Command "./build_files.sh" exited with 127 error: subprocess-exited-with-error × python setup.py egg_info did not run successfully. │ exit code: 1 ╰─> [16 lines of output] /bin/sh: mysql_config: command not found /bin/sh: mariadb_config: command not found /bin/sh: mysql_config: command not found Traceback (most recent call last): File "<string>", line 2, in <module> File "<pip-setuptools-caller>", line 34, in <module> File "/tmp/pip-install-idnmrrqg/mysqlclient_b22b8ce7df8348dab3542acc3f2a7a45/setup.py", line 15, in <module> metadata, options = get_config() File "/tmp/pip-install-idnmrrqg/mysqlclient_b22b8ce7df8348dab3542acc3f2a7a45/setup_posix.py", line 70, in get_config libs = mysql_config("libs") File "/tmp/pip-install-idnmrrqg/mysqlclient_b22b8ce7df8348dab3542acc3f2a7a45/setup_posix.py", line 31, in mysql_config raise OSError("{} not found".format(_mysql_config_path)) OSError: mysql_config not found mysql_config --version mariadb_config --version mysql_config --libs [end of output] note: This error originates from a subprocess, and is likely not a problem with pip. error: metadata-generation-failed × Encountered error while generating package metadata. ./build_files.sh: line 2: python3.10: command not found Error: Command "./build_files.sh" exited with 127 Deployment completed BUILD_UTILS_SPAWN_127: Command "./build_files.sh" exited with 127 I used Python 3.10.7 and MySQL database vercel.json file: { "version": 2, "builds": [ { "src": "shopwise/wsgi.py", "use": "@vercel/python", "config": { "maxLambdaSize": "15mb", "runtime": "python3.10.7" } }, { "src": "build_files.sh", "use": "@vercel/static-build", "config": { "distDir": "staticfiles" } } ], "routes": [ { "src": "/static/(.*)", … -
Django dynamic url from calendar
The desired url should be '.../journal/year/month' Index.html <a class="nav-link active " href="{% url 'journal' {{year}} {{month}} %}">Journal</a> urls.py urlpatterns =[ path('', views.home, name='home'), path('journal/<int:year>/<str:month>/', views.journal, name='journal'), ] Views.py def home(request): year = datetime.datetime.now().year month = datetime.datetime.now().month return render(request, 'base/index.html',{ 'year': year, 'month': month, }) -
How to configure Django project + Tailwind CSS + django-compressor + MinIO
I have Django project which I configured for local development on my notebook and docker-compose for production use. I use Tailwind CSS + django-compressor and it works great locally but I don't understand how make it works with Min.io storage on product server. I found documentation for configure django-compressor with S3 storage, but it doesn't work with MinIO storage... Here is my settings.py ..... # django-compressor settings COMPRESS_ROOT = BASE_DIR / 'static' COMPRESS_ENABLED = True STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', # other finders.. 'compressor.finders.CompressorFinder', ) if not DEBUG: COMPRESS_OFFLINE = True # MINIO settings MINIO_STATIC_FILES_BUCKET = 'my-static-files-bucket' # replacement for STATIC_ROOT if not DEBUG: MINIO_ENDPOINT = 'minio:9000' MINIO_EXTERNAL_ENDPOINT = 'localhost:9000' MINIO_EXTERNAL_ENDPOINT_USE_HTTPS = False MINIO_ACCESS_KEY = os.getenv('MINIO_ROOT_USER') MINIO_SECRET_KEY = os.getenv('MINIO_ROOT_PASSWORD') MINIO_USE_HTTPS = False MINIO_BUCKET_CHECK_ON_SAVE = True # Default: True // Creates bucket if missing, then save # MINIO_CONSISTENCY_CHECK_ON_START = True COMPRESS_URL = f"{MINIO_EXTERNAL_ENDPOINT}/{MINIO_STATIC_FILES_BUCKET}/" COMPRESS_STORAGE = 'django_minio_backend.models.MinioBackendStatic' MINIO_MEDIA_FILES_BUCKET = 'my-media-files-bucket' # replacement for MEDIA_ROOT MINIO_PRIVATE_BUCKETS = [ os.getenv('MINIO_STORAGE_BUCKET'), MINIO_STATIC_FILES_BUCKET, MINIO_MEDIA_FILES_BUCKET, ] # MINIO_PRIVATE_BUCKETS.append(MINIO_STATIC_FILES_BUCKET) STATICFILES_STORAGE = 'django_minio_backend.models.MinioBackendStatic' # MINIO_PRIVATE_BUCKETS.append(MINIO_STATIC_FILES_BUCKET) DEFAULT_FILE_STORAGE = 'django_minio_backend.models.MinioBackend' MEDIA_URL = f"{MINIO_EXTERNAL_ENDPOINT}/{MINIO_MEDIA_FILES_BUCKET}/media/" else: MEDIA_URL = "/media/" -
Deployed django-vite project experiencing 403 error for all the axios calls
I am building a monolith platform of django backend and vue frontend with vite (django-vite). For authentication, I am using session authentication on django side and vue can get user info by djoser or template props (?). When in DEV mode (localhost:8000 for django server and localhost:5173 for vue), no issues of any axios calls(GET, POST, PATCH etc...) to django backend. After building the vue files with css, I placed them in Nginx reverse proxy server. All of the axios calls have been rejected with 403 errors. If I typed the api address on browser address window, DRF is working fine. Originally, I did not use corsheader library because django and vue share same origin. I installed corsheader to allow everything. Nothing works after so many tries. What could be a solution? Please help me out...