Django and Python "Questions and answers", page 1621

11.08.2021
ImportError: cannot import name 'FieldDoesNotExist' from 'django.db.models.fields'

Получаю такую ошибку File "/usr/local/lib/python3.8/site-packages/django_filters/utils.py", line 10, in <module> from django.db.models.fields import FieldDoesNotExist ImportError: cannot import name 'FieldDoesNotExist' from 'django.db.models.fields' (/usr/local/lib/python3.8/site-packages/django/db/models/fields/__init__.py) зашел в файл с этим кодом, изменил django.db.models.fields на django.core.exceptions, но в логах никаких изменений, будто бы я …

11.08.2021
Pass parameters in URL to Django Admin add_view

I need to pass a parameter in the URL to the Django Admin add view, so that when I type the URL: http://localhost:8000/admin/myapp/car/add?brand_id=1, the add_view reads the brand_id parameter. I want to use this so that I can set a …

11.08.2021
How to serialize tthe foreign key field in django rest framework

I working on project with drf where I'm getting serializer data as follows which is absolutely fine: { "message": "Updated Successfully", "status": 200, "errors": {}, "data": { "id": 8, "user": 2, "item": 1, "quantity": 4, "created_at": "2021-08-11T13:49:27.391939Z", "updated_at": "2021-08-11T13:51:07.229794Z" } …

11.08.2021
Django render many to many attributes after query, display None

I am using slug to query the model, and render result in HTML. The code is unable to render actual name of region, it just return None Model class Region(models.Model): name = models.CharField(blank=False, unique=True) def __str__(self): return self.name class Theme(models.Model): …

11.08.2021
Build MultipleChoiceField form based on view request with Django

I have a table named Appointment with : timeslot id ; student id; teacher id ; date ; timeslot (integer) ; I would like to create multiple rows in the table TimeSlot based on MultipleChoiceField form. But the …

11.08.2021
Django celery - Restart the task when it's completed

@app.task def Task1(): print("this is task 1") return "Task-1 Done" Just take an example I want to restart the task when it's completed

11.08.2021
How to fix heroku app deployment? App runs locally but not online

I'm trying to deploy a dog breed classifier django app on heroku, but for some reason heroku doesn't seem to find the path to the exported pkl model file. Whenever I run locally, everything works fine. I'm using the "path" …

11.08.2021
Is there a workaround for Django's `ModelDoesNotExist` error in a situation like this?

So I get a ModelDoesNotExist error when I run manage.py runserver because in a file in my directory, I make a query to a table which has not been populated yet. def __init__(self): self.spotify_object = SocialToken.objects.get(account__provider="spotify") The above is …

11.08.2021
How to display text in input in javascript?

I'm trying to save a price, but the price text doesn't appear in the input box. Where is the problem? How can I save the price? view price = form.cleaned_data['price2'] form price2 = forms.IntegerField(error_messages={'required': "1개 이상 선택 시 참여가 …

11.08.2021
How can we keep only delete operation in django-simple-history

We can keep the history of insert/update/delete operation in any table with django-simple-history in a Django Application. Is there any setting or configuration to keep only the history of deletion operation in a table with django-simple-history?

11.08.2021
Replace html web page by ajax return data on Django 3.2

I managed to use ajax to change the content of my web page without updating it but the only problem is that I cannot replace the old content with the new one which I return, when I do consol.log (data …

11.08.2021
Bad Request 400 - Django REST Framework

I have my api in Django and Django REST framework (DRF). Here is my settings file: DEBUG = False ALLOWED_HOSTS = ['http://localhost:3000', 'http://127.0.0.1:3000'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'corsheaders', 'MyApp.apps.MyappConfig', ] REST_FRAMEWORK …

11.08.2021
I want to select multiple data in django raw_id pop-up and add them inline

Nice to meet you, everyone. I'm creating a talent booking system on django admin. The models.py is as follows. I'm new to django. I'm sorry if there is an agenda that has already been resolved. [master models.py] class Talent(models.Model): def …

11.08.2021
Django not updating pie chart on ajax success event?

I want to change the values in the pie chart whenever onchange event in a tag.But whenever onchange happens the piechart just disappears. Here how my ajax code goes: $( "#date" ).change(function() { $form=$('#form'); var datastring = $form.serialize(); var …

11.08.2021
Django How to make the condition correct on an HTML page - search bar

I try to do a search engine if the word in my DB thah I created then display the word on the HTML page and if not then nothing.. I did it right in VIEW but I can not apply …

11.08.2021
Facing issue in custom manager of django

I am trying to create a custom manager to retrieve all posts with the published status. New to managers!! Thank you in advance <3. models.py class PublishedManager(models.Model): def get_query_set(self): return super(PublishedManager, self).get_query_set().filter(status='published') class Post(models.Model): STATUS_CHOICES = ( …

11.08.2021
Is there any way i can make vs code to format and properly handle django templates?

I tried to use prettier, but it's not handling the Django templates codes properly, is there any alternative to this extension?

11.08.2021
AssertionError: OneToOneField(True) is invalid. First parameter to ForeignKey must be either a model, a model name, or the string 'self' Django

Я новичок в Django и это мой первый проект. Делаю сайт с регистрацией, но при запуске сервера вылетает данная ошибка. Понятия не имею почему. Мой models: from django.db import models from django.contrib.auth.models import AbstractUser class User(AbstractUser): username = models.OneToOneField(max_length=18, unique=True, …

11.08.2021
Not all my column in 'render_table' are orderable, what can i do?

I use render_table from django_tables2 to write a table that contain 4 headers (Title, Delete, View, and Export), the title is orderable, but the other one are not, the problem is that render_table use class orderable in all elements, how …

11.08.2021
Python manage.py loaddata moderation_categories.json having giving me error or FFMPEG not installed

Hello i am facing an issue of FFMPEG not istalled i am working on local and on production both working on local python manage.py loaddata moderation_categories.json works fine while on production running the same commands i am having the issue …

11.08.2021
Django - Is it possible to use other value than pk for modelform field?

I have a model form and I post the form via AJAX. One of the fields is a manytomany field and I render it as checkboxes. By default django uses PKs of the models in the queryset that is passed …

11.08.2021
Context processor in django

To display product categories on the site in several views, I get information about the categories from the database. (Do this in at least 8 views) I use context processor to prevent duplicate codes. Is this method better and …

11.08.2021
Sending emails from my django website, via sendgrid

I want to send account confirmation emails to all the users who sign up on my website, so it has to be an HTML email with the activation link. This is how i am trying to do it: import os …

11.08.2021
How to navigate to different routes in VueJs rendered in DJango Templates

I have a separate environment for front end which is written in ViewJS. I am trying to merge it with DJango default url. I have build it and able to render the screen in DJango server url by collectstatic and …

11.08.2021
I don't know why Price can't be saved in DB

I am a student learning Django and JavaScript. I am trying to save quantity and price in my code, but no matter how I try, it is not saved. Quantity is stored, price2 is not. Please help me.. I feel …

11.08.2021
Django ModuleNotFoundError: No module named 'views'

In my Django Project market I created an app called main. In main I created urls.py main/urls.py: from django.urls import path import views url_patterns = [ path('home/', views.homepage, name='home'), ] main/views.py: from django.shortcuts import render, HttpResponse # Create your …

11.08.2021
Ajax in django doesnt work, no error and nothing happens

I wrote a django app that has articles and im trying to add a like functionality, I added the code in the bottom and nothing happens. No error just nothing in the database or the html code changes. Any idea …

11.08.2021
Работа с css блоками bootstrap 4

Нужна помощь, как работать с css блоками, как интегрировать их в код, нужна инструкция для чайников, работаю с bootstrap 4, можно оставить ссылку, где это подробно объясняется, спасибо

11.08.2021
I want to save the pdf file from local server to online

I want to save the pdf file generated by weasyprint from the local server to online while my website is running on a local server in Django.. please help

11.08.2021
Celery auto reload Django

I am following ChillarAnand's example on how to reload Celery on change in my Django project, however it doesn't seem to close the previous Celery worker. On reload Celery raises the following error: [2021-08-11 10:42:30,216: WARNING/MainProcess] /Users/someuser/Documents/dev/backoffice/venv/lib/python3.8/site-packages/kombu/pidbox.py:72: UserWarning: A …

11.08.2021
Django class based view, save in another model after CreateView

I have a create view (Loan_assetCreateView(generic.CreateView)) where I save if an asset is going to be loaned and when it will be returened in a model called Loan_asset(models.Model). Then I have the asset in a diffrent model Asset(model.Model). I would …

11.08.2021
How to extract only day from timestamp in Django

I want to get a specific date like "8" out of (2021-8-3) but it's showing like this image how can I extract the specific date? usertime = User.objects.filter(groups__name = 'patient').values('date_joined').annotate(date_only=Cast('date_joined', DateField()))

11.08.2021
Whats the best websocket solution without too much overhead?

I'm fairly new to real-time databases with WebSockets so I'm facing probably the most important question when it comes to starting, which database and approach within the backend are the fastest and most reliable to set up and scale. I'm …

11.08.2021
Django REST массовая загрузка файлов

Какие есть наиболее оптимальные варианты загрузки файлов для множества объектов? Например надо загрузить по API 1500 изображений и 3000 документов для 500 товаров. Пока есть варианты преобразовывать в base64 строку и передавать как свойство объекта загружать отдельно через DRF …

11.08.2021
How can I save messages from my facebook webhook to a textfile using python and django. The code is attached below

If 'message' in message: # Print the message to the terminal print(message) # Assuming the sender only sends text. Non-text messages like stickers, audio, pictures # are sent as attachments and must be handled accordingly. print(message['message']['text']) respondinging = …

11.08.2021
Integrating a javascript pipeline to Django

I am trying this tutorial to integrate a modern JavaScript pipeline into a Django application. Javascript code is supposed to write a "Hello webpack" into the page, but it does not. Since I already have an existing …

11.08.2021
How to set new unicode codepoints to my language in django settings to support

I'm trying to add my language (kurdish) which is not existing in languages list in django , but i dont know where to find unicode codepoints from django.conf import global_settings import django.conf.locale from django.utils.translation import gettext_lazy as _ LANGUAGE_CODE = …

11.08.2021
Make form look like an excel table

I made this form: the form: AgregatsFormset = inlineformset_factory(Canva, Bilan, fields=('agregat', 'SCF', 'mois1', 'mois2', 'ecart1', 'evolution1', 'finmois1', 'finmois2', 'ecart2', 'evolution2'), can_delete=False, max_num=5) html: {% for bilan_form in form.forms %} {% for fidden_field in bilan_form.hidden_fields %} {{ hidden_field.errors }} {% endfor …

11.08.2021
Implement Django REST TokenAuthentication for Multiple User Model

I need to implement TokenAuthentication using Custom user model Consumer & Merchant (The default User model still exists and is used for admin login). I've been looking on official DRF documentation and days looking on google, but I can't find …

11.08.2021
Add SECRET_KEY to Heroku

When I type heroku config:set SECRET_KEY='MySecretKey' on my Powershell I got this error: 'SomeOfMyCharacterOnMySecretKey' was unexpected at this time. Please tell me if you know how to solve this. Thank you