Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ValueError: Field 'id' expected a number but got 'str' in Grappelli related field
I'm using grappelli and faced with problem. I have foreign key 'owner' in model hence foreign key related field in django admin add form. When attempting to input symbols in this field I got this error and the problem is in grappelli related field. enter image description here enter image description here Do you have any suggestions/solutions? -
Why the Django Local Server is not running?
TypeError: view must be a callable or a list/tuple in the case of include(). trying to run server and live the django project -
How to check given date is sunday or not in dajngo
Here i am getting a list of dates check whether the day is sunday or not date_list = ['2023-03-17', '2023-03-18', '2023-03-19', '2023-03-20'] Now check each date's days and if date is sunday return that date (using for loop) -
ERROR recieved: django.db.utils.IntegrityError: FOREIGN KEY constraint failed in a MultiUser Django setup
I have been trying to set up DjangoRESTframework as a backend of my project. While defining my model, and then creating a superuser via the terminal, I received the the following error (as mentioned in the title of question) what my code looks like (models.py) The Wallet Model: class Wallet(models.Model): user = models.OneToOneField( "CustomUser", on_delete=models.CASCADE, primary_key=True ) balance = models.DecimalField(max_digits=10, decimal_places=2, default=0) transactions = models.ManyToManyField("Transaction") def __str__(self): return f"{self.user.username}'s wallet" The Transaction model: class Transaction(models.Model): sender = models.ForeignKey("CustomUser", on_delete=models.CASCADE, related_name="sender", db_constraint=False) receiver = models.ForeignKey("CustomUser", on_delete=models.CASCADE, related_name="receiver", db_constraint=False) timestamp = models.DateTimeField(default=timezone.now) transaction_amount = models.DecimalField(max_digits=10, decimal_places=2) transaction_id = models.CharField(max_length=TXN_ID_LENGTH, primary_key=True, unique=True) # status of the transaction SUCCESS = 0 FAILED = 1 PENDING = 2 IN_REVIEW = 3 TRANSACTION_STATUS = [ (SUCCESS, "Success"), (FAILED, "Failed"), (PENDING, "Pending"), (IN_REVIEW, "In Review"), ] transaction_status = models.IntegerField(choices=TRANSACTION_STATUS, default=PENDING) class Meta: unique_together = ('sender', 'receiver', 'transaction_id') def __str__(self): return f"{self.transaction_id} - {self.transaction_status}" def clean(self): if self.transaction_amount < 0: raise ValidationError("Transaction amount cannot be negative") if self.sender == self.receiver: raise ValidationError("Sender and receiver cannot be the same") if self.sender.wallet.balance < self.transaction_amount: raise ValidationError("Insufficient balance") def save(self, *args, **kwargs): self.clean() if not self.transaction_id: self.transaction_id = generate_random_string(TXN_ID_LENGTH) self.sender.wallet.balance -= self.transaction_amount self.receiver.wallet.balance += self.transaction_amount self.sender.wallet.save() self.receiver.wallet.save() if self.sender.wallet.balance < 0: … -
django rest framework giving psycopg2 Error
End developers, I am a FE dev having trouble with setting up BE. I need to connect django project with my FE which uses React.js. I have installed all the required stuff and finally when I ran make runserver, it's giving me this error raise ImproperlyConfigured("Error loading psycopg2 module: %s" % e) django.core.exceptions.ImproperlyConfigured: Error loading psycopg2 module: No module named 'psycopg2' When I ran make install, I get another error, ~/.poetry/venv/lib/python3.10/site-packages/poetry/installation/chef.py:152 in _prepare 148│ 149│ error = ChefBuildError("\n\n".join(message_parts)) 150│ 151│ if error is not None: → 152│ raise error from None 153│ 154│ return path 155│ 156│ def _prepare_sdist(self, archive: Path, destination: Path | None = None) -> Path: Note: This error originates from the build backend, and is likely not a problem with poetry but with psycopg2 (2.9.5) not supporting PEP 517 builds. You can verify this by running 'pip wheel --use-pep517 "psycopg2 (==2.9.5) ; python_version >= "3.6""'. I am using Macbook Air M2, if that is related to my specific device. I am not sure what psycopg2 is and why I am getting this error. I just simply need my django project to run smoothly so that I can connect to it from FE. Can someone help me … -
VPS server nginx + gunicorn not rendering tiny.mce media form in django project
The problem is observed only on the production server. The nginx and gunicorn logs do not show any errors. I have not previously been involved in server administration and I don’t understand it at all. Recently, I independently launched the project on the server for the first time using ubuntu + nginx + gunicorn. At the same time, to be honest, I don’t remember if the problem has been observed from the very beginning or has appeared recently. I did not write anything about tiny.mce in the nginx and gunicorn configurations. And do I need to prescribe it? If I understand correctly, this is not necessary and django should do this work. If necessary to prescribe it, where to delegate it and what is the syntax for this? I will be grateful for any answer! -
How to add new folder in pycharm?
I am practicing django on pycharm , I want to add new folder in existing project but didn't getting any option to add new folder, how can I add? How to add new folder -
Docker - Unable to make URL Requests to outside sites
This is first Docker project and I am not an IT person. I installed Docker using Django Cookiecutter. https://cookiecutter-django.readthedocs.io/en/latest/deployment-with-docker.html All seems to be well until i try to do a URL request. I assume it is some port sort of thing? Just a simples request will not work. response = requests.get(url) Thanks. here is the local.yml: version: '3' volumes: prelim_local_postgres_data: {} prelim_local_postgres_data_backups: {} services: django: &django build: context: . dockerfile: ./compose/local/django/Dockerfile image: prelim_local_django container_name: prelim_local_django depends_on: - postgres - redis - mailhog volumes: - .:/app:z env_file: - ./.envs/.local/.django - ./.envs/.local/.postgres ports: - "8000:8000" command: /start postgres: build: context: . dockerfile: ./compose/production/postgres/Dockerfile image: prelim_production_postgres container_name: prelim_local_postgres volumes: - prelim_local_postgres_data:/var/lib/postgresql/data - prelim_local_postgres_data_backups:/backups env_file: - ./.envs/.local/.postgres ports: - "5432:5432" nginx-proxy: image: jwilder/nginx-proxy:alpine container_name: nginx-proxy ports: - "80:80" - "443:443" volumes: - /var/run/docker.sock:/tmp/docker.sock:ro # - ./certs:/etc/nginx/certs restart: always depends_on: - django whoami: image: jwilder/whoami environment: - VIRTUAL_HOST=whoami.local mailhog: image: mailhog/mailhog:v1.0.0 container_name: prelim_local_mailhog ports: - "8025:8025" redis: image: redis:6 container_name: prelim_local_redis celeryworker: <<: *django image: prelim_local_celeryworker container_name: prelim_local_celeryworker depends_on: - redis - postgres - mailhog ports: [] command: /start-celeryworker celerybeat: <<: *django image: prelim_local_celerybeat container_name: prelim_local_celerybeat depends_on: - redis - postgres - mailhog ports: [] command: /start-celerybeat flower: <<: *django image: prelim_local_flower container_name: prelim_local_flower ports: … -
Python Django Profit Calculator
I trying to make a profit calculator in Python/Django. The user will input some values and then they will be redirect to another html that will show the user values plus calculations values. Is that the best way to do it? url image enter image description here forms from django import forms comissao_choices = ["1","2","3","4","5"] itbi_choices = ["1","2","3","4","5"] despesa_vendas_choices = ["1","2","3","4","5"] class InvestmentForm(forms.Form): comissao_leiloeiro_percentual = forms.ChoiceField(label = 'Comissão do Leiloeiro', choices = comissao_choices, required = True) itbi_percentual = forms.ChoiceField(label = 'ITBI * - Preencha o percentual da sua cidade, em São Paulo é 3%', choices = itbi_choices, required = True) despesa_venda_percentual = forms.ChoiceField(label = 'Na hipótese da venda ser intermediada por corretor informar a comissão',choices = despesa_vendas_choices, required = True) arrematacao = forms.DecimalField(label='Valor da Arrematação (R$)', min_value=100, decimal_places=2, widget=forms.NumberInput(attrs={'class':'form-control', 'placeholder':'This field is required'})) valor_venal = forms.DecimalField(label='Valor Venal do Imóvel (R$)', min_value=100, decimal_places=2, widget=forms.NumberInput(attrs={'class':'form-control', 'placeholder':'This field is required'})) valor_esperado_venda = forms.DecimalField(label='Valor Esperado de Venda (R$)', min_value=100, decimal_places=2, widget=forms.NumberInput(attrs={'class':'form-control', 'placeholder':'This field is required'})) oficial_imissao = forms.DecimalField(label='Oficial (imissão na posse) (R$)', min_value=100, decimal_places=2, widget=forms.NumberInput(attrs={'class':'form-control', 'placeholder':'This field is required'})) carta_arrematacao = forms.DecimalField(label='Expedição da Carta de Arrematação (R$)', min_value=100, decimal_places=2, widget=forms.NumberInput(attrs={'class':'form-control', 'placeholder':'This field is required'})) honorarios_advocaticios = forms.DecimalField(label='Honorários Advocatícios (imissão na posse) (R$)', min_value=100, decimal_places=2, … -
html template is alright , but redirecting on the payments page is not working ... don't know why
`from django.shortcuts import render, redirect, HttpResponse from carts.models import CartItem from .forms import OrderForm import datetime from .models import Order Create your views here. def payments(request): return render(request, 'orders/payments.html') def place_order(request, total=0, quantity=0,): current_user = request.user cart_items = CartItem.objects.filter(user=current_user) cart_count = cart_items.count() if cart_count <= 0: return redirect('storx') delivery_charge = 40 grand_total = 0 tax = 0 for cart_item in cart_items: total += (cart_item.product.price * cart_item.quantity) quantity += cart_item.quantity tax = (2 * total)/100 grand_total = total + tax + delivery_charge if request.method == 'POST': form = OrderForm(request.POST) if form.is_valid(): data = Order() data.user = current_user data.first_name = form.cleaned_data['first_name'] data.last_name = form.cleaned_data['last_name'] data.phone = form.cleaned_data['phone'] data.email = form.cleaned_data['email'] data.address_line_1 = form.cleaned_data['address_line_1'] data.address_line_2 = form.cleaned_data['address_line_2'] data.country = form.cleaned_data['country'] data.state = form.cleaned_data['state'] data.city = form.cleaned_data['city'] data.zipcode = form.cleaned_data['zipcode'] data.order_note = form.cleaned_data['order_note'] data.order_total = grand_total data.tax = tax data.delivery_charge = delivery_charge data.ip = request.META.get('REMOTE_ADDR') data.save() yr = int(datetime.date.today().strftime('%Y')) dt = int(datetime.date.today().strftime('%d')) mt = int(datetime.date.today().strftime('%m')) d = datetime.date(yr,mt,dt) current_date = d.strftime("%Y%m%d") # 20230214 order_number = current_date + str(data.id) data.order_number = order_number data.save() order = Order.objects.get(user=current_user, is_ordered=False, order_number=order_number) context = { 'order': order, 'cart_items': cart_items, 'total': total, 'tax': tax, 'delivery_charge': delivery_charge, 'grand_total': grand_total, } return redirect('checkout') else: return redirect('checkout') return render(request, 'orders/payments.html', context) ` -
JWT always returns tokens of the superuser django, although normal user credentials are used
In my django application I have created two users a superuser and a normal one , the problem is that I always get the tokens of the superuser account even when I use the normal account credentials. I tried deleting the superuser and log in with the normal user account, I got a response saying no active user with credentials provided. Thank you , any help would be much appreciate -
Using autocomplete.ModelSelect2 with htmx functionality
I have a form in Django. Then, however, I tried to add autocomplete functionality. The search bar/autocomplete itself works, but the hx-get never fires the courses/ url. Version 1: Works as expected department = forms.ModelChoiceField( queryset=Department.objects.order_by('name'), initial = Department.objects.order_by('name').first(), widget=forms.Select(attrs={'class': 'custom-select mb-4', 'autocomplete': 'off', 'hx-get': '/courses/', 'hx-target': '#id_course'}) ) department = forms.ModelChoiceField( queryset=Department.objects.order_by('name'), initial = Department.objects.order_by('name').first(), widget=autocomplete.ModelSelect2(url='department-autocomplete', attrs={'class': 'custom-select mb-4', 'autocomplete': 'off', 'hx-get': '/courses/', 'hx-trigger': 'change', 'hx-target': '#id_course'}) ) -
Django render third argument
I am confused with Django renderring. In the code below the third argument used list name in strings and list name as a variable. Why so? from django.shortcuts import render my_playlists=[ {"id":1,"name":"Car Playlist","numberOfSongs":4}, {"id":2,"name":"Coding Playlist","numberOfSongs":2} ] def home(request): return render(request,'zing_it/home.html',{"my_playlists":my_playlists}) -
Django equivalent of sub query
I would like to ask if there is a different way to the following raw SQL query SQL query SELECT id, title, date_format(books.timestamp,"%%Y/%%m/%%d") AS timestamp, (SELECT count(*) FROM pages WHERE pages.book_id=books.id) AS page_count FROM books ORDER BY books.timestamp DESC LIMIT %s models.py class Book(models.Model): title = models.CharField(max_length=64) timestamp = models.DateTimeField(auto_now_add=True) class Page(models.Model): timestamp = models.DateTimeField(auto_now_add=True) book = models.ForeignKey(Book, on_delete=models.CASCADE) views.py def something(request): n_books = 10 books = Book.objects.raw(the_query, [n_books]) return render(request, "books/list.html", {"books":books}) I thought I could do this by using filter() but I don't know how to handle the sub query. Is there any Django equivalent way that uses only Python codes? Or is it better to use a raw SQL query? -
Trying to use an if statement that checks if user is friends and hide content on template page
I have a Friend model that has a variable to check if user is friends with another user. I've tested it out in shell and it works properly. When I try to implement this in my core app (they're in the same project, I just created a separate folder for my friend model), the template page only displays the 'send friend request' hyperlink even if the user is friends with the other user. I think there's an issue with my views.py snippet but I don't know how to debug it. When i try to use print() nothing shows up in my terminal. Could anyone please tell me how I can get this to work? Thanks class UserFriends(models.Model): user = models.OneToOneField( User, on_delete=models.CASCADE, related_name='user') friends = models.ManyToManyField(User, blank=True, related_name='friends') def __str__(self): return str(self.user) def is_friend(self, friend): """ Check if its in your friend list """ if friend in self.friends.all(): return True return False shell: >>> from django.contrib.auth.models import User >>> from friend.models import UserFriends >>> user1 = User.objects.create_user(username='user1', password='password') user2 = User.objects.create_user(username='user2', password='password') friend_list = UserFriends.objects.create(user=user1) friend_list.friends.add(user2)>>> user2 = User.objects.create_user(username='user2', password='password') >>> friend_list = UserFriends.objects.create(user=user1) >>> friend_list.friends.add(user2) >>> friend_list.is_friend(user2) True my views: from friend.models import UserFriends def profile(request, username): profile = … -
Cannot Import Models In Django
I am trying to import my models file into my api.py file but, I get this error: > from dashboard.models import Customer, Lines, Devices > ModuleNotFoundError: No module named 'dashboard' My apps.py is: from django.apps import AppConfig class DashboardConfig(AppConfig): name = 'dashboard' My settings: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sessions', 'dashboard' ] My models: from django.db import models class Customer(models.Model ): account_name = models.CharField(default='', max_length=254, null=True, blank=True) accountNumber = models.CharField(default='', max_length=30, null=True, blank=True) accountType = models.CharField(default='', max_length=40, null=True, blank=True) allowDangerousExtensions = models.BooleanField(default=False) billingCycleDay = models.IntegerField(default=0) @property def customer_name(self): return (self.account_name) class Lines(models.Model): accountId = models.CharField(default='', max_length=30, null=True, blank=True) deviceName = models.CharField(default='', max_length=10, null=True, blank=True) deviceTypeId = models.CharField(default='', max_length=100, null=True, blank=True) def __str__(self): return self.accountId() class Devices(models.Model): uid = models.CharField(default='', max_length=30, null=True, blank=True) online = models.BooleanField(default=False) customer = models.ForeignKey(Customer, blank=True, null=True, on_delete=models.CASCADE) def __str__(self): return self.name() and api.py: from dashboard.models import Customer, Lines, Devices def create_customer(): customer = Customer.objects.create() But I cannot reference the models in the api.py file. I can reference it in my Admin.py but, api.py does not work. -
What does Django do between authentication and view dispatch?
I am trying to diagnose some performance issues I'm having with Django (3.2.18), Graphene (2.1.8), and Graphene-Django (2.14.0) using datadog. I'm also using gunicorn as my web server and postgres as my db. When looking at the trace for some oddly long-running requests, I'm seeing that there is a long delay between when the django.contrib.auth.authenticate call completes and when my view class gets setup and dispatch is called. This delay can sometimes take as long as 20 seconds but most of the time takes 10s of milliseconds. Unfortunately, datadog is not giving me any additional insight into what is happening between the authenticate call and the dispatch as can be seen in this screenshot of a trace. I don't think this is an issue where I'm running out of gunicorn workers because I'm assuming that a worker already has possession of the request in order to perform the authentication logic but I'm happy to be corrected about a bad assumption. Any pointers as to what might be happening here would be greatly appreciated as I'm not really sure where to begin looking. -
500 errors when deleting a many to many relationship using django
I am building a small scale application with a many to many relationship named 'river_rapid'. I am able to see the rapid cards on the river details view on my front end, but am not sure I am 'getting' them correctly. I am ultimately trying to DELETE the relationship (delete a rapid card from river details without deleting the rapid entirely), and previously had been getting an 'unbound local' error (hence the commented out code). After trying several things to solve that error I am now getting the error of: randrapi.models.rapid.Rapid.DoesNotExist: Rapid matching query does not exist. [05/Mar/2023 22:02:15] "DELETE /rapids/11 HTTP/1.1" 500 98330 Here are my river_rapid views and models: from django.http import HttpResponseServerError from rest_framework.viewsets import ViewSet from rest_framework.response import Response from rest_framework import serializers, status from randrapi.models import River_Rapid, River, Rapid class RiverRapidView(ViewSet): def retrieve(self, request, pk): river_rapid = River_Rapid.objects.get(pk=pk) # river = River.objects.get(pk=pk) serializer = RiverRapidSerializer(river_rapid) print('retrieve') return Response(serializer.data) def list(self, request): # river = River.objects.all() # print(river) river_rapids = River_Rapid.objects.all() # print(river_rapids) # new_river_rapids = river_rapids.filter(river_id = river) # new_river_rapids = River_Rapid.objects.all() # new_river_rapids = request.query_params.get = ('river_rapids', None) # if new_river_rapids is not None: # new_river_rapids = river_rapids.filter(river_id = river) # print(new_river_rapids) # if … -
Where to securely store Google_Application_Credentials in Django project?
I have a Django project that uses the Google API. I created a docker-compose.yml which has my Django container and Nginx container. It builds successfully but when I run docker-compose up, I get following error: google.auth.exceptions.DefaultCredentialsError: File /file/path/credentials.json was not found. I have installed the Google SDK and ran 'gcloud auth application-default login' which creates the json file in my root directory. I then created an environment variable for it and configured my Django app. settings.py: GOOGLE_APPLICATION_CREDENTIALS = os.environ["GOOGLE_APPLICATION_CREDENTIALS"] I can open the credentials json file in my finder so I know it's there. The Google API is being used for secret manager to retrive secret keys: from google.cloud import secretmanager import environ env = environ.Env() environ.Env.read_env() def get_secret(secret_id, version_id="latest"): project_id = env("GOOGLE_PROJECT_ID") client = secretmanager.SecretManagerServiceClient() name = f"projects/{project_id}/secrets/{secret_id}/versions/{version_id}" response = client.access_secret_version(name=name) return response.payload.data.decode("UTF-8") Without running docker-compose up it works fine and I can retrieve keys but I want to test it out running my docker containers. My docker-compose.yml: version: '3' services: backend: build: context: ./ dockerfile: ./Dockerfile env_file: - ./backend/.env container_name: backend ports: - 8000:8000 nginx: build: context: ./nginx dockerfile: ./Dockerfile container_name: nginx ports: - 80:80 depends_on: - backend I even tried downloading the service account key which places … -
Django translation inside templates: unable to recognize variables from context dictionary and object attributes
I'm trying to use Django translation and {% translate %} tag inside my template files. Wherever I have some hard coded strings, things work just fine. The problem, however, occurs when I try to translate text from object attributes sent to the templates inside context dictionary. So I have a context dictionary like below: context = { 'object_list': <QuerySet[ <SiteDataKeyValue: some random text>, <SiteDataKeyValue: Some other random text>, <SiteDataKeyValue: and some more random text>, ], } And without translation, I access these objects very easily, for example: <h1>how I access the value of the objects:</h1> {% for object in object_list %} <p>{{ object.value }} </p> {% endfor %} Now, I try to use {% translate %} tag according to Django Docs, and I use the following syntax: <h1>how I access the value of the objects:</h1> {% for object in object_list %} <p>{% translate object.value %} </p> {% endfor %} But after running manage.py makemessages -l -i .venv command, Django fails to recognize {% translate object.value %} and show NO error message. After some research, I even tried using with command to render the object value inside a variable, as below: {% for object in object_list %} {% with value=object.value %} … -
Google Maps - How to draw a polygon and get vertex coords as result
I would like to implement google maps on my personal project (backend python-django). I have already read google maps platform documentations and I can't find the answer. How can I do (and is it possible?) that scenario: User draws a polygon on map. (I found drawing tool already, which seems perfect) At the same time or after finishing polygon, maps send vertex coords to backend. I do not have experience in front. At the beginning I need only basics. I thought using django template and implement google maps using html. But i don't know: How can I send that information (coords) to backend? Sorry for my poor English. -
Django - gettext_lazy not working in string interpolation/concatenation (inside list)
I have a dictionary of items with multiple properties. from django.utils.translation import ( gettext_lazy as _, ) {"item1": { "labels": [ _("label1"), "this is" + _("translatethis") + " label2", ] These items are then serialized in DRF. The problem is that _("label1") is being translated but "this is" + _("translatethis") + " label2" is not translated I tried also string interpolation, fstring and .format but nothing worked. When serializer fetches labels, _("translatethis") is not a proxy object. Is the only way to make this work surrounding whole strings in the gettext_lazy ? -
Django REST framework smiple jwt add custom payload data and access it in route
I am generating a custom jwt token for authentication using RefreshToken.for_user(user) at the time of login and registration. I can access user using request.user in the API endpoint but I also want to add user type in the payload data, so that I can access the user_type field in the API endpoint. This is what I am doing. def get_tokens_for_user(user): refresh = RefreshToken.for_user(user) return { 'refresh': str(refresh), 'access': str(refresh.access_token), class UserRegistrationView(APIView): def post(self, request, format=None): serializer.is_valid(raise_exception=True) token = get_tokens_for_user(user) return Response({ 'token':token }) Now at endpoint class FileDetail(APIView): permission_classes = (IsAuthenticated,) def get(self, request, pk): user = request.user user_type = request.user_type // this data I want to save in the payload and get here. so I want user_type and other data at API endpoint from jwt payload data -
Store image with mongoengine django
I am working on a project in which I have a Company template which contains a name, url and an image under a Mongoengine Document. I would like to know how to store the image in the MEDIA folder without having to store it in DB as with the django model that allows direct image upload only in the folder. Thanks to all I didn’t find any documentation on the mongoengine website or internet without storing it into db -
Django crontab ModuleNotFoundError: No module named 'fcntl'
I'm trying to run a cron job using django-crontab with Django REST framework. I followed all the setup steps described in the library on GitHub, but when I run this command: python manage.py crontab add I get the following error: ModuleNotFoundError: No module named 'fcntl' I'm working locally on Windows, but the project will be deployed to a Linux server. I heard that "The fcntl module is not available on Windows." My questions are: Should I run the project on a Linux docker container instead? Should I search for package similar to fcntl for Windows? Should I try with another cron job package instead of django-crontab? Does anyone have any suggestions?