Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: TextChoices appearing in array as the __str__ representation and not as the value
I have the following field in my model: schedule = models.CharField( choices=WorkScheduleType.choices, max_length=255, unique=True, ) This behaves as expected when I do something like this: print(schedule) > DAILY But when I do something like this: print([schedule]) It renders like this: ["WorkScheduleType<DAILY>"] Why is this? Is the proper way to do this really in two lines instead? my_array = [] my_array.append(schedule) print(my_array) -
How do I use Javascript eventListeners in Django project
I am pretty much new to the Django framework and working on a small project that requires me to use static files (JavaScript) in it. I have a couple of buttons that I want to manipulate from the DOM but for some reason, I cannot have access to these buttons using DOM manipulations. Can someone please tell me why I can't print these buttons in my console? What I get an an output is an empty HTMLcollection[] const deleteButton = document.getElementsByClassName('delete-button'); console.log(deleteButton); ** Template ** <div class="my-2"> {% for todo in mytodos %} <div class="checkbox my-2"> <div class="checkbox-wrapper"> <input type="checkbox" id="cbox3" class="mr-2" value="third_checkbox"> <label for="cbox3"> {{ todo.todotext }} </label> </div> <div> <a href= {% url 'delete' %}> <button class="delete-button btn btn-outline-danger">Delete</button> </a> </div> </div> {% endfor %} </div> -
Django convert timestamp before performing a query?
I have a unique instance where my front-end timestamp is generated based off of a user specific setting. (User can choose their timezeone, 12/24 hour clock). I have a search feature in which a user can search based off of a timestamp. The issue that I have is that my timestamp in the database is a UTC timestamp, but the user will want to search based off of the visual timestamp that they see on the page. For example on the front-end of my application the timestamp shows... 2022-09-21 8:25:26 a.m. Yet on the postgres side that timestamp will show as... datetime.datetime(2022, 9, 21, 12, 25, 26, 959035, tzinfo=datetime.timezone.utc) When a user types in 09-21, as expected, zero results get returned. I am looking for a way to do convert time timestamp to the users timestamp before the query takes place, but not sure on the best solution, or right direction to to here. Any guidance would be greatly appreciated! -
Data upload server with user management and resumable uploads
I’m looking to build a web-based data upload server for a citizen science project and am wondering if there are out-of-the box solutions available or if there are some useful Python packages, libraries available to make the job easier? I don’t really want to reinvent the wheel and it seems that something like this should already exist. Maybe I’m just looking in the wrong place. The brief is that our volunteers make audio recordings to monitor threatened species, then upload their data for archiving and automated processing. I’d like a server that has the following: Simple web-based user interface - many of our participants have limited confidence with computers; No client-side software to install; User management: registration to approved email addresses only (or similar, maybe a manual admin approval process); Data files are 1 to 40MB in size but there are lots of them ~1000 files, and ~10 GB in total. If user loses network connection, uploads should be recoverable with the server capable of resuming an upload where it left off. That's quite important. live progress and status updates to the user. I have access to a web hosting server. Maybe a Django or Flask implementation already exists, or … -
Python Django M2M attribute via an intermediary model
I have a model with 2 M2M attributes: Connection is recursive and the ConnectionRequest uses an intermediary class. With Connection attribute, I am able to retrieve the connections of a user without problems (since I am using a native M2M field). But with ConnectionRequest is where I have challenges. I would like to retrieve the 'connection requests' for this user but struggling with this natively. I have implemented it however programmatically (through a query) - but its not clean. Basically, I would like to return the list of all connection requests. ie where the recipientAccount is the same as the parent class (Account) object. class Account(models.Model): firstName = models.CharField( 'First Name', max_length=100, blank=True, null=True) lastName = models.CharField( 'Last Name', max_length=100, blank=True, null=True) emailAddress = models.EmailField( 'Email Address', max_length=255, blank=True, null=True, unique=True) connections = models.ManyToManyField('self', blank=True) connection_requests = models.ManyToManyField( 'ConnectionRequest', blank=True, related_name='accounts') def __str__(self): return self.firstName + ' ' + self.lastName class ConnectionRequest(models.Model): senderAccount = models.ForeignKey( Account, related_name='sender_Account', on_delete=models.CASCADE) recipientAccount = models.ForeignKey( Account, related_name='recipient_Account', on_delete=models.CASCADE) def __str__(self): return str(self.senderAccount.id) + ' to ' + str(self.recipientAccount.id) I have an idea to try the below but suddenly realised that I am unable to access the Account object from the ConnectionRequest class (since its … -
How i can use nested include and block tag in django templates?
I want to show list of books in page. But below code does not do it. base.html <!DOCTYPE html> <html lang="en"> <head> </head> <body> {% include 'core/main.html' %} </body> </html> main.html <main class="container"> <div class="wrapper"> {% block main %} {% endblock %} </div> </main> books.html {% extends 'core/base.html' %} {% block main %} Books {% endblock %} -
Two different forms on one $(document).ready(function) submit
I have two different forms which basically do the same thing so just for an ease of use and less coding is there any way I can assign both of them on one $(document).ready(function()). My original $(document).ready looks like this : $(document).ready(function() { $("#transaction_form_new").on('submit', (function(e) { e.preventDefault(); var formData = new FormData(this); formData.append('farm', {{farm.id}}); $.ajax({ ... }) This one is for creating a new form and i want to add the 'edit_form' also. I tried it like this but with no result: $(document).ready(function() { $("#transaction_form_new"),$("#transaction_form_edit").on('submit', (function(e) { -
Group records in queryset
I have the following models in an django app. class Person(models.Model): name = models.CharField(max_length=50) class Product(models.Model): owner = models.ForeignKey(Person, on_delete=models.CASCADE) class Order(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) buyer = models.ForeignKey(Person, on_delete=models.CASCADE) I would like to get a list of orders placed by a buyer grouped according to the owner of the product in the order. Something like this orders placed by buyer 1 order__product__owner 1 order 1 order 2 order 3 order__product__owner 2 order 4 order 5 order 6 -
how to dynamically populate choices field from another model containing the values to be used - Django
I have a model that has some choices that the admin chooses while entering some data in the admin pannel. I am using the general way of making a choice field as below CATEGORY= ( ('arbitration', 'arbitration'), ('binding precedent', 'binding precedent'), ('contempt', 'contempt'), ('execution of decree', 'executuon of decree'), ('limitations', 'limitations'), ('negative equality', 'negative equality'), ('od/ss/rd', 'Obitor Dicta / Sub Silenso-Ratio/ Decidendi'), ('review', 'review'), ('special relief', 'special relief'), ) ) class Civil(models.Model): law_category= models.CharField(max_length=60, choices=CATEGORY ,null=True, help_text="required") Here the choices are hard coded. Now I want the admin to have control over what choices he can have inside CATEGORY. So what I thought would work is to create another model where he can enter the the values for CATEGORY and that would in return create some dynamic choices for the field law_category= models.CharField(max_length=60, choices=CATEGORY ,null=True, help_text="required") The way I approached the problem was as below class CivilChoices(models.Model): key=models.CharField() value = models.CharField() Here I thought of entering the key and values. But now I do not know how to get these values inside the Civil model for CATEGORY to use, or even if it is the right way to do it. Please suggest me a way to create dynamic choices for … -
Django LEFT JOIN or INNER JOIN the same query set together multiple times
It's been a minute since I've used SQL so I'm not 100% sure LEFT or INNER join is the correct term, as I googled this and in most cases, people just wanted to concatenate the results, wich is not SQL JOIN's. I have 3 models. Dumbed down they are as follows: class Stakeholders(models.Model): firstname = models.CharField(max_length=50) lastname = models.CharField(max_length=50) email = models.EmailField(max_length=254) class Policy(models.Model): name = models.CharField(max_length=50) description = models.CharField(max_length=150) class StakeholderPolicyResp(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) stakeholder = models.ForeignKey(Stakeholders, on_delete=models.CASCADE) policy = models.ForeignKey(Policy, on_delete=models.CASCADE) response = models.IntegerField(default=0) I want to create a table that has a unique stakeholder with the response for up to 4 policies. In simple example: Stakeholder ------------------- 1 John Doe jd@email.com Policy ------------------- 1 Policy 1 2 Policy 2 3 Policy 3 StakeholderPolicyResp ------------------- UID1 1 1 0 UID2 1 2 4 UID3 1 3 3 What I want out is a table that can have varying amount of columns, but something like this: MyTable ------------------ Stakeholder data - Policy x Resp - Policy y Resp - Policy z Resp ================== John | Doe | 0 | 4 | 3 Here we have the stakeholder with the responses for policy 1, policy 2 and policy … -
How to make a filter in a model (Django/ORM) respecting the place of the fields in the query?
I have a model Student with this fields: id, first_name, last_name. I added a compose index with first_name and last_name. The problem is when i filter. I use Student.objects.filter(last_name='Caicedo', first_name='Pedro') but the internal ORM select is: SELECT `students`.`id`, `students`.`first_name`, `students`.`last_name` FROM `students` WHERE (`students`.`first_name` = 'Pedro' AND `students`.`last_name` = 'Caicedo'); args=('Pedro', 'Caicedo'); It does not respect the order, and I need to respect it by optimizing the query. -
Django Admin and object ID = 0
Using django admin to manage records from a pre-existing external database, I face issues with objects having 0 as value for the model's id fields. Each time i edit this object django creates a new one. I understand that having 0 for an id is like having a null value and that django considers the object as a new one to be inserted in the model table. is there a way to specify that 0 is a good id (even if not a good idea ...) ? -
How to override create action of django rest framework ModelViewSet to create bulk records?
Demo model class Item(models.Model): name = models.CharField(max_length=20) Demo view class ItemViewSet(viewset.ModelViewSet): queryset = Item.objects.all() serializer_class = ItemSerializer Demo input passing using API post request [ {name: 'Book'}, {name: 'PC'}, {name: 'Phone'} ] How to create multiple table records with single post request? -
UndefinedColumn column integrations_externalrecord.oppcontact_id does not exist django postgresql
When accessing my ExternalRecord model via the django admin screen, or by querying ExternalRecord.objects.all(), I receive the error: psycopg2.errors.UndefinedColumn: column integrations_externalrecord.oppcontact_id does not exist I am building an integration functionality, and we have a junction table that houses an external id and the instance in our database that corresponds to this external id, set up like so: class ExternalRecord(UUIDPrimaryKey, CreatedModifiedMixin, models.Model): integration = models.ForeignKey( to=Integration, related_name='external_records', on_delete=models.CASCADE ) emailuser = models.ForeignKey( "accounts.EmailUser", related_name='external_records', null=True, blank=True, on_delete=models.CASCADE ) institution = models.ForeignKey( "institutions.Institution", related_name='external_records', null=True, blank=True, on_delete=models.CASCADE ) oppcontact = models.ForeignKey( "opp_contacts.OppContact, related_name='external_records', null=True, blank=True, on_delete=models.CASCADE ) external_record_id = models.CharField( max_length=1000 ) and so on... When I view the OppContact model either by viewing in the django admin screen or with OppContact.objects.all(), I see that the model has a field for "id". When I rollback to the migration before applying the oppcontact field, everything returns to work as normal, meaning I can query/view ExternalRecords without getting an error. This is my OppContact model: class OppContact(UUIDPrimaryKey): company = models.ForeignKey( "accounts.Company", on_delete=models.CASCADE, blank=True, null=True ) first_name = models.CharField( max_length=100 ) last_name = models.CharField( max_length=100 )... And this is another model to which my ExternalRecord can be linked, Institution: class Institution(UUIDPrimaryKey, CreatedModifiedMixin, models.Model): company = … -
InMemoryUploadedFile is not JSON serializable
I'm sending a payload with some string and two images in a POST Request. But I'm not sure how to serialize the images in the payload. I'm using POSTMAN's form-data to send this request and I'm getting ('Object of type InMemoryUploadedFile is not JSON serializable') def registration(self, payload): try: headers = {"accept": "application/json"} logger.debug({"payload": payload}) response = requests.post(url=self.registration_url, headers=headers,json=payload) if response is None: return None, status.HTTP_424_FAILED_DEPENDENCY parsed_data = data_parser.render_registration_response(response, payload) return parsed_data, response.status_code except Exception as e: logger.error(repr(e)) return None, status.HTTP_424_FAILED_DEPENDENCY Serializers.py class RegistrationSerializer(serializers.Serializer): name = serializers.CharField(max_length=20) vehicle_number = serializers.CharField(max_length=50) blue_book = serializers.ImageField(max_length=None, allow_empty_file=False, required=False) vehicle_class = serializers.CharField(max_length=50) bank_account = serializers.CharField(max_length=50) phone = serializers.CharField(max_length=20) avatar = serializers.ImageField(max_length=None, allow_empty_file=False, required=False) country = serializers.CharField(max_length=20) state = serializers.CharField(max_length=20) city = serializers.CharField(max_length=20) zip = serializers.CharField(max_length=20) -
Add attribute to the checkbox field based on initial django form
class MyForm(Form): real = BooleanField() If MyForm(data={'real': 'on'}), I want to render <input type="checkbox" checked=checked data-initial='on'>. If MyForm(data={}), I want to render <input type="checkbox">. How to achieve this? -
Import images from excell file to django database
I am looking for some code to import all images from excel sheet and save them in my database without using pywin32. Any help would be grateful. Thanks -
ValueError: source code string cannot contain null bytes in django anytime i run mange.py
I am having issues with my django project, Anytime i run the manage.py command line. It gives out this error main() File "/storage/emulated/0/django/twitter/manage.py", line 21, in main execute_from_command_line(sys.argv) File "/data/data/com.termux/files/home/my_venv/lib/python3.10/site-packages/django/core/management/__init__.py", line 425, in execute_from_command_line utility.execute() File "/data/data/com.termux/files/home/my_venv/lib/python3.10/site-packages/django/core/management/__init__.py", line 369, in execute settings.INSTALLED_APPS File "/data/data/com.termux/files/home/my_venv/lib/python3.10/site-packages/django/conf/__init__.py", line 84, in __getattr__ self._setup(name) File "/data/data/com.termux/files/home/my_venv/lib/python3.10/site-packages/django/conf/__init__.py", line 71, in _setup self._wrapped = Settings(settings_module) File "/data/data/com.termux/files/home/my_venv/lib/python3.10/site-packages/django/conf/__init__.py", line 179, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/data/data/com.termux/files/usr/lib/python3.10/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 1006, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 688, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 879, in exec_module File "<frozen importlib._bootstrap_external>", line 1017, in get_code File "<frozen importlib._bootstrap_external>", line 947, in source_to_code File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed ValueError: source code string cannot contain null bytes I have tried other solutions online and it is not working. Please could anyone help me. This is my setting file -
How to validate unique roll number and show them a validation error when the roll already exists using serializers Django Rest framework
I want to validate roll number in Serializers Django Rest framework I want to show validation error when the roll number is already present in the database. -
DRF: Is there any way to keep ModelSerializer's auto-generated validators while using dynamic fields?
I'm trying to have Django Rest Framework serializers with dynamic fields that depend on the context passed (request method, CRUD action etc.). So I set the fields in self.fields when the serializer is initialized. It works fine at the moment, but the problem is that I don't get the automatically generated validators that ModelSerializer provides. Is there any way to get those validators or do I have to resort to copy pasting validators from my models? -
foreign key dynamic filter with another foreign key in admin.py in django
I have a problem with the dynamic design of the admin. Thank you for your help. I want the selected productCategory to be dynamically filtered when I select the productType. For example, I do this manually in models.py (ProductCategory.objects.filter(productType=2 or 1 or 4 ...( i cant dynamic)) models.py enter code here class ProductType(models.Model): name = models.CharField(max_length=200) slug = models.SlugField(max_length=200, unique=True) class ProductCategory(models.Model): productType = models.ForeignKey(ProductType, on_delete=models.CASCADE) name = models.CharField(max_length=200) slug = models.SlugField(max_length=200, unique=True) class Product(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE) brand = models.ForeignKey(Brand, on_delete=models.CASCADE) productType = models.ForeignKey(ProductType, on_delete=models.CASCADE, default=1) productCategory = models.ForeignKey(ProductCategory, on_delete=models.CASCADE) enter code here admin.py class ProductForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(ProductForm, self).__init__(*args, **kwargs) if self.instance: self.fields['productCategory'].queryset = ProductCategory.objects.filter(productType=self.instance.productType.id) @admin.register(Product) class ProductAdmin(admin.ModelAdmin): form = ProductForm -
Django template doesn't see data of db
While learning it, I faced with an issue, when I'm trying to show data from db, template doesn't see it. I tried to remove db and migrations and create new with new objects, but it didn't helped. models file: from django.db import models from django.core.validators import MaxValueValidator, MinValueValidator class Product(models.Model): name= models.CharField( max_length= 100, verbose_name= 'Name' ) description= models.TextField(max_length= 500) photo= models.ImageField(upload_to= 'photos/%Y/%m/%d') price= models.FloatField(validators= [MinValueValidator(2.0), MaxValueValidator(1000000.0)],) amount= models.IntegerField() last_updated= models.DateTimeField(auto_now= True) is_published=models.BooleanField(default=False) category= models.ForeignKey( "Category", verbose_name= 'Category', default='Unselected', on_delete=models.SET_DEFAULT ) class Meta: verbose_name = "Product" verbose_name_plural = "Products" def __str__(self): return self.name class Category(models.Model): name=models.CharField(max_length=100) class Meta: verbose_name = 'Category' verbose_name_plural = "Categories" def __str__(self): return self.name views file: from django.shortcuts import render from .models import * # Create your views here. def index(request): print(request) product=Product.objects.all() return render(request,'main.html',{product :'product'}) template file: {% for item in product %} <h1>{{item.name}}</h1> {% if item.photo %} <img src="{{item.photo.url}}" alt="Not found"> {% endif %} <p>{{item.description}}</p> <h2>{{item.price}}</h2> {% endfor %} I didn't show full html file,due to stackoverflow didn't let me to post it, because there is a lot of code, and no text -
Django: calculating multiple values of over a set of children
I'm writing the management interface for a competition, and have the following models: class Heat(models.Model): current_heat = models.IntegerField() track = models.ForeignKey(Track, on_delete=models.PROTECT) previous_heat = models.ForeignKey('self', on_delete=models.SET_NULL, null=True, blank=True) start_date = models.DateTimeField('Start Date', default=timezone.now) end_date = models.DateTimeField('End Date', null=True, blank=True) class Game(models.Model): heat = models.ManyToManyField(Heat) format = models.TextField(max_length=20, default="V") player1 = models.ForeignKey(User, on_delete=models.PROTECT, related_name='player1') player2 = models.ForeignKey(User, on_delete=models.PROTECT, related_name='player2') winner = models.ForeignKey(User, on_delete=models.PROTECT, related_name='winner', null=True, blank=True) Now I want to get the standings for a specific heat. In other words, I want to get all unique players in that heat, together with how many wins they got (thus where they are in Game.winner), and how many losses they got (thus where Game.winner is not that player but it is not Null, and they are in either Game.player1 or Game.player2.) Ideally, this should then even be ordered by wins (descending), losses (ascending). I've been looking through the aggregation docs from Django, but I don't see how to start since I need to get so many different things all combined. -
urllib [Errno 11001] getaddrinfo failed with windows proxy
I'm running Django 3.2 with django-tenants on a Windows local dev environment. In my windows hosts file I have: 127.0.0.1 *.localhost ...so that I am able to use subdomains with django-tenants. E.g. http://mysub.localhost:8000. When running ./manage.py runserver the dev server runs perfectly. However, when trying to execute urlopen in my code I get an error: >>> html = urlopen('http://mysub.localhost:8000') Traceback (most recent call last): [...] urllib.error.URLError: <urlopen error [Errno 11001] getaddrinfo failed> As far as I can tell the error is due to the proxy settings on my windows machine (this does not fail in production), but I am unsure how to resolve it? -
How to server Django media files on apache2 and docker
I'm Running a django app on apache2 using docker, everything works great but when i try to open an uploaded file ( media file) it says an URL not found error like : physical/path/to/file/filename.jpg doesnt exsits so it converts the url to a phyical path from inside the docntainer.. Here are my files: DockerFile FROM ubuntu RUN apt-get update # Avoid tzdata infinite waiting bug ARG DEBIAN_FRONTEND=noninteractive ENV TZ=Africa/Cairo RUN apt-get install -y apt-utils vim curl apache2 apache2-utils RUN apt-get -y install python3 libapache2-mod-wsgi-py3 RUN ln /usr/bin/python3 /usr/bin/python RUN apt-get -y install python3-pip #Add sf to avoid ln: failed to create hard link '/usr/bin/pip': File exists RUN ln -sf /usr/bin/pip3 /usr/bin/pip RUN pip install --upgrade pip RUN pip install django ptvsd COPY www/demo_app/water_maps/requirements.txt requirements.txt RUN pip install -r requirements.txt ADD ./demo_site.conf /etc/apache2/sites-available/000-default.conf EXPOSE 80 5432 WORKDIR /var/www/html/demo_app #CMD ["apache2ctl", "-D", "FOREGROUND"] #CMD ["python", "manage.py", "migrate", "--no-input"] docker-compose.yaml version: "2" services: db: image: postgres volumes: - ./data/db:/var/lib/postgresql/data - ./data/static:/var/www/html/demo_app/static - ./data/upload:/var/www/html/demo_app/upload ports: - '5432:5432' environment: - POSTGRES_DB=database_innvoentiq - POSTGRES_USER=database_user_innvoentiq - POSTGRES_PASSWORD=mypass@ - PGDATA=/tmp django-apache2: build: . container_name: water_maps environment: - POSTGRES_DB=database_innvoentiq - POSTGRES_USER=database_user_innvoentiq - POSTGRES_PASSWORD=mypass@ - PGDATA=/tmp ports: - '80:80' volumes: - ./www/:/var/www/html # command: sh -c 'python manage.py migrate && …