Django and Python "Questions and answers"

05.10.2022
Self.request.user not returning in queryset

In my views, queryset is returning all the users when I want it to be only returning the user that is currently logged. I have a get self method which has the serializer set to the user but it is …

05.10.2022
Get slug name list by url path name

I am reverse-engineering django urlpatterns. For my purpose, I need to dynamically know the list of slug names developers chose to use within url. Example: path("<slug:membership_slug>/<slug:parent_slug>/data/", rzd.ReportingUnitDataView.as_view(), name="hierarchy.item.data"), So, in the world, where everyone writes perfect code, my function …

05.10.2022
How to fix result display in project

How to adjust the project to improve the performance result: in myworld/members/view.py: def testing(request): template = loader.get_template('template.html') context = { 'heading': 'Hello <i>my</i> World!', } print(context) return HttpResponse(template.render(context, request)) in myworld/members/templates/template.html : <html lang="en"> <head> <meta charset="UTF-8"> <meta …

05.10.2022
Django summernote don't form is not displayed outside the admin panel

I'm trying to add WYSIWYG editor django-summernote to my django project. I found the problem that the editor is not showing up when I try to add it to the page. On the form page, I don't …

05.10.2022
JS function not fired in Django dropdown onchange event

I've question, I've JS function which is used in Django project(downloaded from internet) , so in template.html I've <select class="select_filter" onchange="myFunc(this.value);"></select>, also this function is declareted in this template.html <script> function myFunc(val) { console.log(val); } </script> but in …

05.10.2022
Update only targeted element with ajax

I'm trying to update my cart page with ajax when someone increases or decreases the quantity of the products, my view logic is fine. My issue as I can infer is targeting the class "ajax_updater", as soon as I hit …

05.10.2022
What is the difference between SimpleTestCase.settings() and django.test.override_settings?

Django provides different ways to change settings(documentations) in a test in different levels (TestCase class, test method, context manager). I understand the difference between override_settings and modify_settings, but I can't get the difference between SimpleTestCase.settings() and django.test.override_settings() …

05.10.2022
(Django / Nginx / Gunicorn) HTTPS fails to serve pathed directories on my site

Pretty new to Nginx and web deployment in general. I have a site I am aiming to deploy using a DigitalOcean droplet. Right now it is working, but only with http://[SERVER-IP] (here) Although the site does load …

05.10.2022
UpdateAPIView | Django REST does not update data properly

