"Вопросы и ответы" Django и Python

19.03.2024
"<Model: ModelInstance>" needs to have a value for field "id" before this many-to-many relationship can be used

Currently getting this error between my UserProfile model and Song model when I try to get all user songs &quot;song = user_prof.songs.all()&quot; and error is the title &quot;&lt;UserProfile: ...&gt;. This is my first time using a through model for two …

19.03.2024
WordPress blog in Subdirectory of Django site on cPanel

I've gone through several similar posts here on StackOverFlow but I can't get it to work. What I want to achieve is to load any url that contains /blog/ with WordPress. I have moved my WordPress instance into a folder …

19.03.2024
ConnectionRefusedError Errno 111 when Django uploaded to Godaddy Server

I dont have any problem in Local host when sending and reciving emails. But when I uploaded the files to the godaddy server, I am getting error when I am trying to send email. I spoke to godaddy support, but …

19.03.2024
How can one enable a mix of authenticated and unauthenticated websockets using Django Channels?

I'm running a Django application with DRF and Channels and I've configured a number of websockets, one of which I need to be open/insecure. However, all I can figure out is how to enable/disable security at the application level, not …

19.03.2024
Django: Views and URLs Configured, but Pages Not Found (404 Error) - only /admin shows

I'm encountering an issue with my Django project. I've set up views and URLs for several pages like 'landing', 'chat', 'impressum', 'sales', 'team', and 'user'. However, when I try to access these pages in the browser, I receive a 404 …

18.03.2024
Django makemessages i got no such file directory error

(myenv) C:\Users\Boss\OneDrive\İş masası\Onlineshop&gt;py manage.py makemessages -l ru CommandError: errors happened while running msguniq msguniq: error while opening &quot;C:\Users\Boss\OneDrive\Is masasi\Onlineshop\myenv\Lib\site-packages\rosetta\locale\django.pot&quot; for reading: No such file or directory In ubuntu server it works but in local i got this error

18.03.2024
Django reverts model value saved by form in POST (Ajax) when I call query by GET (Ajax)

I have a screen with a datatable with the data and I update the values using ajax and then reload it, but in some cases I save the value through a post request, and then when I make a new …

18.03.2024
Django - Create a model that holds aggregated Foreign Key values

I have a Django Model defined as a ServiceEvent, and another defined as Part. class ServiceEvent(Model): date = DateTimeField(null=False, blank=False, db_column='date', default=datetime.now()) vehicle = ForeignKey(Vehicle, on_delete=models.CASCADE) description = TextField(null=True, blank=False, db_column='description') # The contents of the notifications to create for …

18.03.2024
Heroku - Django - How to reduce cool down of keep alive

I have an API that creates a model object whenever an action is true. Slight problem, everytime the API sends some data it creates a connection and these connections dont seem to cool down very quickly. Connections seem to stay …

18.03.2024
Django How to Have an Internal Link on Custom Button Component

I am on DjangoCMS 3.11.3. I am not a Django developer, I primarily do .Net but was asked to help out with CSS and HTML. That went well, so now we are here... We currently have an imported Bootsrap4 Link/Button …

18.03.2024
Django ORM: Case When not working when output is a Subquery producing a list of Ids?

I've been spending an incredible amount of time today on something I don't understand at all. Let me explain: I have a code similar to this one: puzzle_sequence__puzzles = &lt;a subquery&gt; puzzle_sequence__puzzles_3d = &lt;another subquery&gt; MyModel.objects.add_only_3d_puzzle_sequence().exclude(puzzle__in=Case( When(Q(only_3d_puzzle_sequence=True), then=Subquery(puzzle_sequence__puzzles_3d)), default=Subquery(puzzle_sequence__puzzles) )) …

18.03.2024
QUALIFY on a non-window field

As stated here, from 4.2 Django supports fIltering against a window function. I've tried it and Django successfully creates a QUALIFY clause when using a window field in the filter clause. However, if using, let's say, a model field, …

18.03.2024
This Customer doesn't have any saved payment details

Def checkout_payment(request): if request.method == &quot;POST&quot;: user = request.user cart_items = Cart.objects.filter(user=user, is_ordered=False) cart_total = sum(float(item.product.discounted_price()) * item.quantity for item in cart_items) # Convert cart_total to the smallest currency unit and then to integer total = int(cart_total * 100) …

