Django and Python "Questions and answers", page 1387

06.08.2021
Docker ModuleNotFoundError: No module named 'xhtml2pdf'

I've looked through several websites but I can't seem to find an answer. I'm new to django and docker and whilist building my first project which is a quotation generator, I've been looking for different ways to generate a pdf …

06.08.2021
JS files not updating in python dev server

I am running a local development server with python using VS as ide through python manage.py runserver. When I update and save JS files, the views in browser do not update (even restarting the server and PC). I refreshed the …

06.08.2021
Django how to update boolean value of an objects in class based views?

In function based views I am using this code Notifications.objects.filter(receiver=user, is_seen=False).update(is_seen=True) for update an objects status from False to True. How to do that in class based view: here is my code: class ListNoti(ListView): model = Notifications template_name = 'notifications/notifications.html' …

06.08.2021
Django rest framework invert serializers

In Django, I have in models.py models defined like this : class foo1(models.Model): name = models.CharField(max_length=100) class foo2(models.Model): name = models.CharField(max_length=100) .... foo1 = models.ForeignKey(foo1, on_delete=models.SET_NULL, null=True) class foo3(models.Model): name = models.CharField(max_length=100) .... foo2 = models.ForeignKey(foo2, on_delete=models.SET_NULL, null=True) …

06.08.2021
How can I retrieve a specific JSON data

I want to retrieve a specific data after selecting an option form. When I select I got data in JSON format which I can't separated. I have tried obj.purchase_price but got undefined. my following code provide following data [{"model": …

06.08.2021
ModuleNotFoundError: No module named 'spyder'

I want to use a crawler project inside Django. I've set up celery and beats correctly but when I use the scraper project inside a Django app gives me the error ModuleNotFound even if I have added it to the …

06.08.2021
Django download file using CBV

How to use Class Based Views eg. TemplateView to display Django template with download links? Clicking the link should start downloading selected file. I already know how to do it with Function Based Views. Also - is it good idea …

06.08.2021
Why Django favicon reloads on routing pages? (about SSR)

Hi I'm using Django framework and made a simple web application. But on routing each page, I could see favicon reloads (OR maybe it could be loading html file). So here's the question. Is it correct that favicon reloads …

06.08.2021
Django-rest-passwordreset create and send token manually