I want to register values in a table of relations when updating data. Conversely, I want to generate an error if the value does not exist. models.py class CustomUser(AbstractBaseUser, PermissionsMixin): uuid = models.UUIDField(default=uuid.uuid4, primary_key=True, editable=False) email = models.EmailField(_('email …

05.10.2022
How to obtain a specific data from model in profile when person is logged in, Django?

I want to post a specific data in profile from user that is logged in. I have a model like this: class Customer(models.Model): user = models.OneToOneField(User, null=True, on_delete=models.CASCADE) name = models.CharField(max_length=60) email = models.EmailField(max_length=100) class Wallet(models.Model): name = models.OneToOneField(User, null=True, …

05.10.2022
Issue deploying Django webapp in OVH Hosting

I'm trying to deploy a Django App in OVH Hosting and, after some hard exploration and try-error, I keep getting an issue. File "/usr/share/passenger/helper-scripts/wsgi-loader.py", line 381, in <module> handler = RequestHandler(server_socket, sys.stdin, app_module.application) AttributeError: module 'passenger_wsgi' has no attribute 'application' …

05.10.2022
How can I find 3 top or max value in django model?

I have a class in django model and how can I find 3 maximum value in it? Do I need for into for loop? or Do I need any class? class Prices (models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE) Price = models.IntegerField() page …

05.10.2022
Using the URLconf defined in name, Django tried these URL patterns, in this order

I have a django project and in this project I have two apps: main and profiles. So I added both mini apps to the settings.py file: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'main', 'profiles', ] and …

05.10.2022
How to mark words that match words from a list in a django form's textarea using javascript?

I have the following form: class TestForm(Form): testfield = CharField(widget=Textarea(attrs={'rows': 10, 'id': 'test'}), label='Input test text here') Rendered to my template along with the following list as context: dummy_list = ['hi', 'hello'] I'm trying to make a button …

05.10.2022
Django: relations between two objects of the same model

I have created this model: class Process(models.Model): name = models.CharField('Process name', max_length=50, unique=True) owner = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, max_length=50, null=True, verbose_name='Process owner') I want to create multiple processes and from those build a hierarchy. Here is a hierarchy model: class …

05.10.2022
XXX is not defined - Importing Class from OpenLayers Node Module in Django

Having difficulty getting the Node OpenLayers to work within Django. npm and ol are installed and the files are in a node_modules folder in my project. I included the node_modules folder in my STATICFILES_DIRS in settings.py. I'm including the OpenLayers …

05.10.2022
Wagtail dumpdata modellogentry null values

Having a problem with dumpdata command in Wagtail v.3.0.3. Some of the entries for the table pagelogentry have data set to null and not the expected {}. It is not all the values. When I do dumpdata I have to …

05.10.2022
Django How do I get a value from a model recursive reference?

I am trying to implement the comment function of comments through self reference. error: models.ReComment.DoesNotExist: ReComment matching query does not exist. Parent_comment of ReComment model was ForeignKey as self I printed self.kwarg and got a value of {'pk': 3, 'comment_id': …

05.10.2022
Wagtail PageRevision errors from loaddata

When I use dumpdata / loaddata to snapshot my live Wagtail sites to my sandbox, I sometimes get pages which I can't edit on my sandbox. These are always pages which the Wagtail admin explorer has marked "live + draft". …

05.10.2022
Error converting data type nvarchar to Datetime While Calling Store Procedure in Django

I am trying to pass datetime value to the store procedure of mssql but getting this error: django.db.utils.ProgrammingError: ('42000', '[42000] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Error converting data type nvarchar to datetime. (8114) (SQLExecDirectW)') Here is the code: fromDate …

05.10.2022
Django password hashing different from python passlib pbkdf2 library

Using django admin, I have created a user email: cuteemail@example.com password: ccpass!ccpass The hashed password stored in the database is pbkdf2_sha256$260000$alGB1h2BRHwn83nz9fSJ3V$qippfbL8g59KPoDh+cIEh70TQCjuWeH8017VcLLpDIY= All I know is that django is generating the password hash using PBKDF2 algorithm. I need to …

05.10.2022
Django Rest Framework - datetime sent as str gets changed to different timezone when being saved to database?

I sent the following: {'ticker': 'XYZ', 'last_price': 394.05, 'last_date_time': '2022-10-04 15:57:18'} When it was saved in DB: ticker: XYZ last_price: 394.05 last_date_time: 2022-10-04 11:57:18 I am not sure how or why this gets changed. models.py class StockPriceModel(models.Model): ticker …

05.10.2022
Difference between Django ORM datetime and Postgre datetime value

I have developed an application with Django and recently changed my DB from Sqlite to Postgresql. I have found the following inconsistency between datetime values in DB and results of Django orm: <img src="https://i.stack.imgur.com/ePR7B.png" alt="enter image description …

05.10.2022
How to join two different modal in django?

I'm using django 3.2. And DB name postgres. I'm stuck in a problem where i want to combine two modals. I have following two modals 1- Profiles 2- Ratings foreignKey(Profiles) now I want to return profiles list with their ratings. …

05.10.2022
How i make a qr code generator in django? [closed]

I'm working on an existing project with Django and I need to add a Qr code that generate the profile info from database , but unfortunately I didn't find a helping documentation so if u have any idea of what …

05.10.2022
Django AWS cannot be access from public IP

I've been trying to put my Django application as docker in AWS ECS and it works as intended when accessing from inside. Then I tried to add an ALB so I can access my application but so far failed to …

05.10.2022
Django Action Append Slash

I am making development, and my POST request come like config/alert and I am trying to catch it with action decorater below.BUT Django does not catch it It wants config/alert/ but It is not possible to change incoming url add …

05.10.2022
Error in activation via URL sent to email in user registration system using DRF

I wanted to add a registration system to the API using DRF. The user receives an activation url by email and can activate his account. I am having problems decoding this sent token, i.e. it is taking the token as …

05.10.2022
Why Django redirect function returns to the same page

I have a website where there are different groups. As soon as you click on one of the groups, you are redirected to the details page of that group. This click happens via a post method, where the name of …

05.10.2022
Foreign Key USER Django Model: django.db.utils.IntegrityError: (1062, "Duplicate entry

I'm trying to use User as a foreign key for Time for an API, but I'm getting this error message when I try to add another time django.db.utils.IntegrityError: (1062, &quot;Duplicate entry '20' for key 'time.user_id'&quot;) My model: class Time(models.Model): …

05.10.2022
Keeping CharFields in array instead of multiple variables

Right now I'm using various variables to store fields, and it works well, but I'd like to move them to lists. Is there a way to do this? What I have now: lessonNameFirst = models.CharField('8:30-10:00', max_length = 50) additInfoFirst = …

05.10.2022
5 seconds delay(pause) from django+apache

I am running a site with django+apache+ssl+mysql+cloudfron+s3. However, I discovered that the ttfb time increases significantly when the first connection and caching setup time ends at some point. (response starts after pause for about 5 seconds) After uninstalling Apache, I …

05.10.2022
How to server static files in the folder without folder 'static'? Django

I have my index.html and static files in this structure: templates: folder: index.html css js images another_folder: index.html css js images I want that staticfiles finder will look for …

05.10.2022
Cronjob is not ran in Elastic Beanstalk

I am running Django in Elastic Beanstalk, platform: Python 3.7 running on 64bit Amazon Linux 2/3.4.0. I need to create a cronjob that runs a custom Django management command once every five minutes. I created the following file to .ebextensions/cron.config: …

05.10.2022
Error after running makemigrations in django app

I have developed a django app and I want to use postgres to store some results. For that reason I have the following docker-compose.yml: version: '3.2' services: elasticsearch: container_name: elasticsearch build: context: elasticsearch/ args: ELK_VERSION: $ELK_VERSION volumes: - type: bind …

05.10.2022
Django Rest not receiving large base64 images through POST

I have a REST API in Django that is able to process JSON data, small base64 images are working by large images like 3MBs are failing to be processed. The images are saved to the folder.

05.10.2022
How to get select options from django models?

I am not able to render product in my order model on my html page. I am trying to find out the problem here. but as i select form.product.model_name it should get me the model names, but its blank in …

05.10.2022
Преобразования обычного текста

Всем доброго времени суток, у меня есть API написанная на python с использованием фреймворка Django, как сделать так чтобы она воспринимала &quot;Неподдерживаемый тип данных &quot;text/plain&quot; в запросе.&quot;, помогите пожалуйста. Вот models.py class Test(models.Model): pub_date = models.DateTimeField(auto_now_add=True) text = models.CharField(max_length=10000, blank=False, …

05.10.2022
Data input from template file is not storing in .txt file in Django Python ( Get method)?

I'm trying to store some data from a html form in a .txt file. But when I store data from my variable used to recieve data it give &quot;None&quot;. But when I pass string directly it successfully store. def write(request): …

05.10.2022
Object data becomes empty after serializing

user = User.objects.filter(id=payload['id']).first() carts = AddToCart.objects.filter(user=user) sum_price = 0 for i in carts: sum_price += int(i.product.price) context = { 'carts': carts, 'sum_price': sum_price, } print(context) serializer = AddToCartSerializer(context, many=True) return Response(serializer.data) **printed 'context' in a terminal looks like …