18.03.2024
KeyError in django when i try to migrate

Everytime i try to migrate i get KeyError: ('komaki', 'msg') Traceback (most recent call last): File &quot;C:\Users\EXO\Downloads\Compressed\mathematics-main_2\mathematics-main\maths\manage.py&quot;, line 22, in &lt;module&gt; main() File &quot;C:\Users\EXO\Downloads\Compressed\mathematics-main_2\mathematics-main\maths\manage.py&quot;, line 18, in main execute_from_command_line(sys.argv) File &quot;C:\Users\EXO\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\core\management\__init__.py&quot;, line 442, in execute_from_command_line utility.execute() File &quot;C:\Users\EXO\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\core\management\__init__.py&quot;, line 436, …

18.03.2024
Django annotate and filter

This is a follow up to a previous question but I will include all the detail here. I'm creating a game where one of the elements is that players vote for each other. Here are the models I've set up …

18.03.2024
Converting to SQLAlchemy from Django ORM in Django Rest Framework

I have a DRF application. I have it written in Django Rest Framework. For database handling, I have used Django's Builtin ORM. Let me explain my project structure. I have a django project named TourReview. Inside TourReview I have an …

18.03.2024
Website not able to become responsive in django

Body, html { height: 100vh; margin: 0; padding: 0; } .part1 { position: relative; width: 100%; height: 100%; background-color: black; display: flex; justify-content: space-between; } .tt { margin-top: 20px; margin-left: 20px; width: fit-content; height: fit-content; animation: slideInLeftTt 1s ease forwards; …

18.03.2024
Django Admin "Export selected" button not showing in Admin

I'm trying to enable the &quot;Export selected&quot; button in the Django admin for users to download data as an Excel sheet. I'm using django-import-export but the button isn't appearing. Here's what I've done: Installed django-import-export (pip install django-import-export). Trial 1: …

18.03.2024
Django, Settings module not found on YouStable hostings

I have been deploying django websites on a shared hosting platform (YouStable). With my latest attempt I get a 500 server error page, because it can’t find the settings file. Background I did previously manage to deploy a site that …

18.03.2024
Slider input ranges in html with min and max values inside a table and a for loop

I'm a newbie and battling my first issues with Django, html, js and so on.. I wonder if anyone can help me out here. I have a page where you must enter a series of ranges of attendances and prices …

18.03.2024
Type object 'Project' has no attribute 'objects'

I use django version 5.0.3. And got this error : type object 'Project' has no attribute 'objects'. from django.db import models from account.models import User import uuid # # Create your models here. class Project(): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) …

18.03.2024
Error with if else in html in django application

Good afternoon, i have django application where i have issue on main page there is header in base html, there is 1 button, but with 2 different values as link {% if roleworker %} &lt;li&gt;&lt;a href=&quot;/addservice/&quot;&gt;Add&lt;/a&gt;&lt;/li&gt; {% else %} …

18.03.2024
Python django paginator not displaying items correctly

I developed a simple web app. I have added the paginate_by property to the view. I'm able to show only the first 10 records retrived from the database. If i change the paginate_by property to 20 I always see 10 …

18.03.2024
Change record title in a StackedInline in Django

I am trying to either change or remove the title for each record in an inline, but have not been able to find a way to do it in the docs or by override get_formset. Specifically, I want to change …

18.03.2024
Drop box small files upload slowly

I have a free dropbox subscription and use it in conjunction with django. def upload_image(request): if request.method == 'POST': dbx = dropbox.Dropbox('') file_from = request.FILES['file'] file_to = '/chat/' + file_from.name # Upload the file dbx.files_upload(file_from.read(), file_to) # Create a shared …

18.03.2024
Django async acount takes forever to execute

Consider a django rest framework application which calls an async function like; class SomeViewSet(ListUpdateViewSet): @action( methods=[&quot;GET&quot;], url_path=r&quot;count-async&quot;, detail=False ) def get_count_async(self, request, *args, **kwargs): print('starting') t = asyncio.run(self.aget_count_async(request, *args, **kwargs)) print('ending') return Response(data={ }) async def aget_count_async(self, request, *args, **kwargs): …

18.03.2024
I'm having trouble sending emails on Django using SMTP. Even after trying various tutorials and checking the documentation, nothing seems to work

Here are the possible things that may cause my problem. using django's live server instead of a domain. I know in gmail you can't no longer use less secure apps. I enabled two factor authentication and created an …

18.03.2024
Django 1.7 workaround to use drf-spectacular

I am trying to use drf-spectacular for annotating my existing python api, but i am currently using django-1.7 in my application, and this tool has a dependency of django-2.2 what can be done as quick solution or any suggetion??

18.03.2024
After renaming my table in Django, items from the old table were not moved or deleted

My old table called Quiz was renamed to CarQuizz, the problem is that all items in the table with the old name were neither moved to the new name nor were they deleted. Here is the following log from my …

18.03.2024
Dynamic data in single send | Twilio SendGrid

I am creating a monthly digest for release logs with wagtail CMS as backend, essentially whenever a new post gets created in cms, it will trigger signals.py which inturn should create a mail in single send. Now the problem is …

18.03.2024
Django custom datetime format not working with form fields

I'm working on a Django project where I wanted to add a date format for local usage. As per the documentation, I have updated the settings to use local date time format : Link Settings are as …

18.03.2024
How to test exception handling when unable to trigger an Exception during testing?

I'm working on a Django REST Framework (DRF) viewset that includes exception handling to deal with unexpected errors. The viewset has an action method that retrieves pricing information for servers from a third-party API. Here's a simplified version of the …

18.03.2024
Status code was: 1 Service /usr/bin/chromedriver unexpectedly exited

I was using selenium , chrmoedriver to make screen short of the provided url in my django app. def take_url_screenshot(url): # Ensure the &quot;screenshot&quot; folder exists or create it if not available screenshot_folder = &quot;screenshot&quot; if not os.path.exists(f&quot;{settings.MEDIA_ROOT}/{screenshot_folder}&quot;): print(f&quot;{settings.MEDIA_ROOT}/{screenshot_folder}&quot;) os.makedirs(f&quot;{settings.MEDIA_ROOT}/{screenshot_folder}&quot;) …

18.03.2024
Not getting Social Token when using SignIn with Slack

I am using django-allauth==0.61.1. I have added settings for Slack. I can successfully Signup/Login on my web app using the SignIn with Slack. I get the email, slack_user_id, and username from Slack. But I don't get any social_token for that …

18.03.2024
Django Migration "NodeNotFoundError"

When I run python manage.py runserver this error occurs: Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). Exception in thread django-main-thread: Traceback (most recent call last): File &quot;C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.11_3.11.2288.0_x64__qbz5n2kfra8p0\Lib\threading.py&quot;, line 1045, in …

