Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
React Query Not Returning Followings from Django API
I'm developing a React application that retrieves a user's followings from my Django backend API. However, I'm facing issues where the followings data is not being returned correctly. API Response When I make a GET request to the endpoint http://127.0.0.1:8000/api/chat/landing/, I receive a JSON response structured like this: { "current_followings": [ { "id": 1, "username": "Amir", "email": "Amir@amir.ir", "full_name": "amirali", "profile_photo": "/media/profile_photo/1000_F_244376003_1smlBNfWYSInMDUFymPuCcms6d1mOqaF_oU9kIP0.jpg", "banner_photo": "/media/banner_photo/header.jpg", "phone": null, "address": "", "bio": "", "profile_views": 1 } ], ... } The response includes an array of current_followings, each containing various fields like id, username, full_name, and profile_photo. Django views.py The view that handles this request is defined as follows: from rest_framework.views import APIView from rest_framework.permissions import IsAuthenticated from rest_framework.response import Response from .models import Follower, BasicUserProfile # Assuming these are defined elsewhere class ChatLandingView(APIView): permission_classes = [IsAuthenticated] def get(self, request): try: current_basic_user_profile = get_current_user_profile(request, User, BasicUserProfile) current_followings = Follower.objects.filter(follower=current_basic_user_profile).select_related('following') followings_serializer = BasicUserProfileSerializer([f.following for f in current_followings], many=True) data = { "current_followings": followings_serializer.data, ... } return Response(data, status=status.HTTP_200_OK) except ObjectDoesNotExist: return Response({"error": "Object not found"}, status=status.HTTP_404_NOT_FOUND) except Exception as e: return Response({"error": str(e)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR) This view checks for authenticated users and fetches their followings using the Follower model. It serializes the followings data before sending … -
Django Haitian Creole
I want to make a Django Project in Haitian Creole I am trying to create a django project in Haitian Creole. I put LANGUAGE_CODE = 'ht' USE_I18N = True USE_L10N = True USE_TZ = True in the settings.py I had installed gettext and run the follow command in my project folder django-admin makemessages -l ht But everytime I run my server it returns an error. Can somebody help me with this please? -
How to create a POST endpoint in Django with Tastypie
I'm learning Django and I watched and finished a tutorial (Mosh Hamedani and I purchased his videos) that created a database API GET method. I was curios how can I create a POST endpoint to add some new data. In the tutorial, he used tastypie module, if matters. In the tastypie's documents, I see it says how to add authorization, but it does not say anything about the POST. Please help me what's needed to add to and edit the question. This is api/models.py: from django.db import models from tastypie.resources import ModelResource from movies.models import Movie class MovieResource(ModelResource): class Meta: queryset = Movie.objects.all() resource_name = 'movies' excludes = ['date_created'] This is also movies/models: from django.db import models from django.utils import timezone class Genre(models.Model): name = models.CharField(max_length=255, default='Comedy') def __str__(self): return self.name class Movie(models.Model): title = models.CharField(max_length=255, default='Bararreh') release_year = models.IntegerField(default=2008) number_in_stock = models.IntegerField(default=100) daily_rate = models.IntegerField(default=150000) genre = models.ForeignKey(Genre, on_delete=models.CASCADE, default='Comedy') date_created = models.DateTimeField(default=timezone.now) These are the fields I have in the admin area to create a new movie. The main urls.py: from django.contrib import admin from django.urls import path, include from api_v1.models import MovieResource from . import views movie_resource = MovieResource() urlpatterns = [ path('', views.home), path('admin/', admin.site.urls), path('movies/', … -
NoReverseMatch at /manager/addVehicle/ Reverse for 'addVehicle' not found. 'addVehicle' is not a valid view function or pattern name
I started my first project in django and am facing the following error. Request Method: GET Request URL: http://127.0.0.1:8000/manager/addVehicle/ Django Version: 5.1.2 Exception Type: NoReverseMatch Exception Value: Reverse for 'addVehicle' not found. 'addVehicle' is not a valid view function or pattern name. Exception Location: C:\Users\\Documents\vehicle-share-system\.venv\Lib\site-packages\django\urls\resolvers.py, line 831, in _reverse_with_prefix Raised during: manager.views.addVehicle this is my views.py folder from django.shortcuts import render # Create your views here. def addVehicle(request): return render(request,'add_vehicle.html') my add_vehicle.html file `{% extends 'base.html'%} {% block content %} <h1>Add vehicle</h1> <br/><br/> <form method="POST" action= "{% url 'addVehicle' %}"> {% csrf_token %} <div class="mb-3"> <label for="Homelocation" class="form-label">Home location</label> <input type="text" class="form-control" id="HomeLocation" name="home_location"> </div> <div class="mb-3"> <label for="Model" class="form-label">Model</label> <input type="text" class="form-control" id="Model" name="model" > </div> <div class="mb-3"> <label for="Make" class="form-label">Make </label> <input type="text" class="form-control" id="make" name="make"> </div> <button type="submit" class="btn btn-primary">Submit</button> </form> {% endblock %}` urls.py from . import views from reservations.models import Reservations from reservations.models import vehicles urlpatterns=[ path('addVehicle/', views.addVehicle) ] I am getting the error even though the fn name in views file is the exact same. I have tried copy pasting the exact name and still don't know where i am going wrong. Any help will be greatly appreciated. -
Using Django JSONField Like a NoSQL Database for a Quiz Application
I'm developing a Django-based quiz website and would like to use a JSONField in the Quiz model to store questions in a manner similar to NoSQL databases like MongoDB. My plan is to store questions as JSON data directly in the Quiz model (e.g., questions=models.JSONField()). While this simplifies the structure and avoids joins, I'm concerned about how it will perform regarding querying and filtering capabilities. Given this approach, what are the pros and cons of using JSONField for a large dataset in Django? How can I optimize performance and scalability? Any advice or best practices for managing such a structure would be greatly appreciated. Thank you! -
Django upload file to Dropbox
Is there any way to upload file from Django to Dropbox as code below for your reference: Created one folder in root directory than copy all files from root directory to dropbox. TOKEN = "xxxxxxxx" LOCALFILE = os.path.join(settings.BASE_DIR, 'dcfiles') BACKUPPATH = "/Apps/backup/"# Keep the forward slash before destination filename dbx = dropbox.Dropbox(TOKEN) with open(LOCALFILE, 'rb') as file: response = dbx.files_upload(file.read(), BACKUPPATH) Error: Internal Server Error: /app01/strequest/ Traceback (most recent call last): File "/Users/imac/Desktop/Project/Test2/myenv/lib/python3.12/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) ^^^^^^^^^^^^^^^^^^^^^ File "/Users/imac/Desktop/Project/Test2/myenv/lib/python3.12/site-packages/django/core/handlers/base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/imac/Desktop/Project/Test2/myenv/lib/python3.12/site-packages/django/views/decorators/csrf.py", line 65, in _view_wrapper return view_func(request, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/imac/Desktop/Project/Test2/test2/app01/views.py", line 36, in strequest with open(LOCALFILE, 'rb') as file: ^^^^^^^^^^^^^^^^^^^^^ IsADirectoryError: [Errno 21] Is a directory: '/Users/imac/Desktop/Project/Test2/test2/dcfiles' -
Django admin inline performing too many queries when having additional ForeignKey
I have the following Django models: from django.db import models from django.utils.translation import gettext_lazy as _ class Enterprise(models.Model): nome = models.CharField(max_length=255) class MediaTopic(models.Model): name = models.CharField(max_length=255) class EnterpriseRelatedMedia(models.Model): enterprise = models.ForeignKey( Enterprise, on_delete=models.SET_NULL, null=True, blank=True, related_name="related_medias", related_query_name="related_media", ) topic = models.ForeignKey( MediaTopic, on_delete=models.DO_NOTHING, related_name="enterprise_related_medias", related_query_name="enterprise_related_media", blank=True, null=True, ) And this is my admin.py: from django.contrib import admin from . import models class EnterpriseRelatedMediaInline(admin.StackedInline): model = models.EnterpriseRelatedMedia extra = 1 @admin.register(models.Enterprise) class EnterpriseAdmin(admin.ModelAdmin): inlines = [ EnterpriseRelatedMediaInline, ] admin.site.register(models.MediaTopic) The problem is that since my inline contains not only the enterprise foreignkey but also an extra foreignkey pointing to MediaTopic, everytime my django admin change page loads, it makes a lot of queries to the database. Im aware that this is the famous N+1 problem, and that a select_related or prefetch_related would solve it, the problem is that i do not know where to put it, i tried putting it in the EnterpriseAdmin class as well as the EnterpriseRelatedMediaInline class, and it doesn't seem to work! Every time the admin loads the page, for each instance of the inline (which are 10), it makes a query to pull all the instances of MediaTopic to be available in the foreignkey attribute of … -
Django,pyinstaller,hidden import question
I tried to use pyinstaller to pack my project, And I meet this : `WARNING: Hidden import "usp.templatetags" not found! 155393 WARNING: Hidden import "django.contrib.contenttypes.context_processors" not found! 155395 WARNING: Hidden import "login.context_processors" not found! 155396 WARNING: Hidden import "django_apscheduler.templatetags" not found! 155411 WARNING: Hidden import "django.contrib.auth.templatetags" not found! 155412 WARNING: Hidden import "usp.context_processors" not found! 155412 WARNING: Hidden import "debug_toolbar.context_processors" not found! 155412 WARNING: Hidden import "django.contrib.staticfiles.templatetags" not found! 155689 WARNING: Hidden import "django.contrib.contenttypes.templatetags" not found! 155689 WARNING: Hidden import "login.templatetags" not found! 155695 WARNING: Hidden import "django.contrib.sessions.templatetags" not found! 155696 WARNING: Hidden import "django.contrib.staticfiles.context_processors" not found! 155696 WARNING: Hidden import "django_apscheduler.context_processors" not found! 155803 WARNING: Hidden import "importlib_resources.trees" not found!` I add the missed import to manage.spect, but it change from warning to error: `INFO: Analyzing hidden import 'usp.templatetags' 154547 ERROR: Hidden import 'usp.templatetags' not found 154547 INFO: Analyzing hidden import 'usp.context_processors' 154547 ERROR: Hidden import 'usp.context_processors' not found` then I tried venv, but it still report the same warning: `55393 WARNING: Hidden import "django.contrib.contenttypes.context_processors" not found! 155395 WARNING: Hidden import "login.context_processors" not found! 155396 WARNING: Hidden import "django_apscheduler.templatetags" not found! 155411 WARNING: Hidden import "django.contrib.auth.templatetags" not found! 155412 WARNING: Hidden import "usp.context_processors" not found! 155412 WARNING: Hidden import … -
Django + spatialite migration IntegrityError
When I modify a class/table with PolygonField, the migration stops with the following error: django.db.utils.IntegrityError: The row in table 'geometry_columns_statistics' with primary key 'new__mc_sitio_benfeitoria' has an invalid foreign key: geometry_columns_statistics.f_table_name contains a value 'new__mc_sitio_benfeitoria' that does not have a corresponding value in geometry_columns.f_table_name. My app is MC_SITIO and the class follows: class ImovelBase(ModelGis): """Base para Imóveis""" descricao = CharField(max_length=255, blank=False, null=True, verbose_name='descrição') administrador = ForeignKey(Pessoa, on_delete=SET_NULL, blank=True, null=True) RIP = CharField(max_length=255, blank=True, null=True, help_text='se for imóvel da União') codigo = CharField(max_length=255, blank=True, null=True, verbose_name='código, matricula, anúncio, ou outro documento') endereco = ForeignKey(Endereco, on_delete=SET_NULL, blank=True, null=True, verbose_name = 'endereço') poligono = PolygonField(srid=EPSG_SRID_PADRAO, blank=True, null=True, verbose_name='polígono') # area_total = UnumCharField(valid_unit=m**2, max_length=255, null=True, blank=True, verbose_name='área total', validators = [MinValueValidator(0.0)]) area_total = SympyCharField(max_length=255, null=True, blank=True, verbose_name='área total') VUP = DecimalField(null=True, blank=True, verbose_name='valor unitário padrão (VUP)', max_digits=11, decimal_places=2, validators = [MinValueValidator(0.0)]) indice_fiscal = DecimalField(null=True, blank=True, verbose_name='índice fiscal', max_digits=11, decimal_places=2, validators = [MinValueValidator(0.0)]) em_condominio = BooleanField(default=False, blank=True, verbose_name='em condomínio') observacoes = TextField(null=True, blank=True, verbose_name='observações') class Meta: abstract = True def __str__(self): return "{0}".format(self.descricao) def area(self): if self.poligono: return self.poligono.transform(get_SRID_UTM_WGS84(self.poligono.centroid), clone=True).area*m**2 return "S/N" @property def popupConteudo(self): return '<a href="/terreno-{}.html" target="_blank">{}</a>'.format(self.id, self.descricao) class TerrenoBase(ImovelBase): """Base para Terreno, tombo""" relevo = CharField(choices=RelevoClasse.choices, max_length=255, blank=True, null=True, verbose_name='classe do relevo') forma_regular … -
HOLA TENGO PROBLEMAS CON MI MODELS Y MI BASE DE DATOS MYSQL , NOSE QUE HACER AYUDAA
LA CUESTION QUE MI ME PASARON ESTE CODIGO PARA ARREGLARLO Y NO TENIA EL PRECIO_PROVEEDOR QUE YO LO VINCULE AL PRECIO DE LA APP DE PROVEDORES , EN LA CUAL ESTA LA TABLA PROVEDORESINSUMO Y TIENE LA COLUMNA LLAMADA PRECIO Y LAS VINCULES Y SIN LA BASE DE DATOS TODO ME FUNCIONABA , ya no me funciona nada D: enter image description here y este es la estructura de la base antigua enter image description here y en esta , yo no le agregue la tabla solo queria insertar los datos y agregarle el ,null nose pense que iba a funcionar y no funciono D: enter image description here pero no me funciona y me sale error todo D: espero que se me pueda arreglar y ya no tener problemas con la base de datos D: -
How to handle file upload of a certain type and size? (Looking for Best Practices / Convention)
I have the following column definition in my Django model media = models.FileField() I want to ensure that only video files (preferably in MP4 format) can be uploaded. Additionally, is it possible to set a maximum file size, like 200 MB? Would this approach create extra load on the server, since it would need to validate the MIME type and check that the file size doesn’t exceed the limit? I know client-side checks aren’t secure on their own since they can be bypassed, but does the csrf_token help address this on the backend? -
Django manage.py migration related commands not returning anything
I had an issue with migrations in a project I'm working on, a migration was deleted manually and the sync was ruined, I tried a lot of solutions but nothing worked and at the end I decided to backup the DB and delete all migrations and drop the django_migrations table from the MySQL db, now when I try to run any command like python manage.py makemigrations or python manage.py migrate nothing appears in stdout or stderr, absolutely nothing, not even an error, which has been puzzling me I can provide any information needed but I don't really know where to start here really, Any help would be appreciated a lot. -
How to create a POST endpoint in Django with Tastypie
I'm learning Django and I watched and finished a tutorial (Mosh Hamedani and I purchased his videos) that created a database API GET method. I was curios how can I create a POST endpoint to add some new data. In the tutorial, he used tastypie module, if matters. I know you need data, but I don't know what data is needed to provide you. Please help me what's needed to add to and edit the question. Update 1 This is api/models.py: from django.db import models from tastypie.resources import ModelResource from movies.models import Movie class MovieResource(ModelResource): class Meta: queryset = Movie.objects.all() resource_name = 'movies' excludes = ['date_created'] This is also movies/models: from django.db import models from django.utils import timezone class Genre(models.Model): name = models.CharField(max_length=255, default='Comedy') def __str__(self): return self.name class Movie(models.Model): title = models.CharField(max_length=255, default='Bararreh') release_year = models.IntegerField(default=2008) number_in_stock = models.IntegerField(default=100) daily_rate = models.IntegerField(default=150000) genre = models.ForeignKey(Genre, on_delete=models.CASCADE, default='Comedy') date_created = models.DateTimeField(default=timezone.now) These are the fields I have in the admin area to create a new movie. -
Bootstrap nav collapse toggle button not appearing or working
I am just starting out and I am trying to figure this out before completely scrapping the feature. Everything I look up online has no effect and I am lost as to what could possibly be causing this. Here is my code: <body> <nav class="navbar navbar-expand-lg navbar-dark fixed-top"> <a href="{% url 'home' %}" class="navbar-brand"> Inventory App </a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarNav"> <ul class="navbar-nav"> <li class="nav-item"> <a href="{% url 'product_create' %}" class="nav-link"> Add Product </a> </li> <li class="nav-item"> <a href="{% url 'product_list' %}" class="nav-link"> Show Products </a> </li> </ul> </div> </nav> <div class="container"> {% block content %} {% endblock %} </div> <script src="https://code.jquery.com/jquery-3.7.1.slim.min.js" integrity="sha256- kmHvs0B+OpCW5GVHUNjv9rOmY0IvSIRcf7zGUDTDQM8=" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.5.2/dist/js/bootstrap.min.js"></script> I have tried using defer, I used the full jquery rather than slim, made sure jquery is before bootstrap, I changed data-toggle to data-bs-toggle also with target, I tried putting everything in a div container and all that did was change the positioning. I have yet to see the nav toggle button even appear on the website yet. -
Error 199 in JazzCash Sandbox Testing During Django Integration
I'm trying to integrate the JazzCash Payment Gateway with my Django project using the HTTP POST Redirect method, but I'm encountering Error 199 from their portal. I've followed the setup in their documentation and am testing using their sandbox environment. Code: Below is a snippet of my integration code, followed by the error response JSON. from django.views.decorators.csrf import csrf_exempt from django.shortcuts import render from datetime import datetime, timedelta import hashlib import hmac JAZZCASH_MERCHANT_ID = "" JAZZCASH_PASSWORD = "" JAZZCASH_RETURN_URL = "" JAZZCASH_INTEGRITY_SALT = "" def calculate_jazzcash_secure_hash(request_data, integrity_salt): sorted_data = {k: v for k, v in sorted(request_data.items()) if k != "pp_SecureHash"} final_string = integrity_salt + '&' + '&'.join(str(v) for v in sorted_data.values() if v) secure_hash = hmac.new( integrity_salt.encode(), final_string.encode(), hashlib.sha256 ).hexdigest().upper() return secure_hash def checkout(request): product_name = "Sample Product" product_price = 100 pp_Amount = int(product_price * 100) # in paisa current_datetime = datetime.now() pp_TxnDateTime = current_datetime.strftime('%Y%m%d%H%M%S') pp_TxnExpiryDateTime = (current_datetime + timedelta(hours=1)).strftime('%Y%m%d%H%M%S') pp_TxnRefNo = 'T' + pp_TxnDateTime post_data = { "pp_Version": "1.1", "pp_TxnType": "MWALLET", "pp_Language": "EN", "pp_MerchantID": JAZZCASH_MERCHANT_ID, "pp_SubMerchantID": "", "pp_Password": JAZZCASH_PASSWORD, "pp_BankID": "TBANK", "pp_ProductID": "RETL", "pp_TxnRefNo": pp_TxnRefNo, "pp_Amount": pp_Amount, "pp_TxnCurrency": "PKR", "pp_TxnDateTime": pp_TxnDateTime, "pp_BillReference": "billRef", "pp_Description": "Test transaction", "pp_TxnExpiryDateTime": pp_TxnExpiryDateTime, "pp_ReturnURL": JAZZCASH_RETURN_URL, "ppmpf_1": "1", "ppmpf_2": "2", "ppmpf_3": "3", "ppmpf_4": "4", "ppmpf_5": … -
Cronjob in Docker container uses outdated settings in Django, despite environment variables in Docker Compose
I'm facing a persistent issue with a Django app using Django REST Framework. The application has several models, including one called Project with a created_at timestamp. There’s a management command in manage.py that archives a project if a user hasn't taken action on it within 72 hours of its creation. This command is executed by a cronjob in production, and the entire setup runs within a Docker container. Initial Setup In the past, I separated the back-end environment into two Docker containers: One container ran the Django application and served the API. The other container was dedicated solely to running the cronjob that executed these management commands. Reason for Combining Containers This setup had the same issue with outdated settings, and managing both containers separately added significant overhead, as I needed to clear both containers’ caches and rebuild them frequently. To simplify, I combined the API and cronjob into a single container and used Supervisor to manage the cronjob within this container. Note that Supervisor is functioning correctly, as the cronjob itself runs on schedule (logs confirm this), but it’s only an environment variable issue within the cronjob. The Problem The cronjob uses outdated settings—specifically an old DB_HOST that points … -
Updating User Profile Logs Out User in Django and Does Not Save Changes
I am working on a Django app with two apps: user for profile management and blog for posts. When a logged-in user tries to update their profile, they are unexpectedly logged out, and the changes are not saved. But it is working when it is done from the admin page. I've included the relevant views, models, forms, and settings below. I am new to django and this is my first project in the same. views.py from django.shortcuts import render, redirect from .forms import UserRegisterForm, UserUpdateForm, ProfileUpdateForm from django.contrib import messages from django.contrib.auth.decorators import login_required def profile(request): if request.method == 'POST': u_form = UserUpdateForm(request.POST, instance=request.user) p_form = ProfileUpdateForm(request.POST, request.FILES, instance=request.user.profile) if u_form.is_valid() and p_form.is_valid(): u_form.save() p_form.save() messages.success(request, 'Your profile has been updated!') return redirect('profile') else: u_form = UserUpdateForm(instance=request.user) p_form = ProfileUpdateForm(instance=request.user.profile) context = {'u_form': u_form, 'p_form': p_form} return render(request, 'user/profile.html', context) models.py from django.db import models from django.contrib.auth.models import User from PIL import Image class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='default.jpg', upload_to='profile_pics') def __str__(self): return f'{self.user.username} Profile' forms.py from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm from .models import Profile class UserRegisterForm(UserCreationForm): email = forms.EmailField() class Meta: model = Userfields = ['username', 'email', 'password1', 'password2'] … -
How to cache django forms?
I use Redis for caching data. But I display forms with dropdown list (ForeignKey objects). That's why i have 2 more sql requests for Book model (where i have author and genre as ForeignKeys) and OrderItem model (where i have bill and book as ForeignKeys). I wanna cache them too for increasing app's speed. I have this mixin: class ModelFormMixin: def post(self, request, *args, **kwargs): self.object_list = self.get_queryset() form = self.get_form() if form.is_valid(): form.save() queryset_cache_key = f'{self.model.__name__}_queryset' cache.delete(queryset_cache_key) return self.form_valid(form) else: return self.form_invalid(form) And these forms: from typing import Type from django import forms from django.forms import ModelForm from .models import Book, Author, Genre, OrderItem, Bill class DynamicModelForm(ModelForm): class Meta: model = None fields = '__all__' @classmethod def create(cls, _model: Type): class Meta(cls.Meta): model = _model form_class = type(f"{_model.__name__}Form", (cls,), {'Meta': Meta}) return form_class class OrderItemForm(DynamicModelForm.create(OrderItem)): price = forms.DecimalField( max_digits=5, decimal_places=2, label='Ціна', # price required=False, disabled=True ) def clean(self): cleaned_data = super().clean() quantity = cleaned_data.get('quantity') book = cleaned_data.get('book') if book and quantity: cleaned_data['price'] = book.price * quantity else: cleaned_data['price'] = 0 return cleaned_data Here's example of my view: class BookView(ModelContextMixin, ModelFormMixin, ModelSuccessUrlMixin, generic.edit.FormMixin, generic.ListView):x model = Book template_name = 'base/books.html' form_class = DynamicModelForm.create(Book) extra_context = {'add_button_name': 'Додати нову книгу'} # … -
Getting integer value from models.PositiveIntegerField() (Django)
I making my first big project(before i was just learning and making simple tasks) so I have some issues, but thats great! But only when there are answers in web - but now I couldn't find them.. I need to do some math with PositiveIntegerField's value as python integer, but I can't find any ways to do it. Here i have some class(not all code and changed names): class SomeClass(models.Model): par = models.PositiveIntegerField() #Making field thar I will compile below class SomeAnotherClass(models.Model): q = models.PositiveIntegerField() w = models.PositiveIntegerField() e = models.PositiveIntegerField() r = models.PositiveIntegerField() t = models.PositiveIntegerField()# Some things i need all = [q,w,e,r,t] counter = 0 if q!=0: counter+=1 if w!=0: counter+=1 if e!=0: counter+=1 if r!=0: counter+=1 if t!=0: counter+=1 #IDK how to make it more elegant..(helping with that is appreciated) if SomeClass.par*counter<=sum(all_rounds[:counter]):# And here are 2 errors, out of <TypeError: unsupported operand type(s) for *: 'DeferredAttribute' and 'int'> and <TypeError: unsupported operand type(s) for +: 'int' and 'IntegerField'> to_par=f'+{sum(all_rounds[:counter])-SomeClass.par*counter}'#Same here if SomeClass.par*counter>sum(all_rounds[:counter]):#Here to_par=f'-{SomeClass.par*counter-sum(all_rounds[:counter])}'#And here So my only reason of errors is that I can't convert from IntegerField to simple python integer... (I tried some ways my self and from web, but now I'm here) Here are 2 … -
requests on django api by javascript with CORS error
I have a web application for many years that uses Django and Django Rest Framework. The API is used by a python application and it works correctly: import requests response = requests.options(http://example.com/api/albums/) 200 {'name': 'Album List List', 'description': '', 'renders': ['application/json', 'text/html'], 'parses': ['application/json', 'application/x-www-form-urlencoded', 'multipart/form-data'], 'actions': {'POST': .... I discovered Svelte and I wanted to work with this API but impossible: let api_ = "http://example.com/api/albums/" const getAlbums = async () => { var response = await fetch(api, { mode: 'cors', method: 'GET', headers: { 'Content-Type': 'application/json'}}); var result = await response.json(); return result.results; Cross-Origin Request Blocked: The “Same Origin” policy does not allow viewing the remote resource located at http://example.com/api/albums/. Reason: The “Access-Control-Allow-Origin” CORS header is missing. Status Code: 200. I read that you need to install django-cors-headers. but now I have this error: Exception in thread django-main-thread: Traceback (most recent call last): File "/home/vianney/Documents/.blog/lib/python3.10/site-packages/django/template/utils.py", line 69, in __getitem__ return self._engines[alias] KeyError: 'django' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/vianney/Documents/.blog/lib/python3.10/site-packages/django/template/backends/django.py", line 174, in get_package_libraries module = import_module(entry[1]) File "/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 … -
Django: Mailgun is stripping out a tags in my email
I have this email template <p>If you have any questions or would like feedback on your profile, please do not hesitate to contact us. To make the changes, you can go <a href="https://languageloom.academy/teacher/edit-profile/">here</a> to view and manage your account.</p> but when I send the email like this @shared_task def send_email_task( subject: str, message: str, from_email: str, recipient_list: list[str], html_message: str = None, ): """ A Celery task to send an email. :param subject: Subject of the email. :param message: Body of the email (plain text). :param from_email: Sender's email address. :param recipient_list: A list of recipient email addresses. :param html_message: HTML content of the email (optional). :return: True if the email is sent successfully, False otherwise. """ try: msg = EmailMultiAlternatives(subject, message, from_email, recipient_list) # Attach HTML content if provided if html_message: msg.attach_alternative(html_message, "text/html") msg.send() return True except smtplib.SMTPException as e: logger.error(f"Email sending failed: {e}") return False it sends the email successfully but the a tag has its href stripped out In my mailgun settings I dont have any tracking enabled. -
Django Migration file not being created despite showing its name and changes
It started seemingly out of nowhere, I'm unable to trace the origins of this issue but yesterday I made migrations just fine and I'm the only working on the project as of now, when I run python manage.py makemigrations it shows: Migrations for 'app_name': app_name/migrations/0XXX_Do_stuff.py - Add field - Remove field - Alter field - Create model - Add field x to model` When running migrations this shows up: Operations to perform: Apply all migrations: things, things Running migrations: No migrations to apply. Your models in app(s): 'app_name', 'app_name_too' have changes that are not yet reflected in a migration, and so won't be applied. Run 'manage.py makemigrations' to make new migrations, and then re-run 'manage.py migrate' to apply them. I can provide any code needed but I honestly don't even know where to start, Any help would be appreciated. I use MySQL. -
Django model filter for string
I have table which has string such as id | url 1 | /myapi/1241/ 2 | /myapi/ 3 | /myapi/1423/ 4 | /myapi/ Now I want to filter them like this below myModel.Objects.filter(url="/myapi/****/") Is it possible , or is there any method to do this? -
How to change the color of a shapefile layer in Django Admin's Leaflet map based on a field's value?
I'm working on a GeoDjango project where I'm displaying a shapefile layer in a Leaflet map embedded in the Django Admin interface. I need to dynamically color the geometry (geom field) in the map based on the value of another field in the model called mean_ctrl. Django Admin with Geom Field Here’s the color scheme I want to implement: def get_color(mean_ctrl): if mean_ctrl < 60: return "#38A800" elif 60.1 <= mean_ctrl <= 120: return "#55FF00" elif 120.1 <= mean_ctrl <= 170: return "#FFFF00" elif 170.1 <= mean_ctrl <= 220: return "#FFAA00" elif 220.1 <= mean_ctrl <= 270: return "#FF0000" else: return "#C500FF" I am looking for guidance on how to apply this color scheme to the Geom field on the Leaflet map in Django admin. Any guidance would be very helpful! Thank you. -
How to get all fields with choices in a Django model?
I have a Django model with dozen fields with Choice options and I want to serialize their values to write an CSV file. How can I traverse the fields to find the ones with Choices options? Something like that: for field in MyModel._meta.fields: if field.has_choices_on_it(): print(f.name)