Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django/Docker/pyaudio: pip install failed beaucause of #include "portaudio.h"
I am using Django on Docker with python:3.8.3-alpine image and want to use pyaudio librairy but pip install failed because of portaudio dependency rc/pyaudio/device_api.c:9:10: fatal error: portaudio.h: No such file or directory 9 | #include "portaudio.h" | ^~~~~~~~~~~~~ I've tried many thing like trying to install portaudio before but nothing works maybe comes from my python image but trying python:3.8.3 image is too long to build How to use pyaudio in DJango/Docker project? -
App Version on Graphene GraphQL documentation
It could be a simple question, however I should specify the version I'm already working on my API-gateway. I'm using graphQL with graphene in my django project. I know in a rest-api using django rest framework, on documentation you can specify version Then, it is posible to do it on GraphQl docs? -
UserModel.objects,get(email=email) returns none
I am trying to write a custom UserModel and Email Authentication backend. When I tried to override authenticate method. user=UserModel.objects.get(email=email) returned none. Here are my models.py , authenticate.py, views.py,settings.py models.py from django.db import models from django.contrib.auth.models import AbstractBaseUser,PermissionsMixin,BaseUserManager from django.utils import timezone # Create your models here. class CustomUserManager(BaseUserManager): def _create_user(self,firstname,lastname,email,password,**extra): if not email: raise ValueError('You have not provided a valid email') email=self.normalize_email(email) if not firstname and not extra['is_superuser']: raise ValueError('You must have a first name') if not lastname and not extra['is_superuser']: raise ValueError('You must have a last name') user=self.model( email=email, firstname=firstname, lastname=lastname, **extra ) user.set_password(password) user.save(using=self._db) return user def create_user(self,firstname=None,lastname=None,email=None,password=None,**extra): extra.setdefault('is_staff',False) extra.setdefault('is_superuser',False) extra.setdefault('is_active',True) return self._create_user(firstname,lastname,email,password,**extra) def create_superuser(self,firstname='admin',lastname='',email=None,password=None,**extra): extra.setdefault('is_staff',True) extra.setdefault('is_superuser',True) extra.setdefault('is_active',True) return self._create_user(firstname,lastname,email,password,**extra) class UserModel(AbstractBaseUser,PermissionsMixin): firstname=models.CharField(max_length=100,default='') lastname=models.CharField(max_length=100,default='') email=models.EmailField(unique=True,default='',null=False,blank=False) is_active=models.BooleanField(default=True) is_superuser=models.BooleanField(default=False) is_staff=models.BooleanField(default=False) date_joined=models.DateTimeField(default=timezone.now) last_login=models.DateTimeField(blank=True,null=True) objects=CustomUserManager() USERNAME_FIELD='email' EMAIL_FIELD='email' REQUIRED_FIELDS=[] class Meta(): verbose_name='UserModel' verbose_name_plural='UserModel' def get_full_name(self): return self.firstname + self.lastname class Profile(models.Model): firstname=models.CharField(max_length=100,null=False,default='') lastname=models.CharField(max_length=100,null=False,default='') email=models.EmailField(null=False,unique=True) mobile=models.BigIntegerField() about=models.TextField(max_length=400) verified=models.BooleanField(verbose_name='verified',default=False) def __str__(self): return self.username Authenticate.py from django.contrib.auth.backends import BaseBackend from django.contrib.auth import get_user_model class EmailAuthBackend(BaseBackend): def authenticate(self, response, email=None, password=None, **kwargs): UserModel = get_user_model() try: user = UserModel.objects.get(email=email) except UserModel.DoesNotExist: return None if user.check_password(password): return user else: return None def get_user(self,user_id): try: return get_user_model().objects.get(pk=user_id) except get_user_model().DoesNotExist: return None Views.py from django.shortcuts import render,redirect from .models … -
Django-rest-framework works but looks ugly
So I´m building an API and I launched it in an online server. When I host the API in my localhost, it looks just fine but when I access it through the online server, it displays the information but kinda in a pure HTML way. It works fine but it kinda bothers me that it looks like that. Do I need to change something in my settings or has anyone else experienced something similar? Here's how it looks: Error image -
Connection between Frontend and Backend (on Django) [closed]
I am currently working on a project that uses Vue.js with TypeScript as the frontend and Django as the backend. Our backend is built on Django templates and we are trying to decide on the best way to handle communication between the frontend and backend. What would be the best approach for handling this communication? We are considering options such as using Ajax, Websockets, Axios, or other technologies. Can you provide any insights or suggestions on what approach we should take and why? -
Unable to delete an object by sending a DELETE request to my API
I've created an API using Django-REST-Framework and This is my backend. urls.py urlpatterns = [ path('getFavourite/', views.getFavourites), path('addFavourite/', views.addFavourites), path('deleteFavourite', views.deleteFavourites), ] and this views.py @api_view(['GET']) def getFavourites(request): favourites=Favorite.objects.all() serializer=FavouriteSerializer(favourites , many=True) return Response(serializer.data) @api_view(['DELETE']) def deleteFavourites(request): name=request.data['name'] favorite=Favorite.objects.get(name=name) favorite.delete() result="Your favorite has been deleted" return Response({"result":result}) And this is my frontend: let newContent=document.getElementById('favorite'); fetch("http://127.0.0.1:8000/getFavourite/") .then(response => response.json()) .then(data => { for(i=0; i<data.length; i++){ newContent.innerHTML += `<div class="container"> <div style=""> I do ${data[i].name} every ${data[i].timeOfDoing} days <div onclick="favDelete('${data[i].name}')" class="deletion-sign">&#9747;</div> </div> </div>` } }) function favDelete(name){ console.log(name) fetch("http://127.0.0.1:8000/deleteFavourite/" , { method:"DELETE", headers: { 'Content-Type' : 'application/json' }, body:JSON.stringify({"name":name}) }) .then(response => response.json()) .then(data => console.log(data.result) ) } Trying this code I saw the following errors in my console: DELETE http://127.0.0.1:8000/deleteFavourite/ 404 (Not Found) Uncaught (in promise) SyntaxError: Unexpected token '<', "<!DOCTYPE "... is not valid JSON Promise.then (async) I successfully managed to add objects using POST request but failed to delete objects using DELETE method. Can anyone kindly tell me have I forgotten to do certain thing or done something wrong? -
In Django I want to fetch product info from database to Html template I tried for loop but didn work
While making E-commerce website i Create Datbase model and fetch product to html page but when i created For loop for fetching product it doesn't work here is my code for View.py def index(request): produts = Product.objects.all() n = len(produts) n_slide = n//4 + ceil((n/4)-(n//4)) parms = {'no_of_slides':n_slide,'range':range(1,n_slide),'produt':produts} return render(request,"shop/index.html",parms) This is My models.py class Product(models.Model): product_id = models.AutoField product_name = models.CharField(max_length=30) product_category = models.CharField(max_length=50,default="") product_subcategory = models.CharField(max_length=50,default="") product_desc = models.CharField(max_length= 80) product_price = models.IntegerField(default = 0) prodct_pub_date = models.DateField() product_image = models.ImageField(upload_to="shop/images",default="") def __str__(self): return self.product_name This is my urls.py 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('shop/',include("shop.urls")), ] + static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT) This is my html code for index page {% block body %} {% load static %} <div class="container"> <div id="demo" class="carousel slide my-3" data-ride="carousel"> <ul class="carousel-indicators"> <li data-target="#demo" data-slide-to="0" class="active"></li> {% for i in range %} <li data-target="#demo" data-slide-to="{{i}}" ></li> {% endfor %} </ul> <!--Slideshow starts here --> <div class="container carousel-inner no-padding"> <div class="carousel-item active"> <div class="col-xs-3 col-sm-3 col-md-3"> <div class="card" style="width: 18rem;"> <img src='{% static "shop/h2.jpeg" %}' class="card-img-top" alt="..."> <div class="card-body"> <h5 class="card-title">{{produt.0.product_name}}</h5> <p class="card-text">{{produt.0.product_desc}}</p> <a href="#" class="btn btn-primary">Go somewhere</a> … -
Validation of DRF fields
i have two models I add a mask to one model, where each letter corresponds to the value A, to the second I will add a serial number and I need this field to be checked against this mask for matching values models.py class EquipmentType(models.Model): name = models.CharField(max_length=255) mask = models.CharField(max_length=100) class Equipment(models.Model): type = models.ForeignKey('EquipmentType', on_delete=models.CASCADE) sn = models.CharField(max_length=255, unique=True) note = models.CharField(max_length=255) def clean(self): mask = self.type regex = '' for char in mask: if char == 'N': regex += 'd' elif char == 'A': regex += '[A-Z]' elif char == 'a': regex += '[a-z]' elif char == 'X': regex += '[A-Z0-9]' elif char == 'Z': regex += '[-_@]' if not re.match(regex, self.sn): raise ValidationError({'serial_number': 'Invalid serial number'}) class Meta: unique_together = ('sn', 'type') serializers.py class EquipmentSerializer(serializers.ModelSerializer): class Meta: model = Equipment fields = '__all__' def validate_serial_number(self, value): mask = self.instance.type.mask regex = '' for char in mask: if char == 'N': regex += 'd' elif char == 'A': regex += '[A-Z]' elif char == 'a': regex += '[a-z]' elif char == 'X': regex += '[A-Z0-9]' elif char == 'Z': regex += '[-_@]' for num in value: if not re.match(regex, num): raise serializers.ValidationError('Invalid serial number') return value class … -
Syncing postgres instances with mongo db in a Django project
Please i am working on a Django project that uses postgres as it primary database. Now I have been tasked with syncing the postgres instances with mongo db but I don’t know how to go about it. I cant find any real resources out there. The idea is that the data in the mongo db should always match what’s in the postgres db. If a row in the postgres db is deleted, created or updated, it should sync to the mongo db. Chat gpt recommended pymongo and mongo-connector to do the syncing but nth seems to be working I pip installed pymongo and mongo-connector, then I was told to create a config.yml in my project root directory, fill up the config file with the necessary configurations and then run mongo-connector -m config.yml. But I get an error -
Overriding viewflow views to return JSON
Probably something basic, but cannot seem to figure it out. I am trying to implement a custom UI for viewflow where the various tasks are displayed as modals. I have managed to get the initial start view to display in a modal and to use AJAX to submit the form. I would like to get all the other process task views to do the same. The following is my attempt based on this answer however, the overridden view AJAXDetailTaskView(DetailTaskView) does not seem to get called and I am wondering where I am going wrong. In this specific instance I am trying to modify the start detail view (which I presume will be the same principle for all the other views) flows.py class AssetFlow(Flow): process_class = models.AssetProccess task_class = models.AssetTask lock_impl = select_for_update_lock start = ( flow.Start( views.StartView) .Permission(auto_create=True) .Next(this.co_approval) ) co_approval = ( flow.View( views.AssetView ) .Next(this.finance_tc) ) ... views.py from viewflow.flow.views.detail import DetailTaskView class AJAXDetailTaskView(DetailTaskView): def render_to_response(self, context, **response_kwargs): if self.request.META.get('HTTP_X_REQUESTED_WITH') == 'XMLHttpRequest': print('An AJAX request') return JsonResponse('Success', safe=False, **response_kwargs) else: print('Not an AJAZ request') return super(AJAXDetailTaskView, self).render_to_response(context, **response_kwargs) class StartView(StartFlowMixin, generic.UpdateView, flow.View): model = models.Item form_class = forms.AssetForm data = dict() detail_view_class = AJAXDetailTaskView def get_object(self): return self.activation.process.asset … -
Django Template Form rendering Dropdown List does not get populated
Having a Template view which gets rendered with the form processor; all values get filled perfectly int the respective fields except the Dropdowns. On all Dropdown-Lists the selected Value is placed on the first item of the Dropdown, not on the one which is in the Database. How it looks, when rendered: <select name="catmedia" class="form-control" placeholder="catmedia" id="id_catmedia"> <option value="" selected="">None</option> <option value="film">Film</option> <option value="serie">Serie</option> <option value="doku">Doku</option> the code from above should look like: <select name="catmedia" class="form-control" placeholder="catmedia" id="id_catmedia"> <option value="" >None</option> <option value="film">Film</option> <option value="serie" selected>Serie</option> <option value="doku">Doku</option> How can this be fixed? The selected part should be inserted at the right place, it does not yet. Why is it not populated correctly? What did I overlook? Here are the related code parts. View: class mForm(ModelForm): def __init__(self, *args, **kwargs): super(mForm, self).__init__(*args, **kwargs) for field in iter(self.fields): self.fields[field].widget.attrs.update({ 'class': 'form-control', 'placeholder': field, }) class Meta: model = Mediadb Model: catmedia_ = ( ('','None'), ('film','Film'), ('serie','Serie'), ('doku','Doku'), ) catmedia = models.CharField(max_length=34,blank=True,choices=catmedia_, default='') Template: {% for field in form %} <div class="form-group"> <label class="col-sm-3 control-label" for="id_{{ field.name }}">{{ field.label }}</label> <div class="col-sm-9"> {{ field }} </div> </div> {% endfor %} -
django Request aborted Forbidden (CSRF token missing.) channels websockets
I'm new to django and I'm trying to get a realtime chat app using channels websockets up and running. I've tried building the chat page myself as well as copy pasting the relevant chat code from the tutorial itself. Still I get "CSRF verification failed. Request aborted." and "Forbidden (CSRF token missing.):" from inside terminal. Things I've tried: adding {% csrf_token %} above the form - then messages aren't added to the list of messages but the page reloads and the "Forbidden (CSRF token missing.):" disappears. adding @csrf_protect in chat/views.py. using channels version 3.0.5. That's the version in the tutorial. I've tried rebuilding the database and deleting all migration files and restoring them. Doesn't change anything (just trying different angles) chat/templates/chat/chat.html {% extends 'core/base.html' %} {% block title %} {{ chat.name }} | {% endblock %} {% block content %} <div class="p-10 lg:p-20 text-center"> <h1 class="text-3xl lg:text-6xl text-white">{{ chat.name }}</h1> </div> <!-- div for actual messages--> <div class="lg:w-2/4 mt-6 mx-4 lg:mx-auto p-4 bg-white rounded-xl"> <div class="chat-messages space-y-3" id="chat-messages"> <div class="p-4 bg-gray-200 rounded-xl"> <p class="font-semibold">Username</p> <p>This is the message for the user</p> </div> <div class="p-4 bg-gray-200 rounded-xl"> <p class="font-semibold">Username</p> <p>This is the message for the user</p> </div> <div class="p-4 bg-gray-200 rounded-xl"> … -
Getting a random element in a QuerySet - Python Django
I have the following query in Django: vms = VM.objects.filter(vmtype=vmtype, status__in=['I', 'R']) .annotate(num_jobs=Count('job')) .order_by('num_jobs') it will return a QuerySet of vms based on the number of jobs running in each VM. Please notice that num_jobs is not a field in the VM object (model). This would return a query set such as the number of jobs is [0, 0, 1, 2, 2, 3, 4, 4, 5]. Doing vms.first() will for sure return me the vm with least number of jobs, but it could not be the only. From all the vms with the least number of jobs, I want to return a random between them, not just the first. How can I accomplish that? -
Django StreamingHttpResponse Google App Engine Flexible
We have a Django application for chatting. UI: Built in HTML, CSS, JS Backend: ChatGPT API integrated in Python using below option to get word to word responses & the rest uses Django standard files stream = True The flow is as follows: An XMLHttpRequest is triggered on a button click from JavaScript which further calls an endpoint in Django which returns a word to word response StreamingHttpResponse from ChatGPT, the UI is also updated in parallel with word to word response. The word to word response works fine on localhost. Problem: When we try to host it in Google App Engine Flexible or Standard it waits for the whole response rather than showing it word to word, can anyone help me out with this ? -
How to stop adding duplicate records after every refresh of the page?
I created a registration form, where I accept the name, gender, address, dob, and state. after submitting it, it gives the message that the record is added and shows an empty form, but if I refresh the page, it adds a duplicate record. a number of time I refresh the page the number of time same record is added this happen on after user registration confirmation. I want to add record only when i click on submit button. Please give me the solution using django I want to add record only when I click on submit button or add record button of form, but It creating a record after first record added and success message display if i refresh here multiple times then multiple same records will be added to the database Code: views.py def std_registration_view(request,username): if 'UserIsActive' in request.session: form=Student_Registration if request.method=="POST": form=Student_Registration(request.POST, request.FILES) if form.is_valid(): form.save() name=form.cleaned_data['full_name'] messages.success(request,"Record is added for "+name) form=Student_Registration return render(request,'std_registration/registration.html',{"username":username,'form':form,'msg':'Record added'}) return render(request,'std_registration/registration.html',{"username":username,'form':form}) return redirect('login') registrations.html {% extends "login/base.html"%} {% block title%} <title> Registration </title> {%endblock%} {% block content %} <div class="container"> <div class="row justify-content-center"> <h3 style="background-color: rgb(245, 250, 255,0.5);text-decoration: wavy;text-align: center;">Welcome {{username}}</h3> <div class="col-md-8"> <div class="card" style="opacity: 0.9;"> <div class="card-header">Student Registration:{%for msg … -
Allow both authenticated and anonymous user access to a view
I have the following in settings.py: REST_FRAMEWORK = { 'DATETIME_FORMAT': "%c", 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.TokenAuthentication', ], } I am trying to have a view that does different things for authenticated and anonymous (guest) users: class CourseListView(generics.ListAPIView): permission_classes = [AllowAny, ] def list(self, request, format=None): user = request.user realUserFlag = not user.is_anonymous ... This works as expected for authenticated users, but returns Unauthorized (401) error for anonymous ones. What am I missing? P.S. A variation on this topic with decorators appears here, but does not seem to have a good answer. -
Django ifchanged template tag rendering when it should not
I am trying to render out a table there are a bunch of djangos {% ifchanged %} conditions that should only render out the value if changes all of them work as intended except the one where I check for whether or not the code_product_type_id has changed but it renders it out anyway. for eg. the first 3 iterations, the code_product_type_id = 100 but it still renders as if it changed. it is unqiue, its the key of the dictionary and does not change unless you move to the next key in the dict at which point it should render out. Any suggestions as to why this might be happening? I've tried using product.product_type in the ifchanged tag and still gives the same result. I've tried creating extra context with a with clause just after the outer most for loop, still the same result. All the bold text in the image below is what is rendered out and the integers are the code_product_type_id to illustrate the the value is not changing Template {% for code_product_type_id, product_types in report_rows.items %} {% for code_product_id, products in product_types.items %} {% for code_company_id, product in products.items %} {# FIXME: I am not rendering out … -
django model-translation, can't filter on multilingual
I'm trying to implement multi-language on my site using django-modeltranslation, but I can't filter product by category when switched to other languages, I'm using Python 3.10.6, Django 4.2, django-modeltranslation 0.18.9 my code: model.py class Category(models.Model): name = models.CharField(max_length=100) created_at = models.DateField(default=timezone.now) class Meta: verbose_name_plural = "Categories" def __str__(self): return self.name class Course(models.Model): name = models.CharField(max_length=100) categories = models.ForeignKey(Category, blank=True, null=True, on_delete=models.CASCADE) class Meta: verbose_name_plural = "Categories" def __str__(self): return self.name views.py def CourseListView(request): qs = Course.objects.all() categories = Category.objects.all() category = request.GET.get('category') if is_valid_queryparam(category) and category != 'All categories': qs = qs.filter(categories__name=category) qs = qs.filter(Q(categories__name_en='category') | Q(categories__name_fr='category')) context = { 'queryset': qs, 'categories': categories, } urls.py path('', CourseListView, name='course-list'), course_list.htnl <form method="GET" action="."> <select onchange="this.form.submit()" id="category" name="category"> <option selected>{% translate "All categories" %}</option> {% for cat in categories %} <option value="{{ cat }}">{{ cat }}</option> {% endfor %} </select> </form> I have tried to use this code it doesn't work, if is_valid_queryparam(category) and category != 'All categories': qs = qs.filter(Q(categories__name_en='category') | Q(categories__name_fr='category')) However this one do work but on default language only: if is_valid_queryparam(category) and category != 'All categories': qs = qs.filter(categories__name=category) -
Radio grid working, checkbox grid raises a validation error
This is a modified version of django-radiogrid which I'm using to create a radio / checkbox grid. The radio version is working fine but the checkbox raises a validation error. forms.py from django import forms from django.forms import ( CheckboxSelectMultiple, MultiValueField, MultiWidget, RadioSelect, ) class GridField(MultiValueField): def compress(self, data_list): return "" if data_list is None else ",".join(data_list) class RadioGridWidget(RadioSelect): template_name = 'grid-widget.html' class CheckboxGridWidget(CheckboxSelectMultiple): template_name = 'grid-widget.html' class GridMultiWidget(MultiWidget): template_name = 'grid-multi-widget.html' def __init__(self, rows, columns, widgets, attrs=None): self.rows = rows self.columns = columns super(GridMultiWidget, self).__init__(widgets, attrs) def get_context(self, name, value, attrs): context = super(GridMultiWidget, self).get_context(name, value, attrs) widgets = context['widget']['subwidgets'] return { 'rows': [(item[1], widgets[i]) for i, item in enumerate(self.rows)], 'columns': self.columns, 'attrs': self.attrs, } def decompress(self, value): if value: return value.split(',') return [None for _ in self.rows] class MyForm(forms.Form): my_grid = GridField(fields=[], required=False) urls.py from django.urls import path from app import views urlpatterns = [path('', views.index, name='index')] views.py from django.forms import ChoiceField from django.shortcuts import render from app.forms import CheckboxGridWidget, GridMultiWidget, MyForm, RadioGridWidget def index(request): rows = [[f'row {i}', f'row {i}'] for i in range(5)] columns = [[f'col {i}', f'col {i}'] for i in range(5)] if request.method == 'POST': form = MyForm(request.POST) else: form = MyForm() choices = … -
Django Media-File Download-Link opening preview
I have a Django project in which I use wagtail. Now on one page, the user can upload an image and download it later. For the download link, I used following html: <a href="{{file.document.url}}" class="text-indigo-600 hover:text-indigo-900" download target="_blank"> <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-download text-black" viewBox="0 0 16 16"> <path d="M.5 9.9a.5.5 0 0 1 .5.5v2.5a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1v-2.5a.5.5 0 0 1 1 0v2.5a2 2 0 0 1-2 2H2a2 2 0 0 1-2-2v-2.5a.5.5 0 0 1 .5-.5z"/> <path d="M7.646 11.854a.5.5 0 0 0 .708 0l3-3a.5.5 0 0 0-.708-.708L8.5 10.293V1.5a.5.5 0 0 0-1 0v8.793L5.354 8.146a.5.5 0 1 0-.708.708l3 3z"/> </svg> </a> On my local device when running with python manage.py runserver, this code works fine and every image gets downloaded. On my Environment, it doesn't work that well. Every image and pdf is opened in a preview first, from where the user has to manually safe the image. What did I do wrong? -
When I try to use CMD in my Windows PC (after the windows 11 update) It stooped working
I can only see the program for a bit and it automatically closes itself. I can't do any of my work specially my django projects. I tried using the Powershell but it's not helping much -
Django ORM Q and Async
I'm using django with Telegram Bot If i need to make ORM Query, i can do it like that all_offers = await sync_to_async(Offers.objects.filter, thread_sensitive=True)( status = True, ) but not i need to make more difficult query with Q function like that all_offers = await sync_to_async(Offers.objects.filter, thread_sensitive=True)( status = True, Q(some_field="1")|Q(another_field=2), ) SyntaxError: positional argument follows keyword argument How it can be solved? -
Django: change project name ModuleNotFoundError
After changing the name of the project_config file i get this error while trying to makemigration or in general do anything related to python manage.py : (.venv) (base) PS C:\Users\Pablo\Database> python manage.py migrate Traceback (most recent call last): File "C:\Users\Pablo\Database\.venv\lib\site-packages\django\core\management\base.py", line 402, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\Pablo\Database\.venv\lib\site-packages\django\core\management\base.py", line 448, in execute output = self.handle(*args, **options) File "C:\Users\Pablo\Database\.venv\lib\site-packages\django\core\management\base.py", line 93, in wrapped saved_locale = translation.get_language() File "C:\Users\Pablo\Database\.venv\lib\site-packages\django\utils\translation\__init__.py", line 210, in get_language return _trans.get_language() File "C:\Users\Pablo\Database\.venv\lib\site-packages\django\utils\translation\__init__.py", line 65, in __getattr__ if settings.USE_I18N: File "C:\Users\Pablo\Database\.venv\lib\site-packages\django\conf\__init__.py", line 92, in __getattr__ self._setup(name) File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 992, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 1004, in _find_and_load_unlocked ModuleNotFoundError: No module named 'postgresTest' postgresTest was the name of the project_config file, it is nowhere in my directory,i have gone through every .pyc file and changed every reference in settings, wsgi , urls, etc. The database is hosted in amazon rds and deployed in heroku. Can someone help me with this? I attempted to find any reference in a settings module name … -
If a Django app only works with Gunicorn's `--preload` option, does it mean that there is something wrong with the app?
Inherited an outdated Django app (Django 2.2) running in "production", served by Gunicorn without the --preload option. New to Python and the Django ecosystem, but was able to update everything to latest (Django 4.2, Gunicorn 20.1.0) without ever having to touch the codebase (apart from settings.py, but even there the changes were minimal). django manage.py runserver works, so tried Gunicorn next. The app gets served, and when I try to log in, the credentials are accepted, but then redirected to the login page. The next attempts loads some of the initial page that a user should see, but there is still the login request. --log-level 'debug' shows no issues, no errors from the app (at least what I could find). --preload solves this issue right away, and now I know that this option is ok to be used in production. Nonetheless, given my inexperience, I wonder if this is normal or something that I should definitely address once moving to actually working on the app itself. Decided to post this here and not on Unix & Linux, ServerFault, or SuperUser, because even though the question involves Gunicorn and its terminal usage, this question is about Django really. -
Django read after update is not getting the latest value
I am working on a Django project that uses MariaDB as the database. The project has a state serialized to the database and it is updated frequently via REST API posting. I use a serializer to handle the state update by calling update(instance, validated_data). Then I send a WebSocket message to the browser client using Django Channels. The browser client listens for the WebSocket message and requests the latest state using get. I run Django with Uvicorn and 6 worker threads in production. However, I encounter a problem where the client sometimes gets an old state, the state prior to the last update. This causes the client to display incorrect information. I suspect this is related to the database isolation level being READ COMMITTED. Would changing it to SERIALIZABLE solve the issue? Or can I set different isolation levels for specific tables that need more strict locking? Any help or advice would be appreciated!