18.03.2024
Проблема в сайте для блога. Django

У меня сайт для блога. views.py from django.shortcuts import render def index(request): latest_articles_list = Article.objects.order_by('-pub_date')[-5] return render(request, 'articles/list.html', {'latest_articles_list': latest_articles_list}) def detail(request, article_id): try: a = Article.objects.get(id=article_id) except Article.DoesNotExist: raise Http404('Проект не найден') latest_comment_list = a.comment_set.order_by('-id')[10] return render(request, 'articles/detail.html', {'article': …

18.03.2024
View returning user as None

So, I'm creating a user confirmation system where a code is created, stored in the session and send through email I made some prints inside the view that is used to confirm the code and active the user, the code …

17.03.2024
Django.urls.exceptions.NoReverseMatch: Reverse for 'like_post' with arguments '('',)' not found

There is full error: Reverse for 'like_post' with arguments '('',)' not found. 1 pattern(s) tried: ['recipe/like/(?P[0-9]+)\Z'] I suspect there is some issue with post_if but I'm unable to point out exactly whats wrong. i really dont know what to do, …

17.03.2024
AssertionError: 404 != 200 in django testing

I have test code, but it displays error: self.assertEquals(response.status_code, 200) AssertionError: 404 != 200 class TestViews(TestCase): def setUp(self): self.client = Client() self.list_url = reverse('home') self.about_url = reverse('about', args=[1]) def test_index(self): response = self.client.get(self.list_url) self.assertEquals(response.status_code, 200) self.assertTemplateUsed(response, 'job_app/index.html') def test_about(self): response …

17.03.2024
Is it okay to use render partial a lot?

I have a main page called home.html which contains some widgets(Latest comments, banner ads, most popular content and ...) Instead of putting all widgets in the main view. I have isolated each widget using render partial. Does it make sense? …