Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to solve CommandError: Can't find msguniq. Make sure you have GNU gettext tools 0.15 or newer installed. on windows
CommandError: Can't find msguniq. Make sure you have GNU gettext tools 0.15 or newer installed. i try to make multi language support website on django it shows error like "CommandError: Can't find msguniq. Make sure you have GNU gettext tools 0.15 or newer installed." -
Initial setup issue: "manage.py migrate" fails to make a DB connection
I'm a novice python developer, so bear with me: I just followed the Project Generation Options in the documentaton, and with a few hickups (mostly because some of the commands don't work on my Windows development machine). However, I made it to the last point of the initial setup " python manage.py migrate" and get the following error: django.db.utils.OperationalError: connection to server at "localhost" (::1), port 5432 failed: fe_sendauth: no password supplied So, i have created a .env file (in /cookiecutter/app_name) that containst this (and only this) information (with my unique values inserted) DB_NAME=my_app_slug DB_USER=postgres DB_PASSWORD=my_pass DB_HOST=localhost DB_PORT=5432 Clearly I have formateed the .env file incorrectly or it is in the wrong spot. I can't see to figure it out. Any help would be appreciated. -
Create dependent dropdown in django from columns of a database
I have set up a model in django: class Car_list(models.Model): car_brand = models.CharField(max_length=20) car_model_cat = models.CharField(max_length=20) car_model = models.CharField(max_length=100) car_fuel = models.CharField(max_length=30) car_typ = models.CharField(max_length=150) And already have put data through a import method and the admin page. Now I want to create a dependent dropdown over all fields. I would be happy if I could do it just for the first two columns. My question: All tutorials show me that I have to create seprate models like one for car_brand and one for car_model_cat. And then have to go via keys. Isn't there another way, cause I have to seprate the whole table which is huge. Can I just make a dependent dropdown out of the data of the whole table? -
How to apply custom "css" and "js" files to all admins in only one app efficiently?
I have custom css and js files, admin.py and overridden base.html located in templates/admin/app1/ as shown below: django-project |-core | |-settings.py | └-static | └-core | └-admin | └-app1 | |-css | | └-custom.css # Here | └-js | └-custom.js # Here |-app1 | |-models.py | └-admin.py # Here |-app2 └-templates └-admin └-app1 └-base.html # Here First, I set the custom css and js files to css and js respectively in Media class in all admins Person, Animal and Food in app1 as shown below, then I can apply them to all admins Person, Animal and Food in only app1: # "app1/admin.py" from django.contrib import admin from .models import Person, Animal, Food @admin.register(Person) class PersonAdmin(admin.ModelAdmin): class Media: css = { 'all': ('core/admin/app1/css/custom.css',) # Here } js = ('core/admin/app1/js/custom.js',) # Here @admin.register(Animal) class AnimalAdmin(admin.ModelAdmin): class Media: css = { 'all': ('core/admin/app1/css/custom.css',) # Here } js = ('core/admin/app1/js/custom.js',) # Here @admin.register(Food) class FoodAdmin(admin.ModelAdmin): class Media: css = { 'all': ('core/admin/app1/css/custom.css',) # Here } js = ('core/admin/app1/js/custom.js',) # Here But, the solution above is not efficient so instead I set them after <link ... "admin/css/base.css" %}{% endblock %}"> in base.html as shown below but the solution below doesn't work: # "templates/admin/app1/base.html" # ... … -
Django filter dynamically?
I want to show the number of players that matches certain criteria in database such as if played the match or not, I want to do that in each challenge, doesn't matter if the same players does exist in other challenges or not as they can be different or new players. to explain this better, assume I have these values in the database: Challenge (2 records) Letter:A Letter:B Match (3 records) Player: One, MatchLetter:A, Played:False Player: Two, MatchLetter:A, Played: True Player: Three, MatchLetter:B, Played:False in the template I want to list each Challenge and then show the number of players who played Challenge A 1 of 2 Players played the match. Challenge B 0 of 1 Player played the match. models.py class Challenge(models.Model): Letter=models.CharField(max_length=20, primary_key=True) class Match(models.Model): MatchLetter = models.ForeignKey(Challenge,on_delete=models.CASCADE,to_field='Letter', db_index=True) Player = models.CharField(max_length=50, db_index=True) Played = models.BooleanField() views.py def show(request): challenges = Challenge.objects.all() matches = Match.objects.all() return render(request,'show.html', {"challenges":challenges, "matches":matches}) show.html {% for challenge in challenges %} <p> Players in Challenge ( {{challenge.Letter}} ) are : {% for match in matches %} {% PSEUDO CODE if {{challenge.Letter}} == {{match.MatchLetter}} and {{match.Played}} == True: count=count+1 %} {% endfor %} {{count}} </p> {% endfor %} Doing this in view is possible … -
Django create model object on business logic condition
I am building something akin to a ranked choice voting app using Django. I need it to programmatically generate ballots based on user input according to required business logic/specified conditions. I'm unfortunately stuck sort of early on and can't figure out how to get it to create ballots on the fly. Expected behavior: There will be many users (at least 80) who visit the same form at different times. When each user visits the form, they will submit a name. Every time when exactly 4 users have submitted a name, a ballot is created for each of those 4 users which contains only the names they each submitted. (I can't wait until all 80 submit) Those 4 users will utilize the ballot to rank the names the other 3 users submitted (no user can rank their own submission)... Other stuff (tallies of votes displayed, etc.) I'm stuck around step 3). This code is sort of stripped down of fields to simplify it. But currently the form I'm using saves the submissions to the database fine - So, I see a Voter per submission I make. And the Ballot model seems OK. I can manually assign each Voter to a Ballot. … -
OperationalError at /admin/app/orderitem/ no such column: app_orderitem.rent
I just newly created this django project in which i added mulitple models & one of them is orderItem. this has a rent option. but from /admin i can't enter the orderItem option nor i can create any orderItem. there's was no data before i started my project. why is it showing me OperationalError at /admin/app/orderitem/ no such column: app_orderitem.rent error? class OrderItem(models.Model): customer = models.ForeignKey( User, on_delete=models.SET_NULL, null=True, blank=False) product = models.ForeignKey( Product, on_delete=models.SET_NULL, blank=True, null=True) order = models.ForeignKey( Order, on_delete=models.SET_NULL, null=True, blank=False) rent = models.BooleanField(blank=False, null=False) date_ordered = models.DateField(auto_now_add=True, blank=True) date_rented = models.DateField(null=True, blank=True) date_returned = models.DateField(null=True, blank=True) date = models.DateField(auto_now_add=True) def __str__(self): return str(self.product) + " Order: (" + str(self.order)+")" serializer.py class orderItemSerializers(serializers.ModelSerializer): class Meta: model = OrderItem fields = '__all__' views.py @api_view(['GET', 'POST']) def getOrderItemData(request): if request.method == 'GET': item = OrderItem.objects.all() serializer = orderItemSerializers(item, many=True) if request.method == 'POST': print(request.data) serializer = orderItemSerializers(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) -
How can I filter a Django queryset for the most appearing element?
I'm trying to filter one of my Django models for the most appearing element (in this case, the user with the most sales) and then sort it afterwards. After a bit of digging, I came to the following solution: best_seller = [seller for seller in Sale.objects.values_list("seller", flat=True).annotate(s_count=Count("seller")).order_by("-s_count")] seller is a column inside of my Sale table containing a User object. The given code only returns an array containing (probably?) the ID/IDs of the found users instead of the queryset itself. -
How to show alert messages with the buttons in "Change List" page in Django Admin?
There is Person model as shown below: # "app1/models.py" from django.db import models class Person(models.Model): first_name = models.CharField(max_length=20) last_name = models.CharField(max_length=20) And, there is Person admin as shown below: # "app1/admin.py" from django.contrib import admin from .models import Person @admin.register(Person) class PersonAdmin(admin.ModelAdmin): list_display = ('first_name', 'last_name') list_editable = ('first_name', 'last_name') list_per_page = 3 list_display_links = None ordering = ('id',) And, there is Change List page for Person admin as shown below: Then, an alert message is shown after changing the first or last names, then clicking on Go button as shown below: So now, how can I show the same alert message after changing the first or last names, then clicking on page numbers', Show all or ADD PERSON buttons as shown below: In addition, an alert message is shown after not changing the first or last names and selecting an Admin Action, then clicking on Save button as shown below: And, another alert message is shown after changing the first or last names and selecting an Admin Action, then clicking on Save button as shown below: So now again, how can I show the same 2 alert messages after not changing or changing the first or last names, then … -
How to display a Foreign key serializer as a dropdown?
I have three different models: class Province(Model): province = models.CharField(max_length=250) class BaseCase(ModelWithStamps): ... province = models.ForeignKey(Province, null=True, blank=True, on_delete=models.CASCADE) class Event(BaseEvent): .... @property def province(self): if hasattr(self, 'case'): return self.case.province return None @property def province_id(self): if hasattr(self, 'case'): return self.case.province.id return None And I have a serializer: class BaseEditCaseSerializer(...): .... province = serializers.ModelField(model_field=Case()._meta.get_field('province'), required=False, allow_null=True) class Meta: model = ManualEvent fields = (..., 'province') Even, the province is a foreign key, the province field is displayed as a "text field" in front end and I cannot change it from there. I want to display it as a dropdown (Province.objects.all()). How can I do it? -
Can I filter foreign keys in Django admin_
The Django admin interface allows to give defaults by using links like /admin/blog_app/post_model/add/?blog_id=1, so it is easy to create links for adding objects with pre-populated fields. I wonder if there is also a way to give filters for foreign fields. In the example link, I generate a link that can be used to pre-select a blog when creating a Post object by giving its ID. Now I would like to give another parameter to filter, e.g., the author field, like this: /admin/blog_app/post_model/add/?blog_id=1&author_filter=author__blog_id=1 such that the author dropdown only contains authors for the corresponding blog. Models for the example above: class Author(models.Model): blog = models.ForeignKey(Blog) # Possibly even a ManyToMany Field # Other fields like name, email, etc. class Post(models.Model): blog = models.ForeignKey(Blog) # preselected by URL parameter author = models.ForeignKey(Author) # field that should be filtered in admin, e.g., by author__blog_id # Other fields like content, category, tags, etc. -
Unable to import module 'vc__handler__python'
I am trying to deploy django web app through vercel. I have added django in requirements.txt file but it shows this error: [ERROR] Runtime.ImportModuleError: Unable to import module 'vc__handler__python': No module named 'django' Feel free to share if it can be fixed. -
I can't connect to the web socket in django
I can't connect to the web socket in django. This is asgi.py import os from django.core.asgi import get_asgi_application import api.routing from channels.routing import ProtocolTypeRouter, URLRouter, get_default_application from channels.auth import AuthMiddlewareStack from channels.security.websocket import AllowedHostsOriginValidator os.environ.setdefault("DJANGO_SETTINGS_MODULE", "back.settings") application = ProtocolTypeRouter({ 'http': get_asgi_application(), 'websocket': AllowedHostsOriginValidator( AuthMiddlewareStack( URLRouter( api.routing.websocket_urlpatterns ) ) ) }) This is routing.py from django.urls import path from . import consumers websocket_urlpatterns = [ path('socket-server', consumers.Consumers.as_asgi()) ] This is consumers.py from channels.generic.websocket import WebsocketConsumer import json class Consumers(WebsocketConsumer): def connect(self): self.accept() self.send(text_data=json.dumps({ 'type': 'connection_established', 'message': 'You are now connected!' })) def disconnect(self, close_code): pass def receive(self, text_data=None, bytes_data=None): text_data_json = json.loads(text_data) message = text_data_json['message'] self.send(text_data=json.dumps({ 'message': message })) This is settings.py # Application definition INSTALLED_APPS = [ "channels", "api", "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", 'rest_framework', 'corsheaders', ] ASGI_APPLICATION = 'back.asgi.application' CHANNEL_LAYERS = { "default": { "BACKEND": "channels.layers.InMemoryChannelLayer" } } I tried to connect the web socket through postman after writing the code in django as follows. However, a 404 not found error appears. I sent the request to ws://localhost:8000/socket-server url. What's the problem? python : 3.7.16 channels : 3.0.5 -
Django ManyToOne relationship
I'm building a django app, with mongoDB using djongo, when adding a student from the django admin interface which he have a parent like this: when i assign the parent to the student it cause this error Here's my django models: class User(AbstractBaseUser, PermissionsMixin): GENDERS = [ ('1', 'Male'), ('2', 'Female'), ] PAYMENTS = [ ('1', 'Monthly'), ('2', 'Yearly'), ('3', 'Freemuim'), ] id = models.AutoField(primary_key=True) firstname = models.CharField(max_length=30) lastname = models.CharField(max_length=30) phoneNumber = models.BigIntegerField() adress = models.CharField(max_length=50) username = models.CharField(max_length=15, unique=True) password = models.CharField(max_length=30) birthdate = models.DateField() gender = models.CharField(max_length=10, choices = GENDERS) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) is_active = models.BooleanField(default=True) date_joined = models.DateTimeField(default=timezone.now) attemps = models.IntegerField(default=3) payement_method = models.CharField(max_length=10, choices = PAYMENTS,default=3) payed = models.BooleanField(default=False) payment_date = models.DateTimeField(null=True) USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['password'] objects = CustomUserManager() class Parent(User): matricule = models.BigIntegerField() email = models.CharField(max_length=50) class Student(User): matricule = models.BigIntegerField() father = models.ForeignKey(Parent,on_delete=models.DO_NOTHING) I expect having a student with his parent registred in the database after submitting that form -
error on a code which automatically opens a websites and copies text from there
I have this code: import pyperclip import requests from bs4 import BeautifulSoup base_url = "https://www.bbc.com" url = base_url + "/news/world" response = requests.get(url) soup = BeautifulSoup(response.text, 'html.parser') articles = soup.find_all('div', class_='gs-c-promo-body') text = '' for article in articles: headline = article.find('h3', class_='gs-c-promo-heading__title') if headline: text += headline.text + '\n' summary = article.find('p', class_='gs-c-promo-summary') if summary: text += summary.text + '\n' link = article.find('a', class_='gs-c-promo-heading') if link: href = link['href'] if href.startswith('//'): article_url = 'https:' + href else: article_url = base_url + href article_response = requests.get(article_url) article_soup = BeautifulSoup(article_response.text, 'html.parser') article_text = article_soup.find('div', class_='story-body__inner') if article_text: text += article_text.get_text() + '\n\n' pyperclip.copy(text) The code I gave above is for example, let's say that I need to copy the text of each headline and the contents inside the headline. So I want to make a Python code that automatically goes to a website and then reproduces the head line, creates an empty line, and then creates another line with the contents given inside the headline. Traceback (most recent call last): File "C:\Users\msala\PycharmProjects\learnPython\venv\pythonProject1\lib\site-packages\urllib3\connection.py", line 200, in _new_conn sock = connection.create_connection( File "C:\Users\msala\PycharmProjects\learnPython\venv\pythonProject1\lib\site-packages\urllib3\util\connection.py", line 60, in create_connection for res in socket.getaddrinfo(host, port, family, socket.SOCK_STREAM): File "C:\Users\msala\AppData\Local\Programs\Python\Python39\lib\socket.py", line 954, in getaddrinfo for res in _socket.getaddrinfo(host, … -
Django served ods map tiles induce Edge's Visual Search tool
My Django project utilizes the opendatasoft map widget and had this "Visual Search" issue when viewing the site on MS Edge. After some investigation, I found out the problem is quite strange... Viewing the map just through Edge doesn't trigger the visual search on the map tiles. However, when viewing the exact same HTML content but served through Django, it does trigger it (see image) Does anyone know a way to deal with this? Using the pointer-events: none gimmick prevents you from using the map interactively altogether (on all browsers...). It would be great if I could just deactivate the tool altogether. -
How to enable external endpoint for Kubernetes servince in a Django project deployment?
I have a Django project with a CICD pipeline in GitLab that automatically builds an image from it and deploys it using Helm to my very barebone Kubernetes cluster. The VM, where the cluster is running, has IP 192.168.122.63 so I add externalIP to the service in order to be able to reach the project from any place outside the VM. Problem: If I don't add the IP address I have used with externalIP manually to the ALLOWED_HOSTS list, accessing the Django project fails with Invalid HTTP_HOST header: '192.168.122.163:8000'. You may need to add '192.168.122.163' to ALLOWED_HOSTS. Since I am already manually patching the service (until I figure out how to do it automatically :D), currently it's not such big of an issue to do that in the container or hardcode the IP in the settings.py. However this doesn't appear to be a long term solution so I am looking for a way to automatically whitelist the externalIP entry (entries if multiple!). -
Is it possible to convert an xlrd object to a win32com object
from win32com import client import xlrd I upload a excel file from a view (via a form) and thanks to xlrd, I am able to get the excel file object if request. Method == 'POST': my_xlsx = xlrd.open_workbook(file_contents=request. FILES['my_excel_document'].read(), on_demand=True) I would like to transform this xlrd object (xlrd.book.Book) to a win32com object without saving it. app = client. Dispatch("Excel.Application") sheets = app.Worbooks.Open(???) Is it possible? If so, how? -
How to prevent the text in Django Admin to get bigger when overriding "base.css" set in overridden "base.html"? [duplicate]
I could change the header color to black in all admin pages with the following steps. So, there is Person model as shown below: # "app1/models.py" from django.db import models class Person(models.Model): name = models.CharField(max_length=20) def __str__(self): return self.name Then, there is Person admin as shown below: # "app1/admin.py" from django.contrib import admin from .models import Person @admin.register(Person) class PersonAdmin(admin.ModelAdmin): pass Then, there is Person admin as shown below: Then, I copied base.css from django/contrib/admin/static/admin/css/base.css to core/static/core/admin/app1/css/ and copied base.html from django/contrib/admin/templates/admin/base.html to templates/admin/ as shown below: Django Project |-core | |-settings.py | └-static | └-core | └-admin | └-app1 | └-css | └-base.css # Here |-app1 | |-models.py | └-admin.py |-app2 └-templates └-admin └-base.html # Here Then in base.css, I replaced background: var(--header-bg); with background: black; as shown below: /* "core/static/core/admin/app1/css/base.css" */ #header { /* background: var(--header-bg); */ background: black; } Then in {% static %} in base.html, I replaced admin/css/base.css with core/admin/app1/css/base.css as shown below to change the header color to black in all admin pages: # "templates/admin/base.html" # ... {# "admin/css/base.css" is replaced #} <title>{% block title %}{% endblock %}</title> {# ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ #} … -
I am new to django, and I have a problem for some reason, a dot appears in the top left corner of the site itself. Help solve the problem [closed]
enter image description here here is a photo of the site I don't understand what the problem is if there is very little text in the html and css code so that I don't see this dot. -
Django Rest Framework: Saving Nested Serializer Workaround
Question: I need to save several objects using nested serializers using DRF. Documentation about saving nested serializers seems to be incomplete. Workarounds suggested in this and this answers do not seem to follow Python's encapsulation principle. As if we treat serializer as an object that encapsulates CRUD of a certain model, it is counter-intuitive to perform an object creation in serializer that "belongs" to another model. In-detail explanation of a question: Lets say we have two models: class A: content = models.CharField() class B: content = models.CharField() relation = models.ForeignKey('A') And two corresponding serializers: class BSerializer(ModelSerializer): class Meta: model = B fields = '__all__' class ASerializer(ModelSerializer): b_field = BSerializer(many=True) class Meta: model = A fields = '__all__' Sample of JSON that has to be saved: { "content": "sample", "b_field": [ { "content": "sample" }, { "content": "sample" } ] } Using the workarounds suggested here and here, I have to override create method of ASerializer to smth like this: class ASerializer(ModelSerializer): b_field = BSerializer(many=True) class Meta: model = A fields = '__all__' def create(self, validated_data): b_field_data = validated_data.pop('b_field', None) instance = super().create(validated_data) if b_field_data: for obj in b_field_data: B.objects.create( content=obj.content, relation=instance ) return instance However, as I've already pointed out … -
How to write Model.clean() properly given invalid (unset) foreign-key form fields (Django)?
I have a model with required ForeignKey fields (null=False, blank=False by default) that ends up in a form in the admin UI. If I leave those fields blank in the admin UI and click "save", the form validation fails, but then the following unfortunate sequence happens: Those fields are not checked by model clean fields (link): # Exclude fields that failed form validation. There's no need for # the model fields to validate them as well. elif field in self._errors: exclude.add(f.name) My custom model.clean is called with invalid form fields (docs). My custom model.clean raises an unexpected because it's checking invalid foreign key fields set to strings (the error messages of the fields). The workaround I found is to check if the field id is None (meaning the foreign key is not set), but it feels like a hack. Is there a better way to deal with this? -
getting this error "ValueError: The following fields do not exist in this model, are m2m fields, or are non-concrete fields: last_login"
i am trying to login user with otp and after checking the otp when i try to login a user with login method i get error on this line of my loginotp method -->login(request,user). i also added lastlogin field but nothing changes it gives same error Here are my Custom User model: if request.method == "POST": mobile_number=request.session['mobile_number'] print(mobile_number) otp=request.POST.get('otp') try: user_profile=User_Profile.objects.get(Phone=mobile_number) print(user_profile.Otp) except ObjectDoesNotExist: messages.error(request,"Invalid mobile nummber") return redirect('login_with_otp') if otp!=str(user_profile.Otp): print(type(otp)) print(type(user_profile.Otp)) print(otp) print(user_profile.Otp) messages.error(request,"Invalid OTP oh") return redirect('login_with_otp') user_profile.Otp=None user_profile.save() print(user_profile.id) user_profile = User_Profile.objects.get(Email=user_profile.User_id) print("user object : ",type(user_profile)) print(user_profile) login(request,user_profile) messages.success(request,"You are now logged in") return redirect('home') class User(AbstractUser): email = models.EmailField(max_length=75, unique=True) username= models.CharField(max_length=75) first_name = models.CharField(max_length=75, null=True, blank=True) last_name = models.CharField(max_length=75, null=True, blank=True) email_verified = models.BooleanField(default=False) last_login = models.DateTimeField(blank=True, null=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS= ['username'] i did everything but nothing changes error is as it is and also i found that error is caused by this line in models.py of django auth model File "C:\Users\rishi\Desktop\Hosted surginatal\env\Lib\site-packages\django\contrib\auth\models.py", line 23, in update_last_login user.save(update_fields=["last_login"]) -
Address in the DRF
I want the address to be a mandatory field at the time of user and bakery registration. My address fields are like this, but I am in doubt whether to put FALSE or leave without NULL and BLANK. Class User endereco = models.OneToOneField( Endereco, on_delete=models.CASCADE, related_name='user', null=True, blank=True ) Class Padaria endereco = models.OneToOneField( Endereco, on_delete=models.CASCADE, related_name='padaria', null=True, blank=True ) -
django-smart-selects un-selects values when editing
I have a django web site which uses django-smart-selects. In one of my models (for a coin which the user can add to a collection), the chained foreign keys are several levels deep: class CollectionMember(models.Model): country = models.ForeignKey( Country, blank=True, null=True, on_delete=models.SET_NULL ) coin_type = ChainedForeignKey( CoinType, chained_field="country", chained_model_field="country", show_all=False, auto_choose=True, blank=True, null=True, on_delete=models.SET_NULL, ) coin = ChainedForeignKey( CoinInfo, chained_field="coin_type", chained_model_field="coin_type", show_all=False, auto_choose=True, blank=True, null=True, on_delete=models.SET_NULL, ) mint = ChainedForeignKey( CoinMint, chained_field="coin", chained_model_field="coin", show_all=False, auto_choose=True, blank=True, null=True, on_delete=models.SET_NULL, ) When you initially enter the data, the chained selects work wonderfully (meaning that the general questions around "has it all been set up properly can be answered in the positive). But, when you then open the entry for edit - using the same form, only having the record added to it as "form instance", the AJAX sort of "jumps a bit" and loses the last two values. In other words, the record has country / coin_type / coin / mint and these initially all display for a second, then the selections on "coin" and "mint" get un-selected. There is a thread on the project site about this happening which is about 3 years old, but the resolution to it was an …