Django and Python "Questions and answers", page 1635

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 …

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 …