Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Trying to connect django and ms sql 2019 with django-mssql-backend
I've got this error: django.core.exceptions.ImproperlyConfigured: 'sql_server.pyodbc' isn't an available database backend. Try using 'django.db.backends.XXX', where XXX is one of: 'mysql', 'oracle', 'postgresql', 'sqlite3' ENGINE': 'sql_server.pyodbc', pip freeze shows me this: asgiref==3.7.2 distlib==0.3.7 Django==4.2.4 django-mssql==1.8 django-mssql-backend==2.8.1 filelock==3.12.3 mssql-django==1.3 platformdirs==3.10.0 pytz==2023.3 sqlparse==0.4.4 tzdata==2023.3 virtualenv==20.24.3 i tried use 'mssql' engine, but it doesn't work too -
Related drop-down lists in the Django admin panel?
how do I make linked drop-down lists in the Django admin panel? there are 3 models when you add a category to products, for example, electronics, and only what is related to electronics fell out in the subcategory. class Products(models.Model): name = models.CharField(max_length=255, verbose_name='Название') category = models.ForeignKey('Category', on_delete=models.CASCADE, verbose_name='Категория') subcategory = models.ForeignKey('SubCategory', on_delete=models.CASCADE, verbose_name='subКатегория') class Category(models.Model): name = models.CharField(max_length=255, db_index=True, verbose_name='Название') class SubCategory(models.Model): name = models.CharField(max_length=255, db_index=True, verbose_name='Название') category = models.ForeignKey('Category', on_delete=models.CASCADE) -
Django. Buttons stop working after fetching
I'm trying to fetch text,images from another html file using django and javascript. HTML Code: <body> <nav style="background: #000;"> <div class="top-bar"> <button type="button" id="page1" >Button</button><button type="button" id="page2">Button</button><button type="button" id="page3">Button</button><button type="button" id="page4">Button</button><button type="button" id="page4">Button</button> </div> </nav> <div id="content"> {% block body %} {% endblock %} </div> </body> JS Code: document.addEventListener("DOMContentLoaded",()=>{ const content = document.getElementById("content"); document.getElementById('page1').addEventListener('click', function() { fetch('path/to/index') .then(response => response.text()) .then(data => { content.innerHTML = data; }); }); document.getElementById('page2').addEventListener('click', function() { fetch('path/to/info') .then(response => response.text()) .then(data => { content.innerHTML = data; }); }); document.getElementById('page3').addEventListener('click', function() { fetch('path/to/comms') .then(response => response.text()) .then(data => { content.innerHTML = data; }); }); }) Whenever i fetch the data, my buttons stop working. I've created this file as a test. I'm currently trying to get texts into the content div using sidebar on my main site that im working on. Both files have the same issue. -
how to send post request when browser closing in React
Well, in order to be able to detect the status of browsers, if users are on the site, I want to send a request if they close the browser and change a feature in a model. It should be noted that this model is different from the user model in Django. Also, I'm using Django sessions and SESSION_EXPIRE_AT_BROWSER_CLOSE=True but that's not working. So I use React window.onblur event and that's not working again! I try this code in react but it's not working! let stid:string|null=localStorage.getItem('stationid') useEffect(() => { window.onblur=()=>{ console.log('hello') Api.delete(STATION_ID(stid)).then((res)=>{ console.log(res.data) }).catch(err=>{ console.log(err) }) } return () => { console.log('hello') } }, []) -
Running background tasks in Flask using Django
I have a web application built fully using Flask, at the moment the entire project runs on flask, i'm using many flask libraries for various functionality. However, some of these tasks i am running are very time consuming and take around 5 minutes to finish, and because of this if someone was to run this task and someone else wanted to navigate the website they would be stuck loading while the other lengthy task is done. I'm currently looking for ways to finish running this task in the background so that users can freely navigate the website without being held hostage for 5 minutes while processing is done, I looked into Celery but would rather not use it. Someone instead suggested that I integrate Django to handle this instead, is this feasible, if so how? Here is a quick sample of the current code I have: @app.route("/apple/newoffercodes/<int:appID>", methods=['GET','POST']) @login_required def newoffercodes(appID): application = ApplicationApple.query.filter_by(appleID=appID).first_or_404() package_name = application.appleID form = offerCode() if form.validate_on_submit(): filename = form.file.data result = createSubscriptionOffer(filename) if result == 200 or result == 201: flash("Offer Code Created Successfully","success") return redirect(url_for('offercodes',appID=appID)) else: flash("An error has occurred while creating the offer. Please check Apple Connect.", "danger") return redirect(url_for('offercodes',appID=appID)) return render_template('newOfferCodeApple.html', … -
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 …