Django and Python "Questions and answers", page 1589

08.08.2021
Creating a new field to an extended user model every time a post is made by that user

I want my extended user model to look like what it does below, where I can upload an Image as many times as I want to that extended user model. With everything being in one model without having two separate …

08.08.2021
Scrollspy not working at all - menu items not being highlighted

I'll preface by saying that I am a complete beginner with HTML, Bootstrap and CSS - I only started a few days ago. For the life of me I cannot seem to get Scrollspy to work. I know this question …

08.08.2021
Django model function implementation to auto initialize a particular field's value

I need to write a Django model function to calculate the value of an existing field. my models.py: class questionNumeric(models.Model): question = models.TextField() marks = models.IntegerField() correctAns = models.FloatField() class questionTureFalse(models.Model): question = models.TextField() marks = models.IntegerField() correctAns = models.BooleanField() …

08.08.2021
Desing patterns in Django

I'm learning Desing Patterns and appling it into Python. I've work with Django, but I don't know how to apply a Factory method (for instance), into Django or I shouldn't use it in it. Thanks for your answers =)

08.08.2021
Django: Querying a stacked inline object | ValueError at /profile Cannot query "Anthony_Jamez12": Must be "Profile" instance

I am trying to make an Instagram Clone. So what I'm trying to do here is query the user's photos that were uploaded and display them on the frontend. When I query into the stacked inline Uploads model I can …

08.08.2021
Django form field error_messages not working with IntegerField

This is my model : class Bid(models.Model): id = models.AutoField(primary_key=True) bid = models.IntegerField(verbose_name='Prix demandé', null=False, blank=False) note = models.TextField(verbose_name='Description', null=False, blank=False) date = models.DateField(auto_now_add=True) This is my form class BidForm(forms.ModelForm): class Meta: model = Bid fields = ['bid', 'note'] …

08.08.2021
I deployed my app on digital ocean and every one can access the URL and the app except me I get error as shown in screenshot

It is a Django app on a ubuntu 20.04 server using nginx and gunicorn error i get

08.08.2021
Can Anyone Please solve this test Project (Django and Django Rest Framework)

Please solve this Test project. The instruction is available at the following link. https://bitbucket.org/staykeepersdev/bookingengine/src/master/

08.08.2021
Comment doesn't submit to the database

I am having a hard time to get the comment object work, anytime i comment and submit it shows the the JsonResponse but wont submit to the database. Here is my view to create comments def blog_detail(request,post_id): user = request.user …

08.08.2021
Django user-uploaded media files in production with Dokku

I would like to serve user uploaded media files using nginx on the same host as the Django application rather than a CDN or S3 or similar. The django-private-storage library can be used to protect media files behind a login: …

08.08.2021
Why am I getting an integer precision error when I run: heroku run python manage.py migrate

I have deployed a Django app on Heroku, but I want to migrate to PostgreSQL, so I am following a video tutorial on YouTube on how to do that. In the tutorial, we have to run Heroku run python manage.py …

08.08.2021
Close div with js event listener in django

I want to add a js eventlistner so i could close an alert pop up after display, below is the current code...i have the script in separate file as well. Thank you Hello all, i want to add a js …

08.08.2021
Django - Admin Area width

My admin area on my Django application is a little bit off since a few days. I don't know what I did wrong... At the moment, the width is not fully used by the tables and the forms. The buttons …

08.08.2021
I am new to Django Rest Framework and practicing this question but i am not able to understand it can anyone help me solve it

Summary: Extend Django Project with Django REST Framework for a simple prebuild booking app that have: - Listing object with two types - booking_engine. models : Apartment(single_unit) have booking information (price) directly connected to it. Hotels(multi-unit) have booking …

08.08.2021
Finding Largest Value of an Integer Field - Django

I have a Django website and one of my models has an integer field. Does anyone know of a way to retrieve the largest value currently in that field into the view? Thanks!

08.08.2021
Django: How to automatically generate the USERNAME_FIELD of a custom user model?

This is a learning project and I've been trying to create a custom user model with the possibility of having multiple accounts with the same nickname. The USERNAME_FIELD would be username = f"{nickname}#{random_number}" (just like the Blizzard and Discord format), …

08.08.2021
Django how to raise validation error if foreignkey objects id change in hidden input

I have an hidden foreigkey filed in my forms. I want to raise validation error or stop submitting forms if user try to change the value. here is my code: html: {%for i in user_profile%} <input type="hidden" name='userprofile' value="{{i.id}}"> …

08.08.2021
Url template tag in django from parent project

