Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Sonarqube exection failure while trying to analyse Python code locally on windows
C:\sonar-scanner-5.0.1.3006-windows\bin>sonar-scanner.bat INFO: Scanner configuration file: C:\sonar-scanner-5.0.1.3006-windows\bin..\conf\sonar-scanner.properties INFO: Project root configuration file: NONE INFO: SonarScanner 5.0.1.3006 INFO: Java 17.0.7 Eclipse Adoptium (64-bit) INFO: Windows 10 10.0 amd64 INFO: User cache: C:\Users\AREKAN.sonar\cache INFO: Analyzing on SonarQube server 9.9.0.65466 INFO: Default locale: "en_US", source code encoding: "UTF-8" INFO: Load global settings INFO: Load global settings (done) | time=105ms INFO: Server id: 147B411E-AYos9Bu0eOBihffPYMUp INFO: User cache: C:\Users\AREKAN.sonar\cache INFO: Load/download plugins INFO: Load plugins index INFO: Load plugins index (done) | time=48ms INFO: Load/download plugins (done) | time=313ms INFO: Loaded core extensions: developer-scanner INFO: Process project properties ERROR: Invalid value of sonar.sources for OLU-APP INFO: ------------------------------------------------------------------------ INFO: EXECUTION FAILURE INFO: ------------------------------------------------------------------------ INFO: Total time: 2.546s INFO: Final Memory: 21M/74M INFO: ------------------------------------------------------------------------ ERROR: Error during SonarScanner execution ERROR: The folder 'C:sonar-scanner-5.0.1.3006-windowsbincode' does not exist for 'OLU-APP' (base directory = C:\sonar-scanner-5.0.1.3006-windows\bin) ERROR: I put my django code in a folder and then edited the .property file to point to the folder where my Django code is but when I ran the sonarscan.. i go the error shown -
DRF ModelSerializer implicitly ignore some fields that are not excluded
I have a model: class GeneratedMessage(models.Model): generated_message_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) status = models.CharField(...) message_type = models.CharField(...) ... prospect = models.ForeignKey(to=Prospect...) ai_prompt = models.ForeignKey(to=AiPrompt...) And a model serializer: class GeneratedMessageSerializer(serializers.ModelSerializer): class Meta: model = GeneratedMessage exclude = ['prospect', 'ai_prompt'] read_only_fields = ['__all__'] Actually, I use this serializer inside another one: class GeneratedEmailSerializer(serializers.Serializer): body = GeneratedMessageSerializer() ... This is the way I create a response: class ProspectGenerateMessageAPI(APIView): ... @extend_schema(..., responses={200: GeneratedEmailSerializer}) def post(self, request): ... generated_message.save() response = GeneratedEmailSerializer(data={ ... "body": GeneratedMessageSerializer(generated_message).data }) response.is_valid(raise_exception=True) return HttpResponse.ok(response.data) However, the response has no field body.generated_message_id even though it was never excluded! Other fields like the body.status are presented in the response. Important facts: I find out in the Debug mode that GeneratedMessageSerializer(generated_message).initial_data have a valid id, while GeneratedMessageSerializer(generated_message).data not. Swagger docs generated by @extend_schema are somewhy correct with the field generated_message_id -
page not found while giving path in urls.py of app 'blog-single.html/<int:id>',views.blogsidebar, name='blog-sidebar'
It shows page not found while giving path in urls.py of app 'blog-single.html/<int:id>',views.blogsidebar, name='blog-sidebar' enter image description here It is my urls.py 's paths. Here while I added <int:id > the blog-single.html page started showing page not found enter image description here and it is my views.py's file .....can anyone say what causes for showing this error enter image description here -
Why dosent django find my assets and attachements?
I have a website hosted on centos7 And I want to move it to ubuntu22.04.3 I installed python 3.10.12 and 3.11.4 versions django and all prerequisits I'v changed the apacheconfig file but when I run the server It works but it does not find my assets and attachements here is the output on the stdout: sudo python3 manage.py runserver Performing system checks... System check identified no issues (0 silenced). August 29, 2023 - 12:00:53 Django version 3.2.12, using settings 'website.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. [29/Aug/2023 12:00:58] "GET /fr/ HTTP/1.1" 200 55434 [29/Aug/2023 12:00:58] "GET /assets/css/default.css HTTP/1.1" 404 179 [29/Aug/2023 12:00:58] "GET /assets/css/bootstrap-icons.css HTTP/1.1" 404 179 [29/Aug/2023 12:00:58] "GET /assets/css/bootstrap.min.css HTTP/1.1" 404 179 [29/Aug/2023 12:00:58] "GET /uploads/2022/12/08/photo1.PNG HTTP/1.1" 404 179 [29/Aug/2023 12:00:58] "GET /uploads/2023/03/17/image35.JPG HTTP/1.1" 404 179 Please any idea might help share if you have a clue I tried modifying the apache2 config file and a lot more. -
Why can't gunicorn utilize more workers (google app engine)?
In documentation you can find https://cloud.google.com/appengine/docs/flexible/python/runtime. It says that not having gunicorn.conf.py that sets multiple workers could increase latency since default worker number is 1 (latency does get high with one worker 800ms). However obeying the recommended gunicorn setup increases the response time by 4 more seconds and sometimes it just fails to deliver. My entrypoint: entrypoint: gunicorn -c gunicorn.conf.py -b :$PORT main:app Entrypoint with one worker: entrypoint: gunicorn -b :$PORT main:app What could be the issue? -
Django:- The QR code is being generated successfully, but it is not being saved to the database
I'm using qrcode, a Python library that enables you to generate QR codes. I want to use this Python library inside my Django signals to generate a QR code for every newly created user. However, when the user is created, it doesn't create an Account model object, and the QR code is generated inside my project directory, instead of static folder. How can I solve this problem. signals.py: @receiver(post_save, sender=User) def create_account(sender, instance, created, **kwargs): if created: random_number = ''.join(random.choices(string.digits, k=20)) img = qrcode.make('cullize') img.save('default.png') Account.objects.create( user=instance, qr_code=img, account_id=random_number ) class Account(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) qr_code = models.ImageField(upload_to='qrcode') account_id = models.IntegerField() -
CommandError: App 'accounts' does not have migrations
when i run python manage.py makemigrations accounts and python manage.py migrate accounts, it does not create a migrations folder and even when i run python manage.py migrate it migrates all apps except accounts. The app has a pycache folder though I expected it to create a migrations folder -
Excluding venv directory in PyCharm does not work
I have a django project with the python virtual environment installed within the project directory. The directory is ignored by git. Now I would like to mark the directory as excluded in PyCharm. I can do this with other directories but if I do it with the venv directory, it doesn't work. It seems as the process is started. If I try do do it again, I get the option "Cancel Exclusion" (see screenshot). This does not go away and does not resolve itself also after longer periods of time (2hrs+). Any idea what I might be doing wrong or how I can fix this issue? -
Django transactions: the documentation about handling exceptions is not clear
In short: does the transaction.atomic() roll back the transaction if an exception occurs, regardless of whether it's properly handled or not? Here's a slightly modified example based on the documentation: try: with transaction.atomic(): generate_relationships_1() generate_relationships_2() generate_relationships_3() return True except IntegrityError: handle_exception(generic_message) return False However, what if I desire a more descriptive message when this happens? Consider the following: with transaction.atomic(): try: generate_relationships_1() except IntegrityError: handle_exception(message_1) return False try: generate_relationships_2() except IntegrityError: handle_exception(message_2) return False try: generate_relationships_3() except IntegrityError: handle_exception(message_3) return False Will the transaction still be rolled back if there's an exception? Examine the code carefully: the exception can arise within the transaction.atomic() block, and it's handled inside the block without transaction.atomic() being aware of the issue. -
Ctrl+C doesnt quit development server in VS Code (MacOS)
A couple months ago or so VS Code was automatically updated and ever since Im not able to kill development servers within the VS terminal for whatever reason. Before it used to work perfectly fine. It doesnt work for Django, React and Flask apps. Every time I want to quit a server I have to open up a new terminal and kill the entire process with "pkill -f", activate the virtual environment again etc. Im using MacOS High Sierra 10.13.01 and VSCode Version: 1.81.1 Screenshot: -
In Wagtail how can I access the Page object from inside the StructBlock template?
I have a page called Event For the event I would like to have a program. Program consists of ProgramEntry objects linked to the page with ParentalKey. I would like this program to be displayed in the html, but it should be in a streamfield so that the editors can place it wherever they like in the page. To do this I would like to render the my custom ProgramEntryBlock that is simply this: class ProgramEntryBlock(blocks.StructBlock): class Meta: label = _("Program entry") template = "blocks/program-entry-block.html" in my template blocks/program-entry-block.html I would like to have something like this: {% if page.program_entries.exists %} (...) {% for entry in page.program_entries.all %} (...) {% endfor %} {% endif %} How can I pass the Page object in this template? Or, what could be a better solution to my problem? -
Find count of students who made payment this month for each teacher
I have got following models Teacher(models.Model): name = models.CharField(...) Student(models.Model): name = models.CharField(...) Group(models.Model): teacher = models.ForeignKey(Teacher) students = models.ManyToManyField(Student) Payment(models.Model): student = models.ForeignKey(Student) I have to prepare report about teachers that includes tottal number students who made payment in this month. like Tacher A 12 students. Here I have tried this one to find number of students for single teacher. teacher.group_set.select_related("course").annotate(students = Count("students").aggregate(tottal = Sum("students")) Here I got number of all students but I can't filter students who made payment. -
how to write test to check fallback in django function?
i have a function read data from redis and if redis is down it read data from database. def read_data(): try: # read from redis redis_handle = redis.Redis(host=redis_host, port=redis_port) # expected data: 'redis data' data = redis_handle.get('my_key') except: data = 'default data' and for test this part to check fallback work corectly i write this test. # Integration test def test_integrate_get_order_book(self, api_client, test_user): with patch.object(redis, 'Redis', Mock(side_effect=Exception("Simulated Redis error"))): default_data = read_data() # Compare data from Redis with data from the database assert default_data == 'default data' the problem is that the mock redis when raise error, function still try to read data from redis and assert invalid request with defualt data. does anybody have idea why this happend? -
changes made in django frontend is not working
I am trying to use a sefaria project : https://github.com/Sefaria/Sefaria-Project i have ran the project locally and when I tried to change the logo and some text in Header.jsx under static/js folder, desired result is not showing on browser. I am guessing its because of django caching that they put in place. If you guys have any idea, how to figure it, plz let me know. const headerContent = ( <> <div className="headerNavSection"> { Sefaria._siteSettings.TORAH_SPECIFIC ? <a className="home" href="/" >{logo}</a> : null } <a href="/texts" className="textLink"><InterfaceText context="Header">Textss</InterfaceText></a> <a href="/topics" className="textLink"><InterfaceText>Topicss</InterfaceText></a> <a href="/community" className="textLink"><InterfaceText>Communityss</InterfaceText></a> <DonateLink classes={"textLink donate"} source={"Header"}><InterfaceText>Donate</InterfaceText></DonateLink> </div> -
Django - setting up Server-sent Events with Channels: Unhandled Exception: SseConsumer() missing 2 required positional arguments: 'receive' and 'send'
I have an existing Django Channels setup that is working with websockets and I have to add another endpoint to support SSE. I'm following an example from here https://channels.readthedocs.io/en/stable/topics/consumers.html to set up a consumer using AsyncHttpConsumer and I've been getting an error: TypeError: ServerSentEventsConsumer() missing 2 required positional arguments: 'receive' and 'send' My setup is as follows: playground/consumers.py from datetime import datetime from channels.generic.http import AsyncHttpConsumer class ServerSentEventsConsumer(AsyncHttpConsumer): async def handle(self, body): await self.send_headers(headers=[ (b"Cache-Control", b"no-cache"), (b"Content-Type", b"text/event-stream"), (b"Transfer-Encoding", b"chunked"), ]) while True: payload = "data: %s\n\n" % datetime.now().isoformat() await self.send_body(payload.encode("utf-8"), more_body=True) await asyncio.sleep(1) playground/asgi.py import os import django from django.core.asgi import get_asgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'playground.settings.production') django.setup() application = get_asgi_application() playground/routing.py from playground.asgi import application from channels.routing import ProtocolTypeRouter, URLRouter from channels.security.websocket import AllowedHostsOriginValidator from .consumers import ( BaseConsumer, ServerSentEventsConsumer, ) from django.urls import path, re_path application = ProtocolTypeRouter( { "http": application, "websocket": AllowedHostsOriginValidator( JwtAuthMiddlewareStack( URLRouter( [ re_path(r"^wss$", BaseConsumer), re_path("sse", ServerSentEventsConsumer.as_asgi()) # <- Desperate attempt. I don't wanna use websockets. ] ) ) ), } ) playground/urls.py urlpatterns = [ path("sse/", ServerSentEventsConsumer.as_asgi(), name="sse") ] I am using the following software versions: asgiref = "3.7.2" Django = "4.0.10" channels-redis = "4.1.0" channels = "4.0.0" I've seen some related issues where people resolved … -
Extending Django model
I have two apps in my project, app1 and app2. In app1 I have two models called Task and Job. I want to add new feature to these two models, I want to add category to them. But its more complicated then just a new field and app2 is mainly responsible for estimation of the category, so I created new model in the app2 as below: class Category(models.Model): CAT1 = 1 CAT2 = 2 OTHER = 6 UNKNOWN = 7 CATEGORY_CHOICES = ( (CAT1, "Cat1"), (CAT2, "Cat2"), (OTHER, "Other"), (UNKNOWN, "Unknown"), ) auto_category = models.PositiveSmallIntegerField(choices=CATEGORY_CHOICES, default=UNKNOWN) user_category = models.PositiveSmallIntegerField(choices=CATEGORY_CHOICES, default=UNKNOWN) modify_timestamp = models.DateTimeField(blank=True, null=True) modified_by = models.ForeignKey("app1.User", on_delete=models.PROTECT, related_name='category_creator', blank=True, null=True) Also I want every Task and Job object to have a default category as soon as it is created so I don't have to deal with None values on the frontend, "Unknown" value should be a default value so I created below function in app2/utils.py: def create_default_category(): new_category = Category.objects.create() return new_category.pk And then I added OneToOneField relation to my Task and Job models in the app1 as well as default value: class Task(models.Model): # Some already existing fields category = models.OneToOneField('app2.Category', on_delete=models.CASCADE, related_name='task_category', default=create_default_category) class Job(models.Model): # Some … -
Blocked 'frame-ancestors'
I have set CSP_FRAME_ANCESTORS = ("*", ) in my Django application. But still, I am seeing Blocked 'frame-ancestors' in logs. Am I missing something here? -
How to resolve graphene DjangoFilterConnectionField?
I have below queries in my graphene API list, class Query(UserQuery, graphene.ObjectType): all_users = DjangoFilterConnectionField( UserType, filterset_class=UserFilter) all_leagues = DjangoFilterConnectionField( LeagueType, filterset_class=LeagueFilter) For these connections fields I need to apply @login_required style permission. I found that I need to resolve these api endpoints in order to apply those. @login_required def resolve_all_users(self, info): #code But I don't know what to return from the above method? There is a model called Users and ideally all records from that model needs to be returned. But when I apply filter on first, last, before, after, I get below error, "message": "Query.resolve_all_users() got an unexpected keyword argument 'first'" Please advise. -
Invalidate Django cached_property in signal handler without introducing unnecessary queries
Let's say I have the following Django models: class Team(models.Model): users = models.ManyToManyField(User, through="TeamUser") @cached_property def total_points(self): return self.teamuser_set.aggregate(models.Sum("points"))["points__sum"] or 0 class TeamUser(models.Model): team = models.ForeignKey(Team, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) points = models.IntegerField() I want to create a signal handler that will invalidate the team.total_points cache when TeamUser object is created/updated/deleted. I started with the following signal handler. Note the Django docs recommended the del instance.prop call. @receiver(post_save, sender=models.TeamUser) @receiver(post_delete, sender=models.TeamUser) def invalidate_cache(**kwargs): try: del kwargs["instance"].team.total_points except AttributeError: pass And some tests. Note I'm using pytest-django. def test_create_team_users(django_assert_num_queries): user = factories.UserFactory() team = factories.TeamFactory() assert team.total_points == 0 with django_assert_num_queries(1): TeamUser.objects.create(team=team, user=user, points=2) assert team.total_points == 2 with django_assert_num_queries(1): TeamUser.objects.create(team=team, user=user, points=3) assert team.total_points == 5 def test_delete_all_team_users(django_assert_num_queries): user = factories.UserFactory() team = factories.TeamFactory() for _ in range(10): TeamUser.objects.create(team=team, user=user, points=2) with django_assert_num_queries(2): TeamUser.objects.all().delete() assert team.total_points == 0 The test_create_team_users test passed but the test_delete_all_team_users test failed because the query count is 12 instead of 2. Yikes! Looks like an N+1 query. To prevent this, I updated my signal handler to only invalidate the team.total_points cache if the user object is cached on the TeamUser object. I found the is_cached method in this SO answer. @receiver(post_save, sender=models.TeamUser) @receiver(post_delete, sender=models.TeamUser) … -
executing async task or background task in a Django service running on GCP Cloud run
I'm building a Django application and planning to deploy it on Cloud Run. I have used celery before, but it seems too complicated to set it up with Cloud Run. After some exploration, I found Cloud Task and Cloud Scheduler. My understanding is I can use Cloud Scheduler to init HTTP requests to my cloud run service periodically and use Cloud Task as a queue to send HTTP requests on demand. So my question is what's the best practice to deploy my service? For the easiness of development, I see I can only have one Django repo docker and deploy that to a single cloud run service. Then all the regular requests and all async/background requests will go to the same service(the task execute endpoints will also be public). Another way is to deploy a second cloud run service using the same docker, but hide that in vpc network. Is there a good reason to do the second one instead? (If cloud run scales itself, isn't that cost the same?) I looked at https://cloud.google.com/run/docs/authenticating/service-to-service, There is service to service authentication, but wonder did anyone implemented the Django level permission auth on task endpoints? can i use my service jwt instead … -
How to return an html file as a response python django
This is my views file: from django.shortcuts import render from django.http import HttpResponse def hellothere(request): return render(request, "hello.html") # use forward slashes Everything is right, the name of the file is right, but for some reason django keeps saying that "the template could not be found". What reasons could there be that django couldn't find the template? This views.py file is in an app called "playground" and the hello.html file is in a folder in playground called "templates". Also, I've already tried adding the filepath to the DIRS attribute in the TEMPLATES array and I've tried using the exact and relative path of hello.html instead of just "hello.html", yet the problem still persists. -
Generate PDF's Pages with a background image
I'm generating a pdf with Django. This is the code def generar_pdf(request): response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename="mi_archivo.pdf"' buffer = BytesIO() doc = SimpleDocTemplate(buffer, pagesize=letter) contenido = [ {"spaceBefore": 0, "spaceAfter": 15, "texto": "text 1", "tipo": 1, "negrita": False}, {"spaceBefore": 0, "spaceAfter": 0, "texto": "text 2", "tipo": 2, "negrita": False}, {"spaceBefore": 15, "spaceAfter": 15, "texto": "text 3", "tipo": 3, "negrita": False}, {"spaceBefore": 0, "spaceAfter": 0, "texto": "text 4", "tipo": 2, "negrita": False}, {"spaceBefore": 15, "spaceAfter": 0, "texto": "text 5", "tipo": 3, "negrita": False}, ... ] flowables = [] for item in contenido: parrafo = Paragraph(item['texto'], ParagraphStyle( name=name, fontName='Helvetica', fontSize=18, alignment=TA_LEFT, spaceBefore=item['spaceBefore'], spaceAfter=item['spaceAfter'] )) flowables.append(parrafo) doc.build(flowables) pdf = buffer.getvalue() buffer.close() response.write(pdf) return response In this pdf, I need each page to have a background image. I tried using PageTemplate this way: frame = Frame(inch, inch, doc.width - 2 * inch, doc.height - 2 * inch) template = PageTemplate(id='background', frames=[frame], onPage=add_background) doc.addPageTemplates([template]) But it only apply in the first page, and no to the others.In addition, it reduces the size where the information is displayed but i don't know why. -
When i publish my Django CMS page with a ManyToManyField it's just be displayed in edit page
When i publish my Django CMS page with a ManyToManyField it's just be displayed in edit page. This is my model code: class ProductCarrossel(CMSPlugin): title = models.CharField( verbose_name='Título do Carrossel', max_length=150, null=True, blank=True, ) subtitle = HTMLField( verbose_name='Subtítulo do Carrossel', max_length=1000, help_text='Insira um subtítulo para o Carrossel', null=True, blank=True, default='', ) categories = models.ManyToManyField( Category, related_name="products_to_carrossel_by_category", blank=True, verbose_name='Selecione as Categorias desejadas', ) subcategories = models.ManyToManyField( Subcategory, related_name="products_to_carrossel_by_subcategory", blank=True, verbose_name='Selecione as Subategorias desejadas', ) text_color = models.CharField( max_length=30, choices=ColorClassesToTexts.choices, default=ColorClassesToTexts.AZUL, verbose_name='Somente os textos da capa', help_text='Selecione a cor dos textos', ) def __str__(self): return "{}{}".format(self.title, self.subtitle) class Meta: verbose_name = 'Carrossel de Produtos' verbose_name_plural = 'Carrossíes de Produtos' This is my CSM plugin code: @plugin_pool.register_plugin class ProductCarroselPlugin5(CMSPluginBase): module = 'Produto' name = '04 - Produtos - Carrossel de Produtos' model = ProductCarrossel render_template = "productapp/product_carrossel.html" allow_children = False def render(self, context, instance, placeholder): if instance.show_only == 'category': carrossel_products = Product.objects.filter( category__in=instance.categories.all(), productimage__isnull=False, # Apenas produtos que tenham imagem productprice__price__gt=0, # Apenas produtos com preço > 0 disp='disponivel' ).order_by('?')[:12] elif instance.show_only == 'subcategory': carrossel_products = Product.objects.filter( subcategory__id__in=instance.subcategories.all(), productimage__isnull=False, # Apenas produtos que tenham imagem productprice__price__gt=0, # Apenas produtos com preço > 0 disp='disponivel' ).order_by('?')[:12] for product in carrossel_products: #Pegando preço dos produtos … -
"Error Failed to load PDF document" in Django"
I am new to web development and trying to create a language translation app in Django that translates uploaded documents. I relies on a series of interconversions between pdf and docx. When my code ouputs the downloaded translated document I get "Error Failed to load PDF document" in my browser. Here is my code: from django.shortcuts import render from django.http import HttpResponse from django.http import JsonResponse from django.views.decorators.csrf import csrf_protect from .models import TranslatedDocument from .forms import UploadFileForm from django.core.files.storage import FileSystemStorage import docx import openai from pdf2docx import parse from docx2pdf import convert import time #remove # Create your views here. @csrf_protect def translateFile(request) : file = '' if request.method == 'POST': form = UploadFileForm(request.POST, request.FILES) if form.is_valid(): uploaded_file = request.FILES['file'] fs = FileSystemStorage() filename = fs.save(uploaded_file.name, uploaded_file) uploaded_file_path = fs.path(filename) file = (converter(uploaded_file_path)) response = HttpResponse(file, content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename="' + filename + '"' return response else: form = UploadFileForm() return render(request, 'translator_upload/upload.html', {'form': form}) def reConverter(inputDocxPath): return convert(inputDocxPath) def translateDocx(aDocx, stringOfDocPath): docx_file = stringOfDocPath myDoc = docx.Document(docx_file) #translation logic myDoc.save(stringOfDocPath) return reConverter(stringOfDocPath) #stringOfDocPath is used as convert() requires file path, not file object(myDoc) def converter(inputPdfPath): # convert pdf to docx pdf_file = inputPdfPath docx_file = inputPdfPath … -
Can we modify a django project from the front end?
I am making an open source suite of web apps using Django. Users can run it on their local servers, heroku, etc. I wish to enable the users to: Update the suite (i.e., the django project) to the latest version, and choose which apps in the project is to be installed. Importantly, I want the users to be able to do this from the front-end. How can I make this happen?