Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Create django query that would give results like this [{"modelfield3_value": {"modelfield1": "value1", "modelfield2": "value2"} }]
How can I create django query that would give results like this [{"modelfield3_value": {"modelfield1": "value1", "modelfield2": "value2"} }]? Basically, the {"modelfield1": "value1", "modelfield2": "value2"} part is the dictionary that .values() method returns. Is such thing possible with django orm and postgres or I need to use the python for this? -
How to count the number of a nested array in django?
I am new to django and I'm still figuring out how use all the functions. This is the result of the query that I want to count { "id": 1, "user_id": 1, "encountersDaily": [ { "id": 1, "DateTime": "2022-08-01T01:22:00Z", "Longtitude": "14.536480570700000", "Latitude": "121.049722723900000", "EncounterExitID": 1, "PromoterID": 1, "GenderID": 1 }, { "id": 10, "DateTime": "2022-08-01T01:42:46Z", "Longtitude": "14.536480570700000", "Latitude": "121.049722723900000", "EncounterExitID": 1, "PromoterID": 1, "GenderID": 1 } ], }, { "id": 4, "user_id": 4, "encountersDaily": [ { "id": 6, "DateTime": "2022-08-01T01:42:09Z", "Longtitude": "14.536480570700000", "Latitude": "121.049722723900000", "EncounterExitID": 2, "PromoterID": 4, "GenderID": 1 }, { "id": 8, "DateTime": "2022-08-01T01:42:29Z", "Longtitude": "14.536480570700000", "Latitude": "121.049722723900000", "EncounterExitID": 1, "PromoterID": 4, "GenderID": 1 }, { "id": 9, "DateTime": "2022-08-01T01:42:38Z", "Longtitude": "14.536480570700000", "Latitude": "121.049722723900000", "EncounterExitID": 1, "PromoterID": 4, "GenderID": 2 } ], } I have this data of 2 users and my goal is to loop through this array and find the sum of the encountersDaily. is it possible to just use filter function here? or loop is necessary . -
Trying to load static images from JS script in Django
I am using a 'select2' dropdown 'https://select2.org/dropdown' component in Django to display a dropdown menu that has a flag image next to each item. In development I was creating a string literal in my JS code to point to the static img folder , but now I've deployed the application to AWS and my static files are being served through an S3 bucket and now the image is not loading. select2 component js code: function formatState (state) { if (!state.id) { return state.text; } var baseUrl = "static/img/flags"; var $state = $( '<span><img src="' + baseUrl + '/' + state.element.value.slice(0,3).toLowerCase() + '.png" class="img-flag" /> ' + state.text + '</span>' ); return $state; }; in my html inspector the image source produces: img src="static/img/flags/bsd.png" class="img-flag"> I can obviously see that the img src above is not pointing to my s3 bucket, so I've tried to create a string literal for a static img inside of the select2 js code to reproduce {% static '/img/flags/all.png' %} : '<span><img src="' + '{% static' + '"' + '/' + 'img' + '/' + 'flags' + '/' + state.element.value.slice(0,3).toLowerCase() + '.png' + '"' + ' %}' + 'class="img-flag" /> ' + state.text + '</span>' this … -
assert celery task runs or not runs
I am working on a django project as an Intern, I am developing the project not coding it from start, I added a feature to contact us section, the feature is about sending support's answer to user who sent the contact message via email after the support answered the message in admin panel, I start celery task for sending email in post_save receiver function based on some conditions, I would like to unit test this feature, what is matter to me is does celery receives task in some conditions or it doesn't I need something like this assertCeleryRecievesTask(task_name) or not, for now it is not important if the task itself works as expected just wanna know if the task starts or not, thanks for your help. -
redirect to detail view after authentication in django templates
I have a simple Group model: class Group(models.Model): leader = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_length=55) description = models.TextField() joined = models.ManyToManyField(User, blank=True) With a simple GroupDetail template: <div>Leader: {{group.leader}}</div> <div>Name: {{group.name}}</div> <div>Description: {{group.description}}</div> {% if user.is_authenticated %} <form action="{% url 'join_group' group.pk %}" method="POST"> {% csrf_token %} <button type="submit" name="group_id" value="{{group.id}}">JOIN</button> </form> {% else %} <div><a href="{% url 'login' %}">Login</a> to join chaburah</div> {% endif %} The idea is that if a User is authenticated (signed in) they can join a group. My issue is that right now, when a User clicks login they're redirected to the login page, but after login they don't return to Group they were about to join. Is there a way to sort of stash the url they were at return to it after authentication? This is becoming more important as I add invite links and private groups, where a User is sent a link to join a private Group that isn't displayed on the home page (using {% if group.private != True %} so the User won't be able to return to the Group detail without having to reclick the link they were sent. -
trouble with testing advisory_lock with pytest
Im currently trying to test a function that will lock some string and will not allow to do anything under that locked string, using advisory_lock. so here is my code: import pytest from django_pglocks import advisory_lock from threading import Thread from time import sleep def function_that_should_lock(): with advisory_lock('secret_string', wait=True): sleep(10) @eager_db_test def test_archive_qualifications_from_project_resource_lock(): failed = False lock_project_resource_qa_action_thread = Thread( target=function_that_should_lock, ) lock_project_resource_qa_action_thread.start() with advisory_lock(f'secret_string', wait=False): failed = True assert not failed For some reason function_that_should_lock actually doesn't lock the string, and failed will be set to True. Please help me understand how it works =) -
cant get selenium to work i want to test my django channels application
im trying to test my app and even if i do the most basic things my selenium refuses to work all i get is a long error message and i cant figure out why im new to selenium and i cant understand these errors, would love some help, im working on static server in django idk if its important CHANNEL_LAYERS = { "default": { "BACKEND": "channels.layers.InMemoryChannelLayer" } } tests.py import time from channels.testing import ChannelsLiveServerTestCase from selenium import webdriver from selenium.webdriver.common.action_chains import ActionChains from selenium.webdriver.common.by import By from selenium.webdriver.support.wait import WebDriverWait class ChatTests(ChannelsLiveServerTestCase): @classmethod def setUpClass(cls): try: super().setUpClass() cls.driver = webdriver.Chrome('C:\\Users\\David\\Desktop\\VSProjects\\LiveChat\\chromedriver.exe') cls.driver.implicitly_wait(10) except: cls.tearDownClass() @classmethod def tearDownClass(cls): cls.driver.quit() super().tearDownClass() def test_admin_login(self): self.driver.get(self.live_server_url) time.sleep(20) error code (livechat_env) PS C:\Users\David\Desktop\VSProjects\LiveChat\livechatapp> py manage.py test --keepdb Found 1 test(s). Using existing test database for alias 'default'... System check identified no issues (0 silenced). DevTools listening on ws://127.0.0.1:53585/devtools/browser/326e028a-0c32-4557-93a4-6c55304bae1d ETraceback (most recent call last): File "<string>", line 1, in <module> File "C:\Python310\lib\multiprocessing\spawn.py", line 107, in spawn_main new_handle = reduction.duplicate(pipe_handle, File "C:\Python310\lib\multiprocessing\reduction.py", line 79, in duplicate return _winapi.DuplicateHandle( OSError: [WinError 6] The handle is invalid ====================================================================== ERROR: test_admin_login (room.tests.ChatTests) ---------------------------------------------------------------------- Traceback (most recent call last): File "C:\Users\David\Desktop\VSProjects\LiveChat\livechat_env\lib\site-packages\django\test\testcases.py", line 287, in _setup_and_call self._pre_setup() File "C:\Users\David\Desktop\VSProjects\LiveChat\livechat_env\lib\site-packages\channels\testing\live.py", line 52, in … -
cannot show the field 'name' in REST API
When I try to retrieve all data from my REST API I get them correctly except from one field, that is the field 'name' from Skill class. Instead of the 'name' I get only its id. Can you help me to resolve this?---------------------------------------------- here is the output Here is the code: models.py from django.db import models from django.forms import ImageField from django.utils.text import slugify class Skill(models.Model): name = models.CharField(max_length=200) def __str__(self): return self.name class Project(models.Model): title = models.CharField(max_length=200) sub_title = models.CharField(max_length=200, null=True, blank=True) front_page = models.ImageField(null=True, blank=True, upload_to="images", default="broken-image.png") body = models.TextField(null=True, blank=True) created = models.DateTimeField(auto_now_add=True) skills = models.ManyToManyField(Skill, null=True) slug = models.SlugField(null=True, blank=True) def __str__(self): return self.title def save(self, *args, **kwargs): if self.slug == None: slug = slugify(self.title) has_slug = Project.objects.filter(slug=slug).exists() count = 1 while has_slug: count += 1 slug = slugify(self.title) + '-' + str(count) has_slug = Project.objects.filter(slug=slug).exists() self.slug = slug super().save(*args, **kwargs) serializers.py from rest_framework import serializers from project.models import Project, Skill class ProjectSerializer(serializers.ModelSerializer): class Meta: model = Project fields = '__all__' views.py from rest_framework.response import Response from rest_framework.decorators import api_view from project.models import Project, Skill from .serializers import ProjectSerializer from rest_framework import status from django.shortcuts import get_object_or_404 @api_view(['GET']) def getData(request): project = Project.objects.all() serializer = ProjectSerializer(project, … -
Django for APIs: Build web APIs with Python and Django
I am currently searching for Django for APIs: Build web APIs with Python and Django 4.0 PDF it would be very helpful if anyone provide me with this books pdf -
unsupported operand type(s) for *=: 'dict' and 'int' - Django RowNumber()
I'm trying to use RowNumber() : qs = self.filter_queryset(self.get_queryset()) qs = qs.annotate( row_number = Window( expression = RowNumber(), order_by = F('score').desc() )) order_by part returns the error: unsupported operand type(s) for *=: 'dict' and 'int' How can I fix? -
omiting path from url
I'm newbie in Django Channels and I'm trying to follow and recreate this project from Django channels documentation (which is 4 part) : https://channels.readthedocs.io/en/latest/tutorial/part_1.html#add-the-index-view as you can see for accessing the project I have to go with STH like this: 192.168.43.175:8000/chat/lobby_room I'm wondering how to completely omit the path and accessing the project through : 192.168.43.175:8000/ This is my urls.py : from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('chat/', include('chat.urls')), ] This is my views.py : from django.shortcuts import render # Create your views here. def index(request): return render(request, 'chat/index.html') def room(request, room_name): return render(request, 'chat/room.html', { 'room_name': room_name }) This is my chat application urls.py: from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), path('<str:room_name>/', views.room, name='room'), ] This is my routing.py: from django.urls import re_path from . import consumers websocket_urlpatterns = [ re_path(r'ws/chat/(?P<room_name>\w+)/$', consumers.ChatConsumer.as_asgi()), ] This is my consumers.py: import json from channels.generic.websocket import AsyncWebsocketConsumer class ChatConsumer(AsyncWebsocketConsumer): async def connect(self): self.room_name = self.scope['url_route']['kwargs']['room_name'] self.room_group_name = 'chat_%s' % self.room_name # Join room group await self.channel_layer.group_add( self.room_group_name, self.channel_name ) await self.accept() async def disconnect(self, close_code): # Leave room group await self.channel_layer.group_discard( self.room_group_name, self.channel_name ) # Receive message from … -
email verification via apppassword is not working
In my Django e-commerce project i was using my g mail account as EMAIL_HOST_USER for sending email verification for registering.but since may30 2022 the less secure apps feature has been disabled.and i got error when i tray to signup with new email .and to let 3rd party apps access gmail I generate an App password for my e-commerce in my gamil account and i change EMAIL_HOST_PASSWORD from my gamil password to the new generated apppassword and when i tray to signup,the error is gone but still it dose not send activation link to the new email !so how can I fix this issue ? -
Cannot satisfy path requirement for an image in FilePathField of model and display it in a template
As per a tutorial I have a model with: class Project(models.Model): ... image = models.FilePathField(path="/img") The files are rendered in the template with: {% extends "base.html" %} {% load static %} ... <img class="card-img-top" src="{% static project.image %}"> ... {% endblock %} In the tutorial, the image files were entered manually and it all worked because they were stored in app_name/static/img. But when I try to enter a new Project via the admin it cannot find the /img directory. But if I change the path= to an absolute address such as /home/me/project_name/app__name/static/img as apparently necessary, or even /static/img, which seems to be accepted, the template adds an extra 'static'in front of the address. I could remove the 'load static' from the template, but I wonder whether there is a better way. Also I am not sure how all this fits into the use of 'collectstatic' later on for production servers. -
django_cities_light not populate No module named 'myapp.settings" I use cookie cutter
I've just create a new project : pubsauvage with cookie cutter django. I want to use Django-cities-light (last version). So I add module and do migrate. I can see all the tables cities_light (empty). When I want to populate with manage.py cities_light I have this error: Thaks for help to solve this. ModuleNotFoundError: No module named 'pubsauvage.settings' -
In Django views.py I create a session in method A and try to read it in class B. Error: attribute session not defined in class B
this may have a straigthforward solution. I hope you can help me. I have the following @api_view(['POST']) def methodA(request): myvariable=request.data['list'] # This is an Ajax Post request.session['myvar'] = myvariable print(request.session['myvar']) # it works. shows Ajax Post value return JsonResponse({'success':True}) class classB(classC): def myvarmethod(request): print(request.session['myvar']) def importantmethod(self): self.myvarmethod() ... return [...] # some stuff My goal is to print 'request.session['myvar']' inside classB (in importantmethod()). The output is: object myChart has not attribute session. Where do I need to define session? -
Validation Check Not Working in Form.py Django
I have to create this validation rule when Start= (start_new + start_old) >0 or is positive and End = (end_new + end_old) >0 or is positive then the validation error will raise that" Positive Strat and Positive End are not allowed in the conjunction", But with my below code it is not checking the validation rule and allowing the positive start and positive end values in the conjunction. **When I debugged the code the the end_new and end_old values are not storing thats why the validation not working any idea how i can solve this error ** my code in django form.py for i in range(count): start_new = int(self.data.get(f'applicationruntime_set-{i}-start_new') or 0) start_old = int(self.data.get(f'applicationruntime_set-{i}-start_old') or 0) end_new = int(self.data.get(f'applicationruntime_set-{i}-end_new') or 0) end_old = int(self.data.get(f'applicationruntime_set-{i}-end_old') or 0) if (start_new + start_old) > 0 and (end_new+end_old) > 0: raise ValidationError( f" Positive Start values and Positive End values are not allowed to be used in conjunction") -
Is there a way could deploy Django project on namecheap in ASGI mode?
I'm trying to deploy my Django on Namecheap, the server should work but I got the following message traceback: [ERROR] [UID:12123][2655752] wsgiAppHandler pApp->start_response() return NULL. Traceback (most recent call last): File "/home/alshigpf/website/passenger_wsgi.py", line 41, in __call__ return self.app(environ, start_response) TypeError: __call__() missing 1 required positional argument: 'send' [ERROR] [UID:12123][2655752] wsgiAppHandler pApp->start_response() return NULL. Traceback (most recent call last): File "/home/alshigpf/website/passenger_wsgi.py", line 41, in __call__ return self.app(environ, start_response) TypeError: __call__() missing 1 required positional argument: 'send' This is what my passenger_wsgi.py file looks like: import os import sys import django sys.path.append(os.getcwd()) os.environ['DJANGO_SETTINGS_MODULE'] = 'website.settings.development' django.setup() SCRIPT_NAME = os.getcwd() print("Script name: ", SCRIPT_NAME) class PassengerPathInfoFix(object): """ Sets PATH_INFO from REQUEST_URI because Passenger doesn't provide it. """ def __init__(self, app): self.app = app print("Start Init") print("App is: ", self.app) print("End Init") def __call__(self, environ, start_response): from urllib.parse import unquote print("Start Calling") environ['SCRIPT_NAME'] = SCRIPT_NAME request_uri = unquote(environ['REQUEST_URI']) script_name = unquote(environ.get('SCRIPT_NAME', '')) offset = request_uri.startswith(script_name) and len(environ['SCRIPT_NAME']) or 0 environ['PATH_INFO'] = request_uri[offset:].split('?', 1)[0] return self.app(environ, start_response) # Get ASGI application from website.routing import application print("Before calling application") application = PassengerPathInfoFix(application) when I googled I glanced that there's something called "Uvicorn" which is an updated version of Gunicorn to handle ASGI mode. when I did … -
when I call this javascript function in django template like this "<h4 id="followings" onclick="followings();">followings</h4>" it is not working
when I call this javascript function(stored in static files) in django template like this "followings" it is not working. But other functions are working. javascript caode function followings() { let url = 'following/' console.log(url) fetch(url) .then(response => response.json()) .then(data => { var body = document.getElementById('follow-body') body.innerHTML = null for (let x = 0; x < data.length; x++) { var user = `<div class="recom-user"> <img src="${data[x].profile_pic}" alt=""> <div class="recom-user-name"> <p class="username">${data[x].full_name}</p> <p class="userid">${data[x].user}</p> </div> <button class="follow-btn">unfollow</button> </div>` b ody.innerHTML += user } }) } i called it like this: <h4 id="followings" onclick="followings();">followings</h4> -
Question: Decouple frontend and backend to send email using DRF
I'm working on a project, the frontend is being built using React while I'm using Django Rest Framework for the backend. I want to send verification and password reset mail to the user. I know I can set emails sub folder in my templates directory, and send the appropriate mail. Is there a way I can navigate that, in the sense that the frontend should be the one to set up the mail design and send the design to the backend while I handle the parameters that should be In the mail and send the mail on the backend? -
Django-tinymce working with "manage.py renserver", but not served by apache2
The mce does not appears when running under apache: I get texaereas. In both cases (running with "runserver" and with apache, on two different machines, Ihave djang-tinymce installed in the vitualenv. In the form.py file I have: from django.forms import TextInput, Textarea from tinymce.widgets import TinyMCE and class myform(forms.Form): titre=forms.CharField(label="titre",help_text=help, required=True, widget =TinyMCE(attrs={'cols': 50, 'rows': 4} and in my template html file: <head> ... {{ form.media }} </head> then: <table class="table table-sm"> {{ form.as_table }} </table> No idea of what happens... -
how does a flask server validates the form even after returning the html file itself?
@app.route("/register", methods=["GET", "POST"]) def register(): form = Form() if form.validate_on_submit(): pass return render_template("register.html", form=form) In the above code first there comes the if statement and then the form is returned. So after returning the form how does the if statement still validates the form? whereas after return statement is executed the function should stop running. -
Django how to reverse to autocreated page
I have a CustomUser model and a UserProfile model. The UserProfile is linked to the CustomUser via a foreign key. A new UserProfile is auto created whenever a new CustomUser is created. After a new CustomUser is added, I want to land on the UserProfile page so the person adding the user can also edit the profile. I have not been able to figure out how to specify the UserProfile id in the view for adding the new user. The models: class UserProfile(models.Model): user = models.OneToOneField(CustomUser, null=True, on_delete=models.CASCADE) preferred_name = models.CharField(null=True, blank=True, max_length= 75) pronouns = models.CharField(null=True, blank=True, max_length= 40) phone = PhoneField(blank=True, help_text='Contact phone number') job_title = models.CharField(null=True, blank=True, max_length= 75) birthdate = models.DateField(null=True, blank=True) bio = tinymce_models.HTMLField(null=True, blank=True) profile_image = ConstrainedFileField( null=True, blank=True, upload_to='projects/employee_profiles', content_types=['image/png', 'image/jpg', 'image/jpeg', 'image/gif'], max_upload_size=2097152, ) def create_user_profile(sender, instance, created, **kwargs): if created: UserProfile.objects.create(user=instance) post_save.connect(create_user_profile, sender=CustomUser) class CustomUser(AbstractUser): full_name = models.CharField(max_length=250, null=True) age = models.PositiveIntegerField(null=True, blank=True) employee_type = models.ForeignKey(Group, null=True, on_delete=models.SET_NULL, default=1) is_active = models.BooleanField(null=False, default=True) The view: class AddCompanyEmployee(CreateView): model = CustomUser template_name = 'manage/add_employee.html' form_class = AddCompanyEmployeeForm def get_success_url(self): return reverse('userprofile_detail', args=[self.kwargs.get('userprofile_pk')]) The form: class AddCompanyEmployeeForm(UserCreationForm): class Meta: model = CustomUser fields = UserCreationForm.Meta.fields + ('email', 'full_name', 'age',) The UserProfile URL: from … -
Video qualities
I need to separate the quality of the video that is being uploaded to my platform and I need to save the video in different qualities for example the quality of the incoming video is 1080p and I need to save it in 720p and 480p. -
Filter data between two dates in Django rest api
I am creating a react app that uses Django rest APIs. I want to filter data between two date range such that the user can select start date and end date and from the frontend and send a post request to my Django backend and the filtering to be done from the backend. Currently I'm stuck the filtering isn't working. I'm filtering by timestamp(added_on). My model class Orders(models.Model): choices = ((1, "Nairobi"), (2, "Nyanza"), (3, "Central"), (4, "Coast"), (5, "Eastern"), (6, "North Eastern"), (7, "Western"), (8, "Rift Valley")) choices1 = ((1, "Pishori"), (2, "Komboka")) id = models.AutoField(primary_key=True) phone = models.CharField(max_length=255) name = models.CharField(max_length=255) customer_id = models.ForeignKey(Customer, on_delete=models.CASCADE) town = models.CharField(max_length=255) region = models.CharField(choices=choices, max_length=255) farmer_id = models.ForeignKey(Farmer, on_delete=models.CASCADE) kgs = models.CharField(max_length=255) packaging = models.CharField(max_length=255) transport = models.CharField(max_length=255) discount = models.CharField(max_length=255) amount = models.CharField(max_length=255) price = models.CharField(max_length=255) comment = models.TextField() rice_type = models.CharField(choices=choices1, max_length=255) status = models.BooleanField(default=False) added_on = models.DateTimeField(auto_now_add=True) objects = models.Manager() my serializer class OrdersSerializer(serializers.ModelSerializer): class Meta: model = Orders fields = "__all__" def to_representation(self, instance): response = super().to_representation(instance) response["farmer"] = FarmerSerializer(instance.farmer_id).data response["customer"] = CustomerSerializer(instance.customer_id).data return response my view class OrderDateViewSet(generics.ListAPIView): serializer_class = OrdersSerializer queryset = Orders.objects.all() permission_classes = [permissions.AllowAny] def post(self, request): try: serializer = OrdersSerializer(data=request.data, context={"request": request}) … -
Django channels send message to all connected users
I want to send random generated message to every client visiting page. For now i can connect only one client. When i try to connect from other tab it throws me an error. Like i said one connection works, but my goal is to have multiple connections, that receives the very same message. Application instance <Task pending name='Task-173' coro=<StaticFilesWrapper.__call__() running at /Users/username/React/app/venv/lib/python3.9/site-packages/channels/staticfiles.py:44> wait_for=<Future pending cb=[_chain_future.<locals>._call_check_cancel() at /usr/local/Cellar/python@3.9/3.9.13_1/Frameworks/Python.framework/Versions/3.9/lib/python3.9/asyncio/futures.py:384, <TaskWakeupMethWrapper object at 0x10c15c5e0>()]>> for connection <WebSocketProtocol client=['127.0.0.1', 50618] path=b'/ws/dice'> took too long to shut down and was killed. My Consumers.py looks like this: import json from random import randrange from channels.generic.websocket import JsonWebsocketConsumer from asgiref.sync import async_to_sync from datetime import * import time class DiceConsumer(JsonWebsocketConsumer): def connect(self, immediately=True): self.room_group_name = 'example_room' self.accept() while True: if datetime.now().strftime('%S') != '00': self.send( json.dumps({'action': "nothing", 'time': datetime.now().strftime('%S')})) elif datetime.now().strftime('%S') == '00': self.send(json.dumps( {'action': "start dice", 'winning_value': randrange(1, 6)})) time.sleep(1) def disconnect(self, code): return super().disconnect(code)