I was trying to use the url tag in my template: <div><a href="{% url 'download_file' filename='rilasci_progetto_scuole.xlsx' %}">Esporta file Excel</a></div> the template path is: \FastFM\Scuole\templates the 'download_file' function is declared inside the views.py (\FastFM\FastFM\views.py) of the parent project (the name …

08.08.2021
Where to store files for admin to download in Django?

I have some example files that I want to serve in a download link to all admins. They are not model dependant or user dependant (other than requiring admin). They're txt files and the same files must be available to …

08.08.2021
Django Rest Framework | TypeError: Field 'id' expected a number but got OrderedDict([('name', 'string')])

I'm trying to update a ManyToManyField in a UserProfile, which is part of my custom User model in my Django REST API. However, I get this error: TypeError: Field 'id' expected a number but got OrderedDict([('name', 'string')]) Since I'm doing …

07.08.2021
Creating a Blogpost Like/Dislike Button within Django/Wagtail

I'm new to Django and Wagtail and have looked for a way to implement a "simple" like/dislike button on a blog entry page using Wagtail. I included a total_likes IntegerField in my model for the page and would like to …

07.08.2021
Django for...empty with different container when empty

I have a common pattern in which I have a container in HTML (e.g., ul, table ...) with elements from a queryset. However, when the list is empty, I don't want to display the container itself. I seek to get …

07.08.2021
Django URLs file redirecting the different URLs to the wrong html files

My Django site isn't working properly. It's hard to explain but when I run my Django web server and go to http://127.0.0.1:8000/hello/ I see "Hello, World!" as expected. But when I go to http://127.0.0.1:8000/dashboard/ …

07.08.2021
Django models - how to track a field on an object when value of the field depends on the different users?

I want a Book object with the field is_read, but the value of the is_read depends on the user. When I first created this app I was only thinking of one user (me). class Book(models.Model): title = models.CharField(max_length=50) author = …

07.08.2021
Retrive data according to the dropdown list item selected, in django

I have a dropdown list that is populated with "price range" from the database. I want to show the relevant "price" according to the "Price Range" for example, in the database, I have this row Price Range Price "0-1500" 28 …

07.08.2021
TypeError: filter must be an instance of dict, bson.son.SON, or any other type that inherits from collections.Mapping

In a Python function If I write like this, I get Expected expression Pylance in vscode. document = await collection.find({'date': {$gte: {start_date}, $lte: {end_date}}}).to_list(100) Here, date is my field and sart_date, end_date are the dynamic value that specify …

07.08.2021
Django/react Dockerfile stages not working together

I have a multistage Dockerfile for a Django/React app that is creating the following error upon running docker-compose up --build: backend_1 | File "/code/myapp/manage.py", line 17 backend_1 | ) from exc backend_1 | ^ backend_1 | SyntaxError: invalid syntax backend_1 …

07.08.2021
Django: Save a formset with commit=False (Docs say nothing)

With a form its easy, one does something like this: obj = form.save(commit=False) obj.foo = 1234 obj.save() obj.savem_m2m() # If has a ManyToMany field Now for formset is seems much more complicated. The documentation does not shed any light: …

07.08.2021
Python/Django 'OperationalError:no such table: main.auth_user_old' in Django Rest Forest (DRF)

I'm trying to create an RESTful API at the URL /polls/ in Django and DRF using a SQLite database. But I keep getting the error below. I'm using DRF's authentication system. What could be the problem? Thanks in advance! …

07.08.2021
Renaming Django model without breaking existing migrations

I want to rename a model in Django 3.2, keep my existing migrations and be able to both migrate a db with the old table name and create a db from scratch. I've started by renaming the model class and …

07.08.2021
How to display li tag in JavaScript or how to display p tag

I want to complete the following code with Django and JavaScript. What I want is <li><p id="optprice">{{value.extra_cost}}</p><option id="value" value="{{value.value_code}}">{{value.name} } (+{{value.extra_cost}}won)</option></li> In this part <p id="optprice">{{value.extra_cost}}</p> I want to float this. So in javascript var optprice = $("#optprice").text(); I did …

07.08.2021
Django how to connect user profile model with comment model for showing data from user profile?

I want to show user profile picture publicly in my blog comment section. I tried to use foreignkey in my comment model for connect user profile model then use this in my html for showing profile picture but didn't work. …

07.08.2021
Django urlpattern path argument empty (' ') meaning?

I am linking a views to urls.py inside the app. Django docs show it like this from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), ] Note: This urls.py is from app not the …

07.08.2021
Can't load CSS Django IIS

I have deployed my web app on Microsoft IIS on my company server. Web.config file is set up and app is running with all permissions. I have created Virtual Directory (to enable serving static files map a static alias to …

07.08.2021
Django forms - what is difference between form.fields and class var?

I wanted to make a dropdown-list that removes data with submit button. <form method="post"> <label for="id_title">Select:</label> <select name="title" id="id_title"> <option value="Return of the Jedi">Return of the Jedi</option> <option value="The …

07.08.2021
How to queryset filter with two lists?

I am very new to django, I have two list and I want to filter the values from table. I was using this query but this is giving me unions of two list i.e OR. I want something with AND …

07.08.2021
How to manage long running tasks via website

I have a django website, where I can register some event listeners and monitoring tasks on certain websites, see an info about these tasks, edit, delete, etc. These tasks are long running, so I launch them as tasks in a …

07.08.2021
`create()` must be implemented

My code: serializers.py: class AuthenticationSerializer(serializers.Serializer): email = serializers.CharField(max_length=255) password = serializers.CharField(max_length=128, write_only=True) def validate(self, data): email = data.get('email') password = data.get('password') user = User.objects.get(email=email, password=password) if user is None: raise serializers.ValidationError( 'A user with this email and password was not …

07.08.2021
How to use default address for saving in django

I have model name address which allow user to create multple address and also have functionality to set the default address but i unable to fetch it for saving in models any suggestion will be a big help thank you …

07.08.2021
Django preventing multiple user logins

I wanted to limit users to one login per account. I read numerous posts, and I've been following this post in particular: How to prevent multiple login in Django. In myapp/models.py, I have this: from django.conf import settings …