Django and Python "Questions and answers", page 1619

13.08.2021
Как сделать, чтобы ответы на форму выводились в админпанели?

Нужна помощь, как сделать так, чтобы ответы на форму, которая расположена на сайте, выводились в админ панели и это все можно было просматривать, заранее спасибо(пишу при помощи библиотеки django)

13.08.2021
Приложение в Django не отображает содержимое приложения, как это исправить?

Кнопка Блог не отображает информацию о количестве написанных блогов и сами блоги (при добавлении номера блога в адресной строке ничего не появляется. [ # all_blogs.html {% extends "portfolio/base.html" %} {% load static %} <h1 id="blogtitle" class="font-weight-bold …

13.08.2021
Обработка обратного вызова API Сбербанка

Есть api сбербанка. Они предоставили адрес для обратного вызова. На него, после проведения оплаты, приходит GET запрос с содержимым, которое меня интересует. Не могу разобраться, как получить этот запрос в переменную. Есть ли в целом возможность узнать какие именно запросы …

13.08.2021
Как context попадает в name,html, через include

Я сейчас прохожу курс основ по Django у меня наверняка глупый вопрос, но меня он вводит в замешательство сейчас. Вопрос: Есть некий index.html в него мы через класс News(ListView) кидаем некий context,выводим новости итд. Я хочу вынести пагинатор в Templates/inc/_paginator.html …

12.08.2021
Django передача переменных в скрипт js

Много искал, не нашел ничего лучше, как передавать массив в скрипт js через <script type="text/javascript"> massages = {{ notification_messages|safe }}; </script> Все прекрасно работало, в js была доступна переменная notification_messages, до тех пор, пока браузер не стал хешировать все …

12.08.2021
Cannot import name 'FieldDoesNotExist' from 'django.db.models.fields'

Хочу сделать миграции, пишу python manage.py makemigrations и получаю это Полный Traceback выглядит так: File "/Users/work/Library/Python/3.9/lib/python/site-packages/django/template/utils.py", line 66, in __getitem__ return self._engines[alias] KeyError: 'django' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/Users/work/Library/Python/3.9/lib/python/site-packages/django/template/backends/django.py", …

12.08.2021
Пропала панель пользователей Django admin

Я новичок в django и это мой первый проект.Создаю сайт на django с возможностью регистрации пользователей. Но когда решил просмотреть список пользователей, в админ части уже не было панели &quot;Пользователи&quot;. Как так? <img src="https://i.stack.imgur.com/JigN2.png" alt="введите сюда описание …

12.08.2021
Почему при записи QuerySet в переменную приходит пустота (django console)?

Такая проблема: Делаю проект на django. В процессе проверяю некоторые вещи, используя интерактивную консоль django, и вот какую проблему я заметил: Есть объект x - Объект модели, у него есть …

12.08.2021
Django: Server Error (500) при выполнении функции после переноса на сервер

Локально всё работает прекрасно. После переноса на сервер, при нажатии на кнопку, функция не выполняется, а выходит ошибка Server Error (500). В чем может быть проблема и как исправить? views.py from django.shortcuts import render, redirect, get_object_or_404 from .models import Fertig …

12.08.2021
Добавление кнопки в админку django для запуска команды manage.py

Django3 Необходимо добавить кнопку в админку которая будет запускать команду manage.py my_command (команда по запуску скрипта python который обновляет данные в таблице) я добавил шаблон и кнопка появилась там где мне надо: templates/.../change_list.html {% extends 'admin/change_list.html' %} {% block object-tools …

12.08.2021
Получить результат сложения полей формы в процессе заполнения полей

Прошу помощи в решении реализации формы калькулятора услуг. Форма работает и сохраняет все необходимые данные в базу. Но мне бы хотелось предоставить пользователю результат сложения полей еще во время заполнения формы. Т.е. выбрал тариф, получил цену, указал количество рабочих мест, …

12.08.2021
Форма Django устанавливает placeholder в CharField вместо значения

Предположим, у меня есть следующая простая форма: class UserForm(Form): first_name = CharField(label='First Name') last_name = CharField(label='Last Name') class UserForm(Form): first_name = CharField(label='First Name') last_name = CharField(label='Last Name') Также есть некоторая пользовательская валидация. Когда пользователь отправляет недопустимые данные, Django …

12.08.2021
Изменить фотографию django-avatar по умолчанию

Я использую django-avatar. и я хочу изменить изображение по умолчанию dajngo-avatar. Я пробовал AVATAR_DEFAULT_URL="https://path-to-image.jpg", но это не работает. django-avatar django-avatar dajngo-avatar AVATAR_DEFAULT_URL="https://path-to-image.jpg"

12.08.2021
Запись запроса внутри модели

Я хочу написать запрос, в котором, если статус Complete все true, то complete внутри модели Order должен быть автоматически true. Могу ли я написать запрос внутри модели Order, используя какие-то методы или что-то еще? И можете ли вы предложить какую-нибудь …

12.08.2021
Django Check constrain prevent save string in json fileld

How can I prevent saving string literal in JSON field? class MyModel(models.Model): settings = JSONField(&quot;Additional settings&quot;, default=dict, blank=True) Now I can do this inst = MyModel.objects.get() inst.settings = 'some string' inst.save() but some login expect dict. now I …

12.08.2021
Django permissions instead of groups

We have multiple positions in the hierarchy of the company : such as director of sales, salesperson, restaurant director and let say maitre d'hotel, however if we have a follow up or a memo some might be a good fit …

12.08.2021
ElephantSQL and Django not working together, atuhentication failed

I have bumped into the following problem and still don't know how to fix it. For the record I am using mac. I would like to connect my djnago app to an elephantsql database, so I have changed the database …

12.08.2021
Issue httpresponseredirect:unable to redirect to homepage

I’m keeping getting this redirect wrong either I got the code wrong or it keeps running in an infinite loop. urls.py first app urlpatterns = [ path(&quot;&quot;,views.pomo,name=&quot;pomo&quot;), path(&quot;agenda/&quot;,views.agenda,name=&quot;agenda&quot;), path(&quot;notes/&quot;,views.notes,name=&quot;notes&quot;), ] urls.py main urlpatterns = [ path('admin/', admin.site.urls), path(&quot;&quot;, …

12.08.2021
Как вывести в context['title'] страницу из paginate_by (listview), чтоб было Сайт -> Страница: 2?

Всем привет, хотелось бы узнать, как сделать так, чтоб при условии, что мы находимся на 2 странице, нам выводилось в {{title}} в ListView &quot;Сайт -&gt; Страница: 2&quot; Именно начинать выводить со второй страницы class HomeListView(ListView): context_object_name = 'posts' paginate_by = …

12.08.2021
How do i store stored data in a new form?

Currently im facing a issue where this my edit webpage have to get the data out of the db and appear in a form (this form looks exactly like the add new device form page). How my add device page …

12.08.2021
Mocking SQLite database calls for DJango ORM pytest

Below is the code from one of my django view which uses django ORM to fetch data, however running the same from pytest gives error: FAILED tests/test_views.py::TestViews::test_trendchart_view - AttributeError: 'NoneType' object has no attribute 'metricname' metrics = Metrics.objects.all() …

12.08.2021
View detailed view of model item directly in django admin

Django shows list of model items in admin panel, but don't want to show the list but I directly want to show the detail view . How can i do this ?

12.08.2021
Automatic id not getting assigned (Django PostgreSQL)

I am using a PostgreSQL 12 backend with Django 2.2. For one particular model of a complex project (with several apps and dozens of models), a model is not assigning the auto-incremented ID anymore. The model itself is innocuous: class …

12.08.2021
AuthCanceled at /oauth/complete/facebook/

Request Method: GET Request URL: http://www.example.com/oauth/complete/facebook/?granted_scopes=public_profile&amp;denied_scopes&amp;code=AQBoM1W9l8X1lnsYCaspOQVi1nxYG1Vh3IDkdXOw1dcW5tG6dNfjzbrQ0APZlpIquhjdeMLsQ6Wd_vktM_7pCv2GI-Uqsvya7iVm7jdnX2nbaMPkF2f7JgznpVZLh5oRXQv2AvG0Syu-GZ4skYp2ZVDNvuWdfEu-OnpN_d0GsY-P07BwwsCIlIwL6CrR0GCjNK3_wSC4c8BTWXS9fPeKd7rQOZB863x9wEwVQDjCx-LgxL41_rGJlIbk01pFWPCze5GZvsFJe8xAvbzjO9E1Jrq6KGf2pddF4-78q3xLz-IG3Ary31DoSHS2POmb-KrPvMQvK96ouft-vUBUFcoEe83P&amp;state=nTPuVRtqNf8wSmU9SiFRYozizutSAoAd Django Version: 3.2.5 Python Version: 3.8.10 Installed Applications:[ 'admin_interface', 'colorfield', 'carparking.apps.CarparkingConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'social_django' ] Installed Middleware:[ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'social_django.middleware.SocialAuthExceptionMiddleware' ] Traceback (most recent call …

12.08.2021
Jupyter runtimeerror

How can I solve this error? seis_model = Model(vp=reshaped, origin=(0., 0., -1000.), spacing=(10., 10., 10.), shape=shape, nbl=30, space_order=4, bcs=&quot;damp&quot;) RuntimeError: Couldn't find libc's posix_memalign to allocate memory

12.08.2021
Django: Can't save image from template

If I try to save image from admin site, it works properly. But I'm trying to save image from template, and its not working. here is my code models.py: class About(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) profilePicture = models.ImageField(upload_to='images/profile/', default = …

12.08.2021
How can I exclude entries if the max of my JSON Field values is 0?

I have this kind of JSON Field called fieldA : `{'test': 0, '1': 0, 'number': 0} And I would like to exclude if the max of the values is 0. I thought to use that if A is my …

12.08.2021
How to get the data from views to template Django

From my model I am uploading a file , In my views I perform some operations on the file .I am using DetailView of CBV of Django , In which I get one object and perform some operations on it …

12.08.2021
Cannot Edit Form in Javascript With Django

I'm trying to edit a form on this site with Django, and save the edits using Javascript (but not mandating a page refresh). When the user clicks 'edit' on the page, nothing happens. No console errors. I think the issue …

12.08.2021
Add a second attribute/category column to Django administrator GUI

I'm learning Django right now and I made this class called Clowns. On the Django Admin page I made two test objects. I made four attributes(dunno what they're called lol) for clowns. They …

12.08.2021
Relation "users_user_groups" does not exist LINE 1: ... "auth_group"."name" FROM "auth_group" INNER JOIN "users_use

I have created Custom User Model in Django as follows, When I got Admin and click on User and then a particular user it gives me error : relation &quot;users_user_groups&quot; does not exist LINE 1: ... &quot;auth_group&quot;.&quot;name&quot; FROM &quot;auth_group&quot; INNER …

12.08.2021
Does using a foreign key as a column in the django admin interface create a new database query for each row?

I have a model relationship that looks like the following: class Author(Model): first_name = CharField() class Book(Model): title = CharField() author = ForeignKey(Author) I want an admin interface like this: class BookAdmin(ModelAdmin): list_display = ('title', 'author_name') def author_name(self, obj): …

12.08.2021
Flutter and Django, notification I need some north

I'm starting a project, my Django app communicates and receives data from an API, it might send notifications to the users when it receive something, I also wanna build a mobile app that receive these notifications, can someone indicate me …

12.08.2021
Send the value of a disabled select in a form with a hidden input

I have a Django form, one of the parts is populated like this: &lt;select {% if 'ba1' in widget.name or 'bs1' in widget.name or 'pm2' in widget.name %} disabled {% endif %} id=&quot;{{ widget.attrs.id }}&quot; name=&quot;{{ widget.name }}&quot; {% …

12.08.2021
Can I build a basic website to access my resume but slowly customize it using python to learn and showcase my skills?

I&quot;m not entirely certain what I'm trying to do is doable. I want a ready made website that I can make live fairly quick but later modify it with python code. I have basic python knowledge and used it, as …

12.08.2021
Why doesn't it return an HttpResponse even though render returns?

My html template and urlpatterns are checked OK, but it just doesn't response anything and saying like this The view search.views.search_list didn't return an HttpResponse object. It returned None instead. So what's wrong? If I return HttpResponse('hello world'), it still …

12.08.2021
AttributeError: object has no attribute 'decode' when using Selenium and Django

I have a Django crawler that stores all URLs in the database from a site and I'm trying to get Selenium to scrape the content of each of the URLs but I'm getting this error object has no attribute 'decode' …

12.08.2021
Permission error when writing files in django + ubuntu + apache

Following is the error message I receive when I save x.mp3 via django : Exception Type: PermissionError Exception Value: [Errno 13] Permission denied: 'x.mp3'

12.08.2021
Django Show Distinct Values in List

I'm trying to create a table that shows only the unique values based on a specific column. The following code does not present any errors, but does not show the unique values as intended - any ideas where the mistake …

12.08.2021
Creating a .java popup for Django Project

Please note - this is (to the best of my knowledge) not a duplicate question; there have been similar questions in the past but they involve applets and other features which no longer exist. I have a working .java file …