Django and Python "Questions and answers"

08.02.2023
How create task with celery in django ? POO issue?

I'm trying to set up a task with Django and Celery. The Celery and Django configuration is okay, nothing to report on that side. However, I have a problem, I think with the writing, of my code in OOP. I …

08.02.2023
How to connect Python Django to Informix DB on a remote Windows Server

I need to connect my Django app to the Informix db I have an Informix db installed on a VM Windows server 2019 Datacenter I can access the db through dbvisualiser on my laptop I installed the Informix client SDK …

08.02.2023
Unable to Pass Django Context Data to HTML View

Can anybody please tell me how I can pass context data to view. I get nothing in HTML page. views.py def cart(request): if request.method == 'POST': return redirect('index') else: if request.method == 'GET': # Recieve local storage product in post_id …

08.02.2023
I wanted to craete a 5 star rating system in django but it keeps getting this error:

I check with django document and But my problem was not solved [08/Feb/2023 15:57:18] "POST /courses/2/learning-django HTTP/1.1" 403 2506 error: Forbidden (CSRF token missing.): /courses/2/learning-django this is my models class Review(models.Model): course = models.ForeignKey(Product, on_delete=models.CASCADE, related_name='reviews') first_name = models.CharField(max_length=50) last_name …

08.02.2023
How to get identityToken from apple account?

I want to create "Sign in with apple" function and using for this drf-social-oauth2. Does anyone knows how to get identityToken from apple account for testing, for example google has OAuth2 playground? Should I create apple developer account?

08.02.2023
Unable to proxy Shiny using Django and Nginx (HHTP Response Code 101)

I am trying to use Nginx and Django to help me serve Shiny applications within my company's internal servers. I am testing everything locally first to make sure all is working properly. I am following two tutorials: <a href="https://pawamoy.github.io/posts/django-auth-server-for-shiny/#proxying-shiny-requests-to-the-shiny-app" …

08.02.2023
How can I view pdf files from an API with Vue Js?

Hello friends I need your support.. I am currently developing an app with django rest framework in the backend and vue js in the frontend.. the app consists of saving pdf files, which I can list in a table.. but …

08.02.2023
Authentication with Microsoft Azure AD in a multi-tenant app

Following the documentation, registered an application with Accounts in any organizational directory. The Tenant where the application resides is in &quot;Default Directory&quot; and has only one user, tiagomartinsperes@gmail.com. Also, the app has user assignment (<a href="https://learn.microsoft.com/en-us/troubleshoot/azure/active-directory/error-code-aadsts50020-user-account-identity-provider-does-not-exist#cause-5-app-requires-user-assignment" rel="nofollow …

08.02.2023
How do I affect a single looped element in Django html?

I'm building an app in Django, using Bulma for styling. I have a Polishes model that has a favorites field, which references the User (users can save polishes to their list of favorites): models.py: class Polish(models.Model): name = models.CharField(max_length=100) image …

08.02.2023
Как в написании теста проверить контекст страниц через цикл в django?

Имеется потребность объединить код для страниц в одну функцию и проверять контекст страниц через цикл. class PostPagesTests(TestCase): @classmethod def setUpClass(cls): super().setUpClass() cls.user = User.objects.create(username='user') cls.group = Group.objects.create( title='Тестовая группа', slug='test-slug', description='Тестовое описание группы', ) cls.post = Post.objects.create( text='Тестовый текст поста', …

08.02.2023
Django: TemplateSyntaxError - Could not parse the remainder

Exception Value: Could not parse the remainder: '['image/jpeg',' from '['image/jpeg',' Why am I getting this TemplateSyntaxError for the code below? {% for file in resource.files.all %} {% if file.file.content_type|lower in ['image/jpeg', 'image/png', 'image/gif'] %} &lt;a class=&quot;resource-image&quot; title=&quot;{{ file.id }}&quot; href=&quot;{{ …

08.02.2023
Change color of a field in a table depending on how much time is left for the user to pay with Django

I am trying to change the color of a field in a table depending on how much time is left for the user to pay, if there are 7 days to pay it should change to yellow and if it …

08.02.2023
Django why model foreign key cascade will not trigger delete?

There two basic ways to do something when an instance gets deleted: Overwrite Model.delete Signal I used to reckon both of them serve the same purpose, just provides different ways of writing, but works exactly. However, in this …

08.02.2023
Django template -TemplateSyntaxError

I am a beginner in Django world. When I try render my login.html template I'm facing this problem even there is a closing block. TemplateSyntaxError at /login/ Invalid block tag on line 12: 'else', expected 'endblock'. Did you forget to …

08.02.2023
Непонятное всплывающее окно с подтверждением логина пользователя при смене парля Django

Сделал кастомную смену пароля но теперь при обновлении страницы после смены пароля всплывает окно с выбором логина пользователя которое ничего не решает :(<img src="https://i.stack.imgur.com/JpoSq.png" alt="введите сюда описание изображения" …

08.02.2023
Django-select2 not loading css maybe or just form looks bad

I downloaded and configured django-select2 and for some reason it looks disgusting not like it should be I check all settings and everything should be all right I guess its just some css files are not loading but in terminal …

08.02.2023
ViewSet class variable

Now I have the following logic implemented for a GET request in Django Rest Framework: class SomeViewSet(mixins.ListModelMixin, GenericViewSet): count = None def get_queryset(self): query_set = ... # some_logic self.count = query_set.count() return query_set def list(self, request, *args, **kwargs): response = …

08.02.2023
How to install the node in Dockerfile?

I want to install the node v18 in on AWS Linux Prerequisite I have Django and frontend React system. So, I want to use node when installing frontend. If I use make Dockerfile such as From node:18 it works, …

08.02.2023
How to serialize Django model with 2 or more foreign keys?

I have two models in models.py: from django.db import models from django.contrib.auth.models import User class Course(models.Model): name = models.CharField(max_length=100) description = models.TextField() cost = models.IntegerField() course_image = models.ImageField() def __str__(self): return self.name class PurchasedCourse(models.Model): purchased_by = models.ForeignKey(User, on_delete=models.CASCADE) purchased_course = …

08.02.2023
Django choosing which model to use in Django admin

I have three models models.py class Cluster(models.Model): blockOption= (('IMG', 'IMG'),('DESC', 'DESC'),) block = models.CharField(max_length= 100, choices=blockOption) order= models.IntegerField(null=True) post = models.ForeignKey(Post, verbose_name=('Link to Post'), on_delete=models.CASCADE) class Image(models.Model): src = models.ImageField(verbose_name=('Imagefile')) captions= …

08.02.2023
Login issue in https in django 1.6

In django 1.6 , when we tried to login using django login then after successful login , user is redirected to same login page. only change is , we change the http protocol to https.

08.02.2023
How do i get default date to my payload in django views

I am trying to create a payment API and part of my request body on postman is date but I want my programme to pick a default date now as my date so user do not need to enter date …

08.02.2023
Getting Logical Error on Django ORM Query, the total is not matching with counts of all age group

` class OPDStatReportView(ListAPIView): filter_backends = [DjangoFilterBackend] serializer_class = OPDStatReportSerializer filterset_class = OPDStatReportViewFilterSet def get_queryset(self): query_dict = {} for k, vals in self.request.GET.lists(): if k != &quot;offset&quot; and k != &quot;limit&quot;: if vals[0] != &quot;&quot;: k = str(k) if k == …

08.02.2023
Django channels with redis in WSL2

I have a redis installation running inside the windows subsystem for linux. It is working finde, but I cannot connect to it from django-channels. In my WSL I started redis and when using a normal terminal and python in Windows …

08.02.2023
Django: password reset not sending any email

I am trying to implement the 'password-reset' functionality using django. I set up my urls: path('account/reset_password/', auth_views.PasswordResetView.as_view(), name='reset_password'), path('account/reset_password_sent/', auth_views.PasswordResetDoneView.as_view(), name='password_reset_done'), path('account/reset/&lt;uidb64&gt;/&lt;token&gt;', auth_views.PasswordResetConfirmView.as_view(), name='password_reset_confirm'), path('account/reset_password_complete/', auth_views.PasswordResetCompleteView.as_view(), name='password_reset_complete'), and the Settings.py: EMAIL_FILE_PATH = f&quot;{BASE_DIR}/sent_emails&quot; EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = …

08.02.2023
In django-formset pypi package Uncaught (in promise) SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data

When i try implement django-formset package selectize and preselect option show the error : Uncaught (in promise) SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data plz help to solve this issue

08.02.2023
Restart Django server automatically at specific time

Is there anyway to restart a local django server automatically everyday at a specific time? Thanks

08.02.2023
How to skip exception and continue to send the exception to sentry (Django)?

I want to be able to send errors to sentry while skipping the errors. The following can skip the error, but how can I make Sentry catch ValueError while achieving this? data = [1,2,3,4,5] new_data = [] def test(data): if …

08.02.2023
Django - Let the user select multiple database entries and use that data in the next page

I would like to create a ListView, where the user can select certain database entries (see image below). The data connected to these entries would …

08.02.2023
How to get the top frequency

I have model class RawFrequencyDicts(Base): __tablename__ = &quot;raw_frequency_dicts&quot; id = Column(types.UInt64, primary_key=True) item = Column(types.String) lemmatized_text = Column(types.String) lemmatized_text_no_ordered = Column(types.String) frequency = Column(types.Int64) count_words = Column(types.Int64) mark_up = Column(types.Int64) domain_id = Column(types.Int64) language = Column(types.String) run = Column(types.Int64) run_desc …

08.02.2023
HTMX method not activated on select from list action in template (view does not see HTMX)

Good afternoon I have a micro Django app. In which I want to configure the ability to update the element using the [HTMX] method. I have a small form in a template - which is based on selecting an item …

08.02.2023
Эрик Мэтиз "Изучаем Python" Глава 18 Знакомство с Django

Вопрос по книге &quot;Изучаем python&quot; На административном сайте django после регистрации Entry (стр. 406) в раскрывающемся списке для выбора темы вместо Chess Rock Climbing у меня Topic object (1) Topic object (2) admin.py: from django.contrib import …

08.02.2023
Beginner Django: How to order a queryset by a property

I have a model: class Project(models.Model): title = models.CharField(&quot;Project title&quot;, max_length=128) start_date = models.DateField(&quot;Project start date&quot;, blank=True, null=True) end_date = models.DateField(&quot;Project end date&quot;, blank=True, null=True) @property def has_ended(self): return self.end_date is not None and self.end_date &lt; timezone.now().date() …

08.02.2023
Can't delete django-vote

I am working on a small university project. And I want to add voting to my app. I've decided to use django-vote for it. Here is the documentation: https://pypi.org/project/django-vote/ Upvoting works fine. The problem is whenever I …

08.02.2023
Pip Version Upgrade

Pip install --upgrade pip I want to update with the command, but I am getting an error, the error is below. Hello, pip install --upgrade pip I want to update with the command, but I am getting an error, the …

08.02.2023
Django Create Model Instance from an Object

I am working on a Django Daily Saving App where Staff User can create Customer Account, and from the list of the Customer Accounts there is link for Deposit where staff user can add customer deposit. The issue is that …

08.02.2023
How to create Python: Create automated strictly-designed multi-page .pdf report from .html [closed]

Can anyone design me Python: Create automated strictly-designed multi-page .pdf report from .html I have foudn this link usfeul but i need someone to do it for me please, here is the link: Python: Create automated strictly-designed multi-page .pdf …

08.02.2023
How can I detect a file is malicious during upload using VirusTotal API in Django Rest Framework

Working on a Django app. I have files being uploaded by users through the React front-end that end up in the Django/DRF back-end. How can I detect the file is malicious during upload using VirusTotal API in Django Rest Framework. …

08.02.2023
How to get OTP in django admin panel only?

So i am working on REST API and doing KYC verification of aadhar card. This is my code: admin.py def save_model(self, request, obj, form, change): customer_id = obj.customer_id customer_object = Customer.objects.get(id=customer_id) first_name = customer_object.first_name middle_name = customer_object.middle_name last_name = …

08.02.2023
Django : use @property in success_url KO . while using it with get_success_url is OK (class based view)

I found a workaround for my issue but I need to know why the first above case doesn't work. I need to pass a parameter (reman_pk) to my view but when I try : class RepairCreateView(LoginRequiredMixin, CreateView): @property def reman_pk(self): …