Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to implement feature flags efficiently for a backend?
Doesn't matter it is a web app or api, we need feature flags. If we don't need separate flags per user groups, the same flags works on all site. We don't update these flags too frequently. In this situation there are some options to store this flags. I believe the effects are similar for any framework such as Django, NodeJs, Rails, Spring. Database: We can store the flags in database, but the drawback it that, each time we access to a flag, it connects to database. Database + Application Constants: Application can read and cache the flags at the boot time. The drawback is that when we update a setting we have to restart all processes. Redis: Faster than database but the management is more hassle. SaaS Service: The slowest one because it works with connections to outside. Environment variables: Works native but updating them is not comfortable process, plus requires restart. I am curious if someone uses a way better than those. Or a technique removes the drawback. Thanks. I am looking the best way to implementing feature flags. -
How to add another dictionary entry in a nested python dictionary
I would like to make a dictionary in the dictionary. I have this code dictionary = {} for g in genre: total = 0 products = Product.objects.filter(genre=g) for product in products: total += product.popularity dictionary[g.category] = {g.name: total} I would like it to look like this, for example {'book': {'Horror':0, 'Comedy:0}, 'cd': {'Disco': 0, 'Rap': 0}} -
Why is mypy not inferring Django CharField choices as type with django-stubs?
I have a Django model with a field that is a models.CharField with choices: from django.db import models class MyChoice(models.TextChoices): FOO = "foo", _("foo") BAR = "bar", _("bar") BAZ = "baz", _("baz") class MyModel(models.Model): my_field = models.CharField(choices=MyChoice.choices, max_length=64) Then, if I use this choice field in a function that has it as a typed parameter, mypy catches it as an error. def use_choice(choice: MyChoice) -> None: pass def call_use_choice(model: MyModel) -> None: use_choice(model.my_field) # error: Argument 1 to "use_choice" has incompatible type "str"; expected "MyChoice" [arg-type] My configuration is as follows: # pyproject.toml [tool.poetry.dependencies] python = ">=3.10,<3.11" Django = "^3.2.8" [tool.poetry.dependencies] mypy = "^1.1.1" django-stubs = "^1.16.0" # mypy.ini [mypy] python_version = 3.10 ignore_missing_imports = True plugins = mypy_django_plugin.main [mypy.plugins.django-stubs] django_settings_module = "config.settings" Why is this happening? -
Looking for alternatives to Celery for running background tasks
I'm building an application using Django Rest Framework. One of the requirements is to initiate/maintain background tasks that will continuously monitor some cloud instances and update the database. For this, I used Celery in the way of creating Celery tasks via DRF code. However, it didn't help on long run since Celery was not able to scale up and became unstable. So, please suggest any alternate software/ methodology to accomplish the task. Thanks -
Migrating string column into array column django postgresql
In my models I have old field tag and created new one tags. tag = models.CharField(max_length=64, null=True, default=None, db_index=True, choices=[(tag, tag) for tag in TAGS]) tags = ArrayField(models.CharField(max_length=64, choices=[(tag, tag) for tag in TAGS]), db_index=True, null=True). Column tag have only strings, for example 'APPLE' or 'PEAR'. I want that column tags to be an array of one string after migrations. In my migrations after creating new field and before deleting old one I want to transfer data from column tag into tags. I tried using raw sql: cursor.execute("UPDATE form_builder_formfield SET tags = ARRAY[tag] WHERE tag IS NOT NULL") but this is not working. I recived errors: django.db.utils.DataError: malformed array literal: "["APPLE"]" "[" must introduce explicitly-specified array dimensions. I also tried using django queryset but I always end with this errors above. Any ideas how to do it? -
Problem with save data from popup form in Django
I have a problem with save data from popup form to sqlite database via django. My part code : dash.html: BUTTON FOR POPUP FORM <div class="card-footer clearfix"> <a href="" type="button" class="btn btn-primary float-right" data-toggle="modal" data-target="#newItem"><i class="fas fa-plus"></i> Add item</a> </div> POPUP CODE <div class="modal-content"> <div class="card card-success"> <div class="card-header"> <h3 class="card-title"><b>Add Item</b></h3> </div> <div class="card-body"> <form action="" method="post"> {% csrf_token %} <div class="row"> <div class="col-sm-6"> <div class="form-group"> <label> Item Name:</label> <input class="form-control form-control-lg" name="item_name" type="text" placeholder="Item name"> </div> </div> <div class="col-sm-6"> <!-- text input --> <div class="form-group"> <label> Item size:</label> <input class="form-control form-control-lg" name="item_size"type="text" placeholder="Item size"> </div> </div> <!-- /.card-body --> <div class="modal-footer"> <input type="submit" class="btn btn-default" value="submit"></input> <button type="button" class="btn btn-default" data-dismiss="modal">Close</button> </div> </div> </div> popup Code is a part of dash.html models.py : class itemModel(models.Model): name = models.CharField(max_length=50) size = models.CharField(max_length=20) def __str__(self): return self.name I use SQLITE3 as a default database. forms.py: from django import forms from .models import itemModel class itemForm(forms.ModelForm): class Meta: model = itemModel fields = ["item_name", "item_size"] views.py: from django.shortcuts import redirect from dashboard.models import addItem def addItem(request): if request.method == "POST": name = request.POST['item_name'] size = request.POST['item_size'] itemModel.objects.create(Name=name, size=size) return redirect('dashboard') urls.py: from django.urls import path from . import views urlpatterns = … -
updating a django webpage as a result of information from a websocket from an external script
i have a django project and an external script. ive recently learened websockets and i am able to send info from my external script to my django consumers.py (which handles the websockets) however im struggling to update the django page based upon the info being passed from my external script. my original consumers.py in my django project class MiConsumer(WebsocketConsumer): def connect(self): self.accept() self.send(text_data = json.dumps({ 'type' : 'connection_established', 'message': 'you are now connected!' })) async def receive(self, text_data=None, bytes_data=None): message = json.loads(text_data) print(message) if "ogilvie = free" in message: print("ogilvie = free") ogilvie_free = True elif "ogilvie = busy" in message: print("ogilvie = busy") ogilvie_free = False message = json.dumps({'message': message}) await self.send(message) at first i was looking for possibilities to directly change the webpage from here, but started to think that was impossible. so then i tried to have consumers.py pass on information to my html, after the consumers.py had recieved information from my external script. the js in my html is below, this does connect to my django consumers.py file. but never recieves anything more than the initial connection message from the connect function const socket = new WebSocket('ws://localhost:8000/ws/'); socket.addEventListener('message', function(event) { console.log("good socket") const message = JSON.parse(event.data).message;//.toString(); … -
Django Form Displaying Form Error on GET Method
I have been using django web framework for some time now, I would love to write a custom password change form without using the default provided by django or third-party packages. I have tried following a similar pattern used in django SetPasswordForm and PasswordChangeForm My Current Implementation project/app/forms.py class ChangePasswordForm(forms.Form): old_password = forms.CharField(max_length=50, ) password1 = forms.CharField(max_length=50, ) password2 = forms.CharField(max_length=50, ) def __init__(self, user, *args, **kwargs): self.user = user super().__init__(*args, **kwargs) def clean(self): cleaned_data = super().clean() old_password = cleaned_data.get('old_password') password1 = cleaned_data.get('password1') password2 = cleaned_data.get('password2') # Validate new user password if password1 and password2 and old_password: if not self.user.check_password(old_password): raise ValidationError("Invalid old password, please enter your current password") elif password1 != password2: raise ValidationError("Password mismatch, please re-type same password") password_validation.validate_password(password1, self.user) return cleaned_data def save(self, commit=True): new_password = self.cleaned_data.get('password2') self.user.set_password(new_password) if commit: self.user.save() return self.user project/app/views.py class ChangePasswordView(LoginRequiredMixin, View): def get(self, request, *args, **kwargs): form = ChangePasswordForm(request.user, request.POST) context = { 'form': form, } return render(request, 'auth/change_password.html', context) def post(self, request, *args, **kwargs): form = ChangePasswordForm(request.user, request.POST) if form.is_valid(): user = form.save() # log user out of all active sessions update_session_auth_hash(request, user) messages.success(request, "Password updated successfully") return redirect('custom_redirect') return redirect('custom_redirect')) HTML Template Rendering <form class="card-style mb-30" action="{% url 'account_change_password' … -
Django Bootstrap Search Bar on Navigation Bar
I have made a search bar on the navigation bar. However, when I search it, it has no response. I have made a separated file for my navigation bar - navbar.html. navbar.html <nav> <ul> {% if user.is_authenticated %} <form class="form-inline" action="{% url 'search_journal' %}" method="GET"> <input class="form-control mr-sm-2" type="search" name="q" placeholder="Search" aria-label="Search"> <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button> </form> <li><a href="{% url 'journal_list' %}">HOME</a></li> <li><a href="{% url 'journal_list_favourite' %}">FAVORITE</a></li> <li><a href="{% url 'logout' %}">LOGOUT</a></li> <li class="profile"> <div class="profile-img-container"> <a href="{% url 'profile' %}"><img id="profile-img" src="{{ user.profile.image.url }}" alt="Profile Picture"></a> </div> <li class="nav-item"> <a class="nav-link active" href="#">Hi {{user.username}}</a> </li> {% else %} <li class="nav-item"> <a>Please Login!</a> </li> {% endif %} </ul> </nav> views.py @login_required def search_journal(request): if request.method == 'GET': query= request.GET.get('q') submitbutton= request.GET.get('submit') if query is not None: lookups= Q(title__icontains=query) | Q(content__icontains=query) results= Journal.objects.filter(lookups).distinct() context={'results': results, 'submitbutton': submitbutton} return render(request, 'audioJournaling/search_journal.html', context) else: return render(request, 'audioJournaling/search_journal.html') else: return render(request, 'audioJournaling/search_journal.html') search_journal.html {% extends "base.html" %} {% block content %} <h1>Search Page</h1> <br/> <!-- <form action="{% url 'search_journal' %}" method="GET" value="{{request.GET.q}}"> Search <input type="text" name="q" value="{{request.GET.q}}" placeholder="Search posts"/> <input type="submit" name="submit" value="Search"/> </form> --> {% if submitbutton == 'Search' and request.GET.q != '' %} {% if results %} <h1>Results for <b>{{ … -
GDAL reprojection error: in method 'Geometry_Transform', argument 2 of type 'OSRCoordinateTransformationShadow *' error in Cartoview and Terria JS
While uploading layers in cartoview, these are uploaded but there is the error message in the console: GDAL reprojection error: in method 'Geometry_Transform', argument 2 of type 'OSRCoordinateTransformationShadow *' which is why in Terria JS the map is not shown. i.e. the integration is not complete. Can someone kindly help identify the issue? Thanks in advance. -
Count elements from ForeignKey with condition
I have a view, which returns all Company objects. In my HTML file I want to count all Ads which are online (online == True) and belong to the Company. In my file companySearch.html all Ads are counted, even those which have online == False. I am looking for a way which should have the logic of: {{ o.ad_set.count where o.ad.online == True }} views.py def companySearch(request): obj = Company.objects.all() paginator = Paginator(obj, PAGINATION_NUMBER) page_number = request.POST.get('page') page_obj = paginator.get_page(page_number) context = {'obj': page_obj} return render(request, 'core/companySearch.html', context) models.py class Company(models.Model): id = models.BigAutoField(primary_key=True) name = models.CharField(max_length=64, blank=False, null=False, unique=True) class Ad(models.Model): id = models.BigAutoField(primary_key=True) name = models.CharField(max_length=128, blank=False, null=False) company = models.ForeignKey(Company, on_delete=models.CASCADE) online = models.BooleanField(default=False) companySearch.html {% for o in obj %} <div>{{ o.ad_set.count }} open position{{ o.ad_set.count|pluralize:',s' }}</div> {% endfor %} -
When should "_set" be added to a Django query?
In the following query, the reference to tweet has a "_set" in prefetch, but not in annotate. The relationship from user to tweet is many-to-one in both cases as well." How do I determine if "_set" should be added? class User(models.Model) name = models.CharField(max_length=50) class Tweet(models.Model) user = models.ForeignKey("User") favorite = models.IntegerField(default=0) User.objects.prefetch_related( Prefetch( "tweet_set", query_set=Tweet.objects.order_by('favorite') ).annotate(most_favorites=Max("tweet__favorite")) # Why not "tweet_set__favorite"? -
Could not parse the remainder: '${id}' from '${id}'
Hi there I am working on a blogpage using django rest framework api system. I am trying to set the url id using javascript DOM but don't know where it all go wrong my javascript code: fetch('http://127.0.0.1:8000/getdata') .then(response => response.json()) .then(data => { ul = document.getElementById('my-list'); ul.innerHTML = ''; data.forEach(element => { const list = document.createElement('div') id = element.id list.innerHTML = ` <h1 class='text-uppercase' >${element.title}</h1> <hr> <h5>@${element.author}</h5> <div>${element.content} </div> <button class="btn btn-danger" onclick="deleteitem(${element.id})">delete</button> <a href="{% url 'editpost' ${id} %}" class="btn btn-info"></a> `; list.classList.add('card'); list.classList.add('card-body'); list.classList.add('mb-2'); ul.appendChild(list); console.log(element.title) }); }) if you need more informations please ask I have try it to use {{}} and {} and just raw id it didn't work -
TemplateSyntaxError at / Could not parse the remainder: 'product.tk' from ''main-product-detail'product.tk'
I'm stuck on a problem that I solve most of the time but now, when I place the links in my home.html files for the product detail page, an error appears: TemplateSyntaxError at / Impossible to analyze the rest: 'product.tk' of ''main-product-detail'product.tk' I checked everywhere and modified things but nothing changed. take a look at my code and tell me where is the error views from django.shortcuts import render, redirect,get_object_or_404 from django.contrib.postgres.search import SearchVector from django.db.models import Q from main.models import Cart from command.models import * from notification.models import * from user.models import * from rest_framework.views import APIView from rest_framework.response import Response from rest_framework.viewsets import ModelViewSet from rest_framework.viewsets import ReadOnlyModelViewSet from main.serializers import ProductSerializer # CategorySerializer from .utils import get_cart_data import validators from amazon import scrape, scrape_search def home(request): products = Product.objects.all() product_recommadeds=Product.objects.all().order_by('-date') # new_products= Product.objects.filter(date='') cart_id = request.COOKIES.get('cart_id') cart = None cart_count = 0 if cart_id: try: cart = Cart.objects.get(id=cart_id) cart = get_cart_data(cart) cart_count = cart and len(cart['cart_products']) or 0 except Exception as e: print(f'panier non trouvé: {e}') response = render(request, 'main/home.html', locals()) if not cart and cart_id: response.delete_cookie('cart_id') return response def product_detail(request,tk): product = Product.objects.get(id=tk) similar_products = Product.objects.annotate(search=SearchVector( 'name', 'description', 'keywords', 'price','color')).filter(Q(search=product.keywords) | Q(search__icontains=product.keywords.split(' ')))[:12] product = vars(product) … -
Cannot make namespace work for main django app
TL;DR I want to use namespaces for all of my django apps. It works fine for all the regular apps, but I get a "NoReverseMatchError: 'myproject' is not a registered namespace" for my main project app. Is there anything specific to this app that causes the namespace to not work? Details I just started a new django app and I'm using namespaces for the first time. My project tree is as follow (only relevant files and directories included): myproject/ ├── myproject/ │ ├── templates/ │ │ ├── base.html │ │ └── home.html │ ├── settings.py │ └── urls.py └── app1/ ├── templates/ ├── urls.py └── views.py My urls.py files are as follows: myproject/urls.py from django.conf import settings from django.conf.urls.static import static from django.contrib import admin from django.urls import path, include from myproject import views app_name = 'myproject' urlpatterns = [ path('admin/', admin.site.urls), path('', views.home, name='home'), path('app1/', include('django.contrib.auth.urls')), path('app1/', include('app1.urls')), ] if settings.DEBUG: urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) app1/urls.py from django.urls import path from app1 import views app_name = 'app1' urlpatterns = [ path('login', views.login, name='login'), path('logout', views.logout, name='logout'), ] When calling {% url 'app1:login' %} or return redirect('app1:login') everything works fine. However, when I try to use … -
Optimal filtering of the manytomany relationship
I have a model called "Car" and another model called "Preference". The car field has a M2M relationship with "Preference". I am doing a query to get all the cars that have the preference (for example) with id= 1 and 2. (The car has many more preferences assigned to it). How can I get optimally all the cars that have strictly the Preferences with id 1 and 2? The actual functional code is the following (very suboptimal): preferences_list = [1, 2] for preference_item in preferences_list: cars = cars.objects.filter(preferences__id=preference_item) I have tried this but it doesn't work either: preferences_list = [1, 2] cars_q = Q() for preference_item in preferences_list: cars_q &= Q(preferences__id=preference_item) cars=cars.objects.filter(cars_q) Is there any more optimal alternative that does not do a query for each Preference? -
How to show a link after login on the basis of user authentication whether user has a blogging account or not
Problem context: Below is my Blogger model. I am using a one-to-one relation ship with inbuilt user class Blogger(models.Model): user = models.OneToOneField(User, null=True, on_delete=models.CASCADE) about = models.TextField(max_length=2000, null=True) def __str__(self) -> str: return f'{self.user.first_name} {self.user.last_name}' Before logging in I get the the following Login page. ( I am using django.contrib.auth.urls with custom login page that extends base_generic.html. HTML has link in the side bar About Yourself which would only show up after successful login only. {% if user.is_authenticated %} <li>User: {{ user.get_username }}</li> <li><a href="{% url 'blogger-create' %}">About yourself!</a> </li> When a user after sign up or login clicks on About yourself link then user is redirected to blogger create form where he will update his About information. User Registration creates an instance of user which would be mapped to a new instance of Blogger via About Yourself Problem I want to have two views UpdateView and CreateView that would ensure if a blogger instance is already mapped to user then the update view would be called. this would require conditions in the template of base_generic.html. if else conditions would use something like models.Blogger.objects.filter(user=self.request.user). The trouble is as already stated I am using inbuilt accounts\login. How to achieve this logic … -
Consuming API that is big part of my application
I need to consume API of my second app which will be big part of my main application. This API will affect to my main tables/models and it will extend them. I have a problem with authorization. I created standard authorization depending on access_tokens, but there is a problem with it. As I said, API will extend my main models, so I need to override save(), get() and similar methods to work with. For example: Saving ModelA in my app performs the save of ModelB in external API Geting ModelA in my app performs get of ModelB in external API The problem is when I try to talk with external API in overrided method. To do this I need request (where access_token is stored) but I can't get request in model save() method. Even if I will somehow get it, it will always be problem in diffrent places of application when I have no request. I don't know how to make it works and create the code clean. Maybe I should change the type of authorization in my second APP? -
Django project run from terminal but not from PyCharm
I can run my Django project from terminal like: python manage.py runserver, but if I try to run it from PyCharm it give me a lot of various errors. I've checked if interpreters are the same by typing "pip -V": from terminal: /home/user/Desktop/project/venv/lib/python3.8/site-packages/pip in configuration, interpreter path: ~/project/venv/bin/python -
why distinct can't save changes in value
I have this code trees = AssessmentTaskForm.objects.distinct('tree') print(trees.count()) # output is 1 trees = trees.distinct('tree_status__name_en') print(trees.count()) #output is 3 and the output are 1 in 1st print 3 in 2nd print my need is : i want to use first filtring query and use it as input in 2nd query -
Django: Get absolute file path of template file from template name, without parsing the template
How to get the absolute file path of a template file from it's template name, without parsing the template? E.g. given foo/bar.html return home/user/project/app/foo/templates/foo/bar.html The django.template.loader.get_template will parse the template. I think there was a django.template.loader.find_template but it was deprecated. Please note this is not a duplicate of How to get the template path in the view django becaue that solution parses the whole template, which is slow when trying to find the path of many template_names. -
HTTPSConnectionPool(host='newsapi.org', port=443): Max retries exceeded with url
I am trying to communicate between Django and Python file but I am getting below error : [enter image description here](https://i.stack.imgur.com/saR0y.jpg) I tried to use the api to construct a website based on django,these are my code and the error,I have tried set time out,false verify,and even changed my network connection, but it still could not connect -
Working on django project. want to make api access restricted based upon the user's group permissions
I have a custom user model with group as a field. from django.contrib.auth.models import Group class Users(AbstractBaseUser): group=models.ManyToManyField(Group, blank=True) i'm assigning model permissions to the group from django admin panel. Now i want to make sure that user's group permission should be checked before a user can access an api like this: @authentication_classes([TokenAuthentication]) class SiteList(generics.ListCreateAPIView): permission_classes = [IsAuthenticated, GroupPermission] //GroupPermission as a check queryset = Site.objects.all() serializer_class = SiteSerializer -
uwsgi not starting and returns no error, exit after showing "[uWSGI] getting INI configuration from ../ubuntu/ENV/uwsgi.ini"
When i am trying to run uwsgi, it starts and exit with out any error only return single line responce "[uWSGI] getting INI configuration from ../ubuntu/ENV/uwsgi.ini" my uwsgi.ini strict = true #binary = /home/xyz/pqr/bin/uwsgi chdir = /home/xyz virtualenv = /home/xyz/pqr uid = ubuntu gid = ubuntu wsgi-file = /home/xyz/deploy/wsgi.py socket = /home/ubuntu/sockets/uwsgi.sock master = true # threads = 4 #run uwsgi with process only thread-stacksize = 512 threads-stacksize = 512 # auto scaling cheaper-algo = busyness processes = 64 ; Maximum number of workers allowed cheaper = 4 ; Minimum number of workers allowed cheaper-initial = 4 ; Workers created at startup cheaper-overload = 1 ; Length of a cycle in seconds cheaper-step = 2 ; How many workers to spawn at a time cheaper-busyness-multiplier = 30 ; How many cycles to wait before killing workers cheaper-busyness-min = 25 ; Below this threshold, kill workers (if stable for multiplier cycles) cheaper-busyness-max = 75 ; Above this threshold, spawn new workers cheaper-busyness-backlog-alert = 16 ; Spawn emergency workers if more than this many requests are waiting in the queue cheaper-busyness-backlog-step = 4 ; How many emergegency workers to create if there are too many requests in the queue harakiri = 60 … -
Free(): Invalid Pointer error while trying to upload multiple layers in cartoview?
I have installed cartoview and trying to upload multiple layer files (total 6) in cartoview, but when i upload it then this error occurs: Free(): Invalid Pointer Aborted (core dumped) I tried to find the solution to the problem but it was not found on the web. Can someone kindly help?