Django and Python "Questions and answers", page 1388

06.08.2021
How to fix: ProgrammingErrorsAlreadyExists'django_content_type'

When I run the server it gives this message on console: "You have 18 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions. Run 'python manage.py migrate' to …

06.08.2021
Unable to add values at features in django admin panel

I am new in Django and now I am working with manipulation of database in django admin panel. While playing with features I am unable to add values in features. There is no key and after saving it leaves empty …

06.08.2021
Getting multiple countdown timers from querysets using django models and javascript

I really don't know how to push on with this, the idea is an investment platform where the user can have multiple investments and each investment has a due date enter image description here this image shows …

06.08.2021
Get Django Custom user model listed under admin app `Authentication and Authorization`

Note my question is similar to this one, however that answer recommend not calling the customised user model User, whereas the official docs and this issue do. I created a custom User model …

06.08.2021
Store data just for a single session in Django?

I am currently creating a website with Django and I came across the following question: I want to store data the user enters (a string, for example a name or the user's age), BUT it must be "deleted" when the …

06.08.2021
How to i get session value userid in adddomainwiseprojects - django(using inline formset method)

Here i have attached views.py where add_projectdomain fields are added by importing models, here how can i get the loginid i.e. session key(userid) (as i have got in company_details view by using reuest.session.get method) in Add_domainwise projects form and save …

06.08.2021
Django slow inner join on a table with more than 10 million records

I am using mysql with Django. I am trying to count the number of visitor_pages for a specific dealer in a certain amount of time. I would share the raw sql query that I have obtained from django debug toolbar. …

06.08.2021
Mock or override values in apps.py (Django) for testing

Typically I'd set a value in settings.py and then use @override_settings in tests to override it. Is there any similar mechanism that exists for overriding settings in apps.py when using app_config? For instance # apps.py class MyConfig(AppConfig): SOME_VAR = "SOME_VAR" …

06.08.2021
Pagination does not work for numbers in between and also for reverse in django

I am filtering my data, and also applying paginator, I have found some solution and I used it but it is working only for the next button and not for previous and button numbers in between i.e. for {{i}} (Django, …

06.08.2021
Не проверяется user.is_authenticated на главной странице

Шаблон с кодом наследуются с хедера главной страницы для всех приложений {% extends "mainpage/header.html" %} {% block content %} Но почему-то только на главной странице условие проверки на авторизацию просто не работает, на остальных страницах все отображается корректно {% …

06.08.2021
Django testing how to make a request as logged in user?

In Django tests, I want to log in and make a request. Here the code def test_something(self): self.client.login(email=EMAIL, password=PASSWORD) response = self.client.get(reverse_lazy("my_releases")) self.assertEqual(response, 200) But the code doesn't work and returns AttributeError: 'AnonymousUser' object has no attribute 'profile' …

06.08.2021
File deletion when cloning a model that contains an ImageField

When I save() a model that contains an ImageField, the post_save signal of the model base deletes the file that was previously associated with the ImageField which is fair enough because the file has changed to a new value. However, …

06.08.2021
Is It possible to listen to Rest API Endpoint using django channels?

Goal is to send the serialized data of the created object of POST Method! Request will come from Android/IOS app built with Flutter/Dart I am trying to use Django Channels Rest Framework. But I am not sure if it is …

06.08.2021
Angular app keeps saying message does not exist

I'm building a chat app with Angular and Django using the get stream tutorial. https://getstream.io/blog/realtime-chat-django-angular/ However, I'm trying to run the app to create the chat view but it keeps saying 'messages' does not exist at the …

06.08.2021
How to show success message on keyclock page in django?

{% if messages %} <ul class="messages"> {% for message in messages %} <li {% if message.tags %} class="{{message.tags}}" {% endif %}> <i class="bi bi-exclamation-triangle-fill"></i> {{ message }} </li> {% endfor %} </ul> {% endif %} I want to show …

06.08.2021
Running Unit testing in Django

I'm running a unit test in Django but keep getting an error File "C:\****\views.py", line 21, in post s = str(points['string_points']) KeyError: 'string_points' Command Used: python manage.py test The structure of my test code looks as follows: class …

06.08.2021
Call manager of select_related field

I have the following example: class Profile(models.Model): ... class Person(models.Model): profile = models.ForeignKey(Profile, ...) I have complex Model manager for Profile class and I built a view to list a big amount of Person. I try to compute everything …

06.08.2021
Nested table rows

I'm working on a project that is still in its early stages using Django and Jquery. I would wish to create a nested table in that team leaders have people assigned to them. So far I have been able to …

06.08.2021
Django, Foreign key not getting filled with session data

Im trying to fill my foreignkey with the user that is logged in, but i have seen alot of way but they havent worked for me, does anyone know what im doing wrong? and how i can fix it? View: …

06.08.2021
Use model's value to create a Django form

I have a model which is as follows: class BloodTestType(models.Model): type = models.CharField(max_length=200) def __str__(self): return str(self.type) class BloodParameters(models.Model): type = models.ForeignKey(BloodTestType, on_delete=models.CASCADE) parameter = models.CharField(max_length=200) minimum_value = models.FloatField() maximum_value = models.FloatField() unit = models.CharField(max_length=200) required = models.BooleanField(default=True) GENDER_CHOICES = …

06.08.2021
Django- Ajax returning wrong data

I'm building a webcomic using Django framework. The problem that I have now is to display chapters from different issues with AJAX. Let's say we have issue#1 and issue#2, when user clicks on issue#1 cover, it displays chapters of issue#1. …

06.08.2021
Using multiple connection vs single connections in sql python

I am using pymysql to connect to sql like this: con=pymysql.connect(...) cur=con.cursor() Well I am using flask web framework for some use. I defined the connection object as a single time and pass it to other function …

06.08.2021
AlueError: Cannot assign value-field-must-be-a-object-instance

I get the following error ValueError: Cannot assign "(<UserProfile: testUser>, True)": "Comments.profileInfo" must be a "UserProfile" instance. What I am doing is unit testing : def create_user_profile(user): profile = UserProfile.objects.update_or_create(gender = 'F', defaults={ 'user': user}) return profile def create_comment(profile, …

06.08.2021
Django - Able to makemigrations and migrate locally but not on Heroku

There seems to be a problem with migrating my models on the Heroku server. I am able to run python manage.py makemigrations and python manage.py migrate just fine and I am able to view my site on my local machine …

06.08.2021
Ошибка при попытке вывести из статических файлов изображение

У меня появилась проблема, которая видна на скриншотах: Сам проблемный html файл: Там видно и окно отладки и ещё структура проекта. Вот код файла urls.py from django.contrib import admin from django.urls import path from …

06.08.2021
Django test field that slug is created from

I'm trying to write a test for UpdateView of Model which has a title and slug. When I try to test my view I can't recive a response because save method throws an ERROR Reverse for 'books-delete' with arguments '('',)' …

06.08.2021
Distribution of Django based application [closed]

I want to distribute a Django based application to run on customer's intranet. I want to give a simple way to install the application, one script or tgz to install everything needed, including a http server and a database. What …

05.08.2021
Как сделать url с двумя slug?

Как сделать url для товара со своим слагом, и с слагом категории. Например: category/slug категории/slug товара/ from django.db import models from django.contrib.auth.models import User from django.urls import reverse class Profile(models.Model): user = models.ForeignKey(User, unique=True, on_delete=models.CASCADE) wishlist = models.ForeignKey('Product', on_delete=models.CASCADE, blank=True, …

05.08.2021
Создание двух таблиц с неповторяющимися между собой id primary_key в DJANGO ORM

Необходимо создать две таблицы у которых не будут совпадать id в поле primary_key. Например, в таблицу1 мы добавляем новый элемент у которого id будет = 1. Затем в таблицу2 добавляем элемент у которго id будет продолженим последовательности и равен 2. …

05.08.2021
Cannot import name 'FieldDoesNotExist' from 'django.db.models.fields' (/usr/local/lib/python3.8/site-packages/django/db/models/fields/__init__.py)

Полная ошибка выглядит так File "/usr/local/lib/python3.8/site-packages/django/template/backends/django.py", line 123, in get_package_libraries raise InvalidTemplateLibrary( django.template.library.InvalidTemplateLibrary: Invalid template library specified. ImportError raised when trying to load 'mptt.templatetags.mptt_tags': cannot import name 'FieldDoesNotExist' from 'django.db.models.fields' (/usr/local/lib/python3.8/site-packages/django/db/models/fields/__init__.py) насколько я понял, мне нужно исправить строчку from …

05.08.2021
Как добавить атрибут lastmod для index sitemap в django

Мне нужно добавить lastmod для сайтмапы index, сейчас sitemap.xml выглядит так: <sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" <sitemap> <loc>localhost:8000/sitemap-pages.xml</loc> </sitemap> </sitemapindex> То есть, необходимо добавить тег <lastmod></lastmod>, вот мой urls.py sitemaps_pages = { 'pages': sitemaps.PageViewSitemap, 'life': sitemaps.LifeViewSitemap, 'lifes': sitemaps.LifesSitemap, 'novosti': sitemaps.NewsViewSitemap, 'novost': sitemaps.NewsSitemap, …

05.08.2021
Python manage.py makemigrations выводит ошибку

System CheckError: System check identified some issues: ERRORS: ?: (urls.E004) Your URL pattern (<module 'chat.urls' from 'D:\djangoproject\web_ chat\chat\urls.py'>, None, None) is invalid. Ensure that urlpatterns is a list o f path() and/or re_path() instances. HINT: Try using path() instead of …

04.08.2021
Нейминг и архитектура в django

Хочется найти фундаментальные материалы, возможно книги, по организации архитектуры проектов с django и впринципе python. Существует множество статей которые рассматривают кодстайл в каких-либо локальных моментах, та же самая документация и PEP (например https://docs.djangoproject.com/en/dev/internals/contributing/writing-code/coding-style/). Но хочется посмотреть какой-либо …

04.08.2021
Django передать переменную из шаблона во views

Никак не получается передать переменную(user.username) из шаблона во views, выбрал простой вариант передать через запрос, ошибок не выдает, но и переменная не приходит: template: <form action="{% url 'cabinet' %}?user.username={{user.username}}" method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit" class="w-50 …