Reading the [django-rest-passwordreset][1] I have not found a way to create and send the reset_password_token manually, meaning without the use of the endpoint created by the package. Currently I have this implementation: urlpatterns = [ ... url(r'^api/password_reset/', include('django_rest_passwordreset.urls', namespace='password_reset')), ... …

06.08.2021
How do I change a model after I ran makemigrations and migrate? Django

I made a model ran all the neccesery migrations commands and I want to add a field and change a field. How do i do that? I thought about changing them in models.py and ran makemigrations and migrate again but …

06.08.2021
Python can't see environment variables from script

I was invited to collaborate on a Django project and now I need to set it up. I am stuck with setting environment variables. In the given project envparse is used. I was provided an .env file, where items look …

06.08.2021
Import "pyrebase" could not be resolve pylance(reportMissingImports)

Installed pyrebase4 in my system but still unable to import in my view.py even tried "import pyrebase4" still the same error, I followed a youtube tutorial for it I followed the exact same things he/she said, so I'm not understanding …

06.08.2021
In Django raw query selects all my user twice

I have a raw query in my view: SELECT stressz_profile.id, projekt_id, user_name_id, szerv01b AS szervkult01a FROM stressz_szervezetikultura INNER JOIN stressz_profile WHERE stressz_profile.projekt_id=1 I try to get the data from the db but every time it duplicates the results. It …

06.08.2021
Error when installing node-django-hashers

In order to implement password hashing on the server side with nodeJS 14.7.4, we selected node-django-hashers so that it can be implemented the same with django website side, but when installing module, we are recieving the following error. docker …

06.08.2021
Single search bar managing all fields using django-filter and django-tables2 through Jquery

I need to manage the django-table2 using django-filter through jquery. Please help me how can i access this via jquery and how do i pass queryset in django-filter I am having my search box in the following way: where I …

06.08.2021
Return context variable along with saved form

I have following class based view which creates a project using form and then returns that created form. class ProjectCreateView(LoginRequiredMixin, CreateView): login_url = "registration:login" model = Project # fields = ['name', 'desc', 'start_date', 'end_date'] template_name = 'project/form.html' form_class = ProjectModelForm …

06.08.2021
'verbose_name': _('Small screens') NameError: name '_' is not defined

After installation django-responsive2 as django-responsive2, i got following error: 'verbose_name': _('Small screens') NameError: name '_' is not defined I use from django.utils.translation import gettext_lazy as _. I got this error: mw_instance = middleware(adapted_handler) TypeError: object() takes …

06.08.2021
Converting my Django/Python app from App Engine Standard Environment to Flexible Environment

I am trying to convert my Django/Python app from the Google App Engine Standard Environment to the Flexible environment mainly due to the app becoming slow and was constantly hitting a soft memory limit and suggested I upgrade to a …

06.08.2021
Редирект на прошлую страницу при сохранении объекта

Есть ли стандартный или просто способ редиректить пользователя из админки на прошлую страницу (с которой он пришел на страницу сохранения объекта)?

06.08.2021
How i can wrap json response data for djago-rest-framework?

I use djano rest framework. I have model, serializer and view: class PictureModel(models.Model): id = models.AutoField(primary_key=True) url = models.CharField(max_length=256) class PictureView(mixins.ListModelMixin, generics.GenericAPIView): serializer_class = PictureSerializer queryset = PictureModel.objects.all() def get(self, request): return self.list(request) class PictureSerializer(serializers.ModelSerializer): class Meta: model = PictureModel …

06.08.2021
How to make a web app with an embedded interactive map?

I work on a project where I have to make a web app. The main idea is for the app to have a map (from OSM preferably) on which you can draw a rectangle and then get lon and lat …

06.08.2021
How to retrieve list of tasks in a queue in Celery on Heroku?

My goal is to retrieve active & reserved tasks on my Celery workers. I'm using a Django-Celery-Redis framework. As suggested here: Retrieve list of tasks in a queue in Celery I have done this to retrieve the tasks: from …

06.08.2021
Run commands inside docker as non root after running it with exec (shell)

I have a Django project with Docker (in Ubuntu) and MySQL as a database, everything is working .i'm just curious: instead of running the long command like: docker-compose run backend python manage.py startapp myapp // 'backend' is the name …

06.08.2021
How to include images in django templates using an image url?

I am trying to build a web app which is similar to a search engine. Now when a user inputs "Eminem" for example , I need to show him an image of Eminem. Since the search term or query can …

06.08.2021
API endpoint for django `Group` model generating excess number of queries

I am trying to build an endpoint for the default django's Group model, which has name and permissions fields:- Here are my view and serializers:- Serializers.py:- class GroupSerializer(serializers.ModelSerializer): class Meta: model = Group fields = ('id', 'name', 'permissions') …

06.08.2021
Django Prefetching Nested FKs not working

I have been working on this for a bit but I cannot seem to get prefetching to work correctly in my instance. I am trying to run a nested Prefetch() to prefetch items from a prefetched object, but the attribute …

06.08.2021
OperationalError at /admin/auctions/listing

Enter image description hereHi new to Django unable to detect the error here, please tell me what I am doing wrong .I am Confused about the flow of the files in DJango also.

06.08.2021
Django application not logging request info in production log file when deployed with gunicorn and Nginx

This is the log settings of my Django application. LOG_DIR = "logs" LOG_DIR_PATH = os.path.join(BASE_DIR, LOG_DIR) if not os.path.exists(LOG_DIR_PATH): os.mkdir(LOG_DIR_PATH) LOGGING = { "version": 1, "disable_existing_loggers": False, "formatters": { "verbose": { "format": "{asctime} {levelname} : {filename} line - …

06.08.2021
Docker postgres role does not exist

I am using postgres with docker and having trouble with it. I successfully docker-compose up --build When I run below command it works fine. psql starts with my_username user as expected. I can see my database, \l, \dt commands works …

06.08.2021
Django.contrib.admin.sites.AlreadyRegistered: The model Ingredients is already registered with

I was trying to register the offer model, but it instead of throwing me this error now , help needed , thanks in advance from django.contrib import admin from django.contrib.admin import ModelAdmin from menus.models import Category, MenuItem, Ingredients,Offer # …

06.08.2021
Django messages not showing in my html template

I am trying show success message after objects delete from my list view page. here is my code: #this is the delete view class DeleteNoti(DeleteView): model = Notifications def get_context_data(self, **kwargs): data = super().get_context_data(**kwargs) data['messages'] = messages.add_message(self.request, messages.INFO, 'Notification deleted') …

06.08.2021
Изображение передается некорректно при запросе put django

Картинка получена через форму: class CustomUploadFileForm(forms.Form): file = forms.FileField()) Помимо картинок через эту же форму загружаются и файлы любых других форматов. Я пытаюсь загрузить картинку, полученную из формы, через API OpenstackSwift Swift, я вижу черный фон с небольшим белым …

06.08.2021
Overwrite of the save method to ensure integrity in database doesn't work

A user always has one default dashboard for each company they are associated with. They can add new dashboards, as soon as they set one as the default, the other one gets reset. To achieve this I tried overwriting the …

06.08.2021
QuerySet Manager django problem with 'objects'

I need to create 2 different ModelManager which inherits from my own Manager 'models.QuerySet' I created : class ActiveObjectsQuerySet(models.QuerySet): def filter_active(self): return self.filter(status=Book.Statuses.ACTIVE) class AllObjectsQuerySet(models.QuerySet): def filter_reissued(self): return self.filter(status=Book.Statuses.REISSUED) def filter_reviewed(self): return self.filter(status=Book.Statuses.ON_REVIEW) and this one: objects = ActiveObjectsQuerySet.as_manager() …

06.08.2021
Django saving ManyToManyField gives error: Field 'id' expected a number but got 'str'

I'm trying to use a ManyToManyField to create a model attribute with a set of options (instances of the m2m model). When I go to save the model in my ModelForm, save_m2m() gives an error saying that Field 'id' expected …

06.08.2021
Why I'm getting this Error TemplateDoesNotExist at /konfigure/index.html

I'm getting this error when I'm trying to go to the configuration section of my site. This is my folder structure: [[1]: https://i.stack.imgur.com/DhV7A.png] Here's the code: 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', …

06.08.2021
Tables automatically added to database when creating custom user model in django

I created custon user model extending AbstractUser. But when making migrations, many tables were added to postgresal, i have only two models. i named my customuser : CustomUser and the other model Offers. These tables were found in postgresql: api_customuser …

06.08.2021
Which is better: MongoDB vs PostgreSQL for storing JSON data

I am creating a Django project. The core feature of this project is to create dynamic forms, then to fill these forms and finally to visualize this informations using some BI tools. In addition to creating/storing dynamic forms information, user …

06.08.2021
I'd like to modify the JavaScript code to meet the conditions [closed]

I am a student who is learning web programming. It's just that I added functionality to the program, so it's not saved in DB. Above is saved, but features have not been added, below is added, but not saved to …

06.08.2021
Storing Multiple data from HTML forms to the database

I am creating a quiz app and i have some value for every radio Option, and i want to store the question,option the user has selected and the value for that option in database. Below is the model for Questions …