Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ReactJS AXIOS doesn't fetch data from Django backend when page refreshes
I have been trying to fetch data from my backend, which is based on Python Django. I've noticed that the data is not fetched when page refreshes. I have tried multiple solutions from SO but nothing works. Can anyone help? import axios from "axios"; import React, { useState, useEffect } from "react"; import StatBox from "../components/StatBox"; function Bucketsize() { // State variable for storing data const [data, setData] = useState({size: '', unit: ''}); // Function to fetch data const fetchDevices = async () => { try { const res = await axios.post("http://127.0.0.1:8000/bucketsize/", {}); const size = res.data.size; const unit = res.data.unit; setData({ size, unit }); } catch(err) { console.error(err); } }; useEffect(() => { fetchDevices(); }, []); return ( <StatBox data={data.size} size={data.unit} heading="Bucket Size" /> ); } export default Bucketsize; I have tried to fetch data using an asynchronous function. Doesnt work. My backend has python files that fetches data from AWS Timestream everytime its executed. Note: The python scripts at the backend take around 5-10seconds to execute to fetch data from AWS -
Custom django_filters (how to sun filters result)
I have an analytics model: class StoreAnalytics(models.Model): class Meta: verbose_name_plural = "store's analytics" verbose_name = "store's analytics" store = models.ForeignKey(Store, on_delete=models.CASCADE, null=True, related_name="store_id") accruals_sum = models.DecimalField( max_digits=10, decimal_places=2, default=Decimal(0), verbose_name="Accruals sum" ) taxes_count = models.DecimalField(max_digits=7, decimal_places=2, default=Decimal(0), verbose_name="Taxes sum") sold_products = models.PositiveSmallIntegerField(default=0, verbose_name="Number of products sold") def __str__(self): return f"{self.store.pk}" My view: class StoreAnalyticsApi(ListCreateAPIView): permission_classes = (IsAuthenticated,) http_method_names = ["get"] serializer_class = StoreAnalyticsSerializer filter_backends = (DjangoFilterBackend,) filterset_class = StoreAnalyticsFilter def get_queryset(self): queryset = StoreAnalytics.objects.filter(store__user_id=self.request.user.pk).aggregate(accruals_sum=Sum(F("accruals_sum")), sold_products=Sum(F("sold_products")), taxes_summ=Sum(F("taxes_count"))) #{'accruals_sum': Decimal('10045'), 'sold_products': 68, 'taxes_summ': Decimal('602.700000000000')} return queryset By default, the GET method api/v1/analytics/ should return the sum of sold products, sum of taxes and sum of accruals for all existing user's stores. If a user wants to view statistics only for chosen stores, then he selects the store ids and he should get the total analytics for the selected stores. How should my filters.py look like to accruals tha aim? My filters: from dashboard.models import StoreAnalytics from django_filters import rest_framework as filters from django.db.models import Sum, F class ListFilter(filters.Filter): def filter(self, qs, value): if not value: return qs self.lookup_expr = "in" values = value.split(",") return super(ListFilter, self).filter(qs, values) class StoreAnalyticsFilter(filters.FilterSet): stores_ids = ListFilter(field_name="store_id") class Meta: model = StoreAnalytics fields = [ "stores_ids", ] … -
Multiple django apps in one django project
I have 3 applications(app1, app2, app3) in one django project(mydjango), each of these apps have different usage and different domains to be served (app1.domain.com; app2.domain.com; app3.domain.com) as it is single django project we have only one manage.py file. I am trying to deploy these using apache2 web server and all these 3 apps uses same virtualenv(using pyenv) and same mysql database with different tables. Now the problem is how to point these 3 domains to thier specific apps, can anyone please suggest a solution I tried few methods that suggested by chatgpt and other sources/articles from web, <VirtualHost *:80> ServerName domain1.com ServerAlias www.domain1.com DocumentRoot /path/to/your/project/<project_name> WSGIDaemonProcess domain1.com python-path=/path/to/your/project/<project_name>:/path/to/your/project/<virtualenv_name>/lib/python3.X/site-packages WSGIProcessGroup domain1.com WSGIScriptAlias / /path/to/your/project/<project_name>/app1/wsgi.py <Directory /path/to/your/project/<project_name>> Require all granted </Directory> </VirtualHost> <VirtualHost *:80> ServerName domain1.com ServerAlias www.domain1.com DocumentRoot /path/to/your/project/<project_name> WSGIDaemonProcess domain1.com python-path=/path/to/your/project/<project_name>:/path/to/your/project/<virtualenv_name>/lib/python3.X/site-packages WSGIProcessGroup domain1.com WSGIScriptAlias / /path/to/your/project/<project_name>/app2/wsgi.py <Directory /path/to/your/project/<project_name>> Require all granted </Directory> </VirtualHost> <VirtualHost *:80> ServerName domain1.com ServerAlias www.domain1.com DocumentRoot /path/to/your/project/<project_name> WSGIDaemonProcess domain1.com python-path=/path/to/your/project/<project_name>:/path/to/your/project/<virtualenv_name>/lib/python3.X/site-packages WSGIProcessGroup domain1.com WSGIScriptAlias / /path/to/your/project/<project_name>/app3/wsgi.py <Directory /path/to/your/project/<project_name>> Require all granted </Directory> </VirtualHost> here the suggested configuration shows 3 different "wsgi.py" files for 3 apps, but mydjango project created just one wsgi.py Now how should i modify the apache configuration. can anyone suggest some solution. Thanks in … -
why vagrant cannot open file (django api testing)
I am testing my django rest framework API on my windows 10 pc, then this problem make me crazy. I cannot run the server. 8000 port also does not work. Then I tries another API, which could work properly. I googled this problem, those solution did not work for me. I think it might be that the vagrant server cannot open lower level file. In this case, I have openned helloworld file and connect to vagrant. But finally, I still in the upper level of helloworld file. (helloworld, snippets and eshop are three seperate api, they have their own manage.py file) -
Django Ninja Testing
I am trying to create a test for an API I wrote using Django-Ninja. Here is my Model: class Country(models.Model): created_at = models.DateTimeField(auto_created=True, auto_now_add=True) name = models.CharField(max_length=128, null=False, blank=False) code = models.CharField(max_length=128, null=False, blank=False, unique=True) timezone = models.CharField(max_length=128, null=False, blank=False) Here is my schema: class CountryAddSchema(Schema): name: str code: str timezone: str Here is the post endpoint: uter.post("/add", description="Add a Country", summary="Add a Country", tags=["Address"], response={201: DefaultSchema, 401: DefaultSchema, 422: DefaultSchema, 500: DefaultSchema}, url_name="address_country_add") def country_add(request, country: CountryAddSchema): try: if not request.auth.belongs_to.is_staff: return 401, {"detail": "None Staff cannot add Country"} the_country = Country.objects.create(**country.dict()) the_country.save() return 201, {"detail": "New Country created"} except Exception as e: return 500, {"detail": str(e)} Finally, here the test function: def test_add_correct(self): """ Add a country """ data = { "name": "".join(choices(ascii_letters, k=32)), "code": "".join(choices(ascii_letters, k=32)), "timezone": "".join(choices(ascii_letters, k=32)) } respond = self.client.post(reverse("api-1.0.0:address_country_add"), data, **self.AUTHORIZED_HEADER) self.assertEquals(respond.status_code, 201) self.assertDictEqual(json.loads(respond.content), {"detail": "New Country created"}) the_country = Country.objects.last() self.assertDictEqual( data, { "name": the_country.name, "code": the_country.code, "timezone": the_country.timezone } ) Please notice I have self.AUTHORIZED_HEADER set in setUp. And here the error: FAIL: test_add_correct (address.tests_country.CountryTest) Add a country ---------------------------------------------------------------------- Traceback (most recent call last): File "SOME_PATH/tests_country.py", line 80, in test_add_correct self.assertEquals(respond.status_code, 201) AssertionError: 400 != 201 I can add a country … -
I want to put a custom message saying"Logged in successfully" and status code "1000 OK"post successful login in my Django Login API. I'm using Knox Vi [closed]
This is my views.py- class LoginAPI(KnoxLoginView): permission_classes = (permissions.AllowAny,) def post(self, request, format=None): serializer = AuthTokenSerializer(data=request.data) serializer.is_valid(raise_exception=True) user = serializer.validated_data['user'] login(request, user) return super(LoginAPI, self).post(request, format=None) This is my serializers.py- class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('password','username' ) extra_kwargs = {'password': {'write_only': True}} I've tried if-else statements and also Ive tried creating a dictionary and returning it -
Convert string datetime with 9 digits in last to ISO format datetime object in python
I have string datetime (eg: "2022-11-11T06:19:32.776289776Z"). I want to convert the same in ISO format. I tried below datetime.datetime.fromisoformat("2022-11-11T06:19:32.776289776Z") But it is throwing error. ValueError: Invalid isoformat string: '2022-11-11T06:19:32.776289776Z It is working if I give only 6 digits in the last without Z. However not working for the strings those I want to convert. eg: i/p-> datetime.datetime.fromisoformat("2022-11-11T06:19:32.776289") o/p-> datetime.datetime(2022, 11, 11, 6, 19, 32, 778394) -
Cannot resolve keyword 'ir' into field. Choices are: category, category_id, date, description, id, is_on_main, name, price, url
for some reason it does not see the ir field, although it exists. views.py def index(request): data = ( Product .objects.select_related('category') .filter(is_on_main=True) .values('pk','name','price','ir') ) categ = Category.objects.all() return render(request,'magazin/index.html',{'data' : data,'cat' : categ}) models.py(Product) class Product(models.Model): is_on_main = models.BooleanField(default=False) category = models.ForeignKey(Category, on_delete = models.CASCADE) name = models.CharField(max_length=50) price = models.IntegerField() date = models.DateTimeField(null = True,auto_now=True) url = models.SlugField(max_length=100,unique=True,null=True) description = models.TextField(max_length=2000,default='Описание') ir = timezone.now() - datetime.timedelta(minutes=30) def __str__(self): return self.name class Meta: ordering = '-date', index.html(part with data) {% for i in data %} <div> <h4><b>НАЗВАНИЕ: </b>{{i.name}}</h4> <h4><b>ЦЕНА: </b>{{i.price}}</h4> <a href="{% url 'detail' pk=i.pk %}">ПОДРОБНЕЕ</a> {% if i.date >= i.ir %} <h1 class="r">НЕДАВНО В ПРОДАЖЕ!</h1> {% endif %} <hr> </div> thank you in advance -
I am having errors in running the command pip install face_recognition
I am trying to install face_recognition into my project and thus I am running the command 'pip install face_recognition' in the terminal, but I am having this error(I have installed cmake): in short : ERROR : Could not build wheels for dlib, which is required to install pyproject.toml-based projects Whole Error : Building wheel for dlib (pyproject.toml) ... error error: subprocess-exited-with-error × Building wheel for dlib (pyproject.toml) did not run successfully. │ exit code: 1 ╰─> [314 lines of output] running bdist_wheel running build running build_ext Building extension for Python 3.8.8 (default, Apr 13 2021, 15:08:03) [MSC v.1916 64 bit (AMD64)] Invoking CMake setup: 'cmake C:\Users\Shashwat\AppData\Local\Temp\pip-install-gem29hzl\dlib_bd69ef4fa75e4a58a152da24ab42b4d5\tools\python -DCMAKE_LIBR ARY_OUTPUT_DIRECTORY=C:\Users\Shashwat\AppData\Local\Temp\pip-install-gem29hzl\dlib_bd69ef4fa75e4a58a152da24ab42b4d5\build\lib.win-amd64-cpython-38 -DPYTHON _EXECUTABLE=C:\ProgramData\Anaconda3\python.exe -DCMAKE_LIBRARY_OUTPUT_DIRECTORY_RELEASE=C:\Users\Shashwat\AppData\Local\Temp\pip-install-gem29hzl\dlib_bd69 ef4fa75e4a58a152da24ab42b4d5\build\lib.win-amd64-cpython-38 -A x64' -- Building for: Visual Studio 17 2022 -- Selecting Windows SDK version 10.0.22000.0 to target Windows 10.0.22621. -- The C compiler identification is MSVC 19.36.32534.0 -- The CXX compiler identification is MSVC 19.36.32534.0 -- Detecting C compiler ABI info -- Detecting C compiler ABI info - done -- Check for working C compiler: C:/Program Files/Microsoft Visual Studio/2022/Community/VC/Tools/MSVC/14.36.32532/bin/Hostx64/x64/cl.exe - skipped -- Detecting C compile features -- Detecting C compile features - done -- Detecting CXX compiler ABI info -- Detecting CXX compiler ABI info - done -- … -
How to optimize value to range comparison using Django ORM
(First time posting here, so apologies in advance) I would like to get the names and number of events for top 10 countries over a specific time period (last 1, 3, 7, 30 and 90 days). My current solution works, but is too slow for the number of events I receive (about 500 per hour). Using Python 3.11.4 and Django 4.1.7 with a MySQL database. Test Here is a test with the events from the last day (8,802). The timing may not be overly precise, as it was done with the simple datetime.now() - start method. Retrieve events: 0:00:00.197001 Get top 10 locations: 0:01:12.714176 Total: 0:01:12.911177 Models I have a table of Events with the following model: class Events(models.Model): idhoneypot = models.IntegerField(db_column="idHoneypot") tshoneypot = models.CharField(db_column="tsHoneypot", max_length=24) tsserver = models.DateTimeField(db_column="tsServer") srcip = models.CharField(db_column="srcIP", max_length=16) type = models.CharField(max_length=16) f1 = models.TextField() f2 = models.TextField() f3 = models.TextField() Furthermore, I have an IP2Location table (DB1 from https://lite.ip2location.com/ modified to use ISO-3 codes) of IP ranges and the corresponding location with the following model: class IP2Location(models.Model): from_IP = models.IntegerField(db_column="FromIP", primary_key=True) to_IP = models.IntegerField(db_column="toIP") country_code = models.CharField(db_column="CountryCode", max_length=3) country = models.CharField(db_column="Country", max_length=250) The table also containse a unique B-Tree index using from_IP and to_IP Current … -
Stage "Test" skipped due to earlier failure(s) in one of the pipelines
In our project one of the pipeline is failing to build which was actually working earlier. Little backstory the entire project is in django and it's failing while downloading httplib. We have removed the cache inside jenkins but still getting the same error. Can anyone help find the issues? I have skipped some of the libraries installation inside console output in order to meet the standards set by stack overflow This is how my jenkins file looks like pipeline { agent any stages { stage('Cleanup') { steps { sh 'docker rm $(docker ps -a -f status=created -q) || true' sh 'docker stop $(docker ps -a -f ancestor=divyanshu-ubertower-django -q) || true' sh 'docker rm $(docker ps -a -f status=exited -q) || true' } } stage('Build') { steps { sh "pwd" dir('ubertower_django') { sh "pwd" sh 'docker build -t divyanshu-ubertower-django .' } sh "pwd" } } stage('Test') { steps { echo 'Testing..' } } stage('Deploy') { steps { echo 'Deploying....' dir('ubertower_django') { sh "pwd" sh 'docker run -p 8002:8000 -i -t -d -u 0 divyanshu-ubertower-django' } } } } } Here's the detailed console output for the same > git rev-parse --resolve-git-dir /var/lib/jenkins/workspace/Django Divyanshu@script/76206a91249aa4b58c0231a2fb7971ef1ec6b6dc3d6273ce410409c4cc7cef14/.git # timeout=10 Fetching changes from the remote Git … -
ValueError at /post/18/
I learn django, and I do the Django girls' tutorial. (https://tutorial.djangogirls.org/fr). When I try to see the text ,even if i'm not register, I have the edit views. And when I click on save, it send to me this messageError message I want just to see the text when I'm not register and have not the edit views. I hope you can help me views.py from django.shortcuts import render from django.utils import timezone from .models import Post from django.shortcuts import render, get_object_or_404 from .forms import PostForm from django.shortcuts import redirect # Create your views here. def post_list(request): posts= Post.objects.filter(published_date__lte=timezone.now()).order_by('published_date') return render(request, 'blog/post_list.html', {'posts' : posts}) def post_detail(request, pk): #Post.objects.get(pk=pk) post = get_object_or_404(Post, pk=pk) if request.method=='POST': form = PostForm(request.POST, instance=post) if form.is_valid(): post = form.save(commit=False) post.author = request.user post.published_date = timezone.now() post.save() return redirect('post_detail', pk=post.pk) else: form = PostForm(instance=post) return render(request, 'blog/post_edit.html', {'form':form}) def post_new(request): if request.method == "POST": form = PostForm(request.POST) if form.is_valid(): post = form.save(commit=False) post.author = request.user post.published_date = timezone.now() post.save() return redirect('post_detail', pk=post.pk) else: form = PostForm() return render(request, 'blog/post_edit.html', {'form': form}) def post_new(request): if request.method == "POST": form = PostForm(request.POST) if form.is_valid(): post = form.save(commit=False) post.author = request.user post.published_date = timezone.now() post.save() return redirect('post_detail', pk=post.pk) else: … -
"Unknown column 'column_name' in 'table_name'" error while running django migrate command to rename a field
I am trying to connect an already existing database to django. I was able to make the models using inspectDb command. I have made the initial migrations as well. The problem has started occurring when I am trying to rename a field. It shows the error "Unknown column 'column_name' in 'table_name'", even when the column in the given table exists. I want to rename my fields and have those changes reflected in my database. Model I got from inspect db class ManufacturerModel(models.Model): auto_manufacturer_model_name = models.CharField(max_length=255) year = models.PositiveSmallIntegerField() manufacturer_name = models.CharField(max_length=255) manufacturer_id = models.IntegerField(blank=True, null=True) manufacturer_year_id = models.IntegerField(blank=True, null=True) class Meta: db_table = 'manufacturer_model' Changed I want to be reflected in databse: class ManufacturerModel(models.Model): auto_manufacturer_model_name = models.CharField(max_length=255) year = models.PositiveSmallIntegerField() manufacturer_name = models.CharField(max_length=255) manufacturr_id = models.IntegerField(blank=True, null=True) manufacturer_year = models.IntegerField(blank=True, null=True) class Meta: db_table = 'manufacturer_model' ERROR: django.db.utils.OperationalError: (1054, "Unknown column 'manufacturer_id ' in 'manufacturer_model'") I want the database changes to be reflected properly after i run the migrate command without errors. -
Django nested serializer prefetching before validation
I am having some difficulty with prefetching nested model objects, so the number of repeated queries are causing big performance issues, in case of multiple create (1000+) In short: I have 3 models in this example. Project contains multiple Sites. Sites have a Country. One country can have multiple Sites. When I am creating multiple sites from one request, the serializer automatically creates queries for each site's country_code. I assume this causes the performance issue, when serializing and I think that I would need to prefetch the countries before somehow, so I can spare all the time it takes to query a country with a country_code. models.py class Project(models.Model): project_name = models.CharField(max_length=255) status = models.CharField(max_length= 255) owner = models.ForeignKey(User, null=True, on_delete=models.CASCADE) user_id = models.PositiveIntegerField() def __str__(self) -> str: return self.project_name class Country(models.Model): SUPPORTED = "supported" NOT_SUPPORTED = "not_supported" SUSPENDED = "suspended" STATUS_CHOICES = [ (SUPPORTED, "Supported"), (NOT_SUPPORTED, "Not supported"), (SUSPENDED, "Suspended"), ] name = models.CharField(max_length=255) iso_code2 = models.CharField(max_length=2, primary_key=True) iso_code3 = models.CharField(max_length=3, unique=True) status = models.CharField(max_length=255, choices=STATUS_CHOICES, default=NOT_SUPPORTED) class Meta: verbose_name_plural = "Countries" ordering = ["name"] def __str__(self) -> str: return self.name class Site(models.Model): project = models.ForeignKey(Project, on_delete=models.CASCADE, null=True, related_name="sites") site_id1 = models.CharField(max_length=255) site_id2 = models.CharField(max_length=255, blank=True) country_code = models.ForeignKey(Country, … -
Getting Cors error when calling functions from ModelViewSet in Django Rest Framework
This error is pretty odd, I have a project on Django with Django Rest Framework and I have an app with a ModelViewSet to create CRUD endpoints for my Race resource. race.py from ..models.race import Race from ..serializers.race import RaceSerializer from rest_framework.viewsets import ModelViewSet from rest_framework.permissions import IsAuthenticated class RaceViewSet(ModelViewSet): model = Race serializer_class = RaceSerializer queryset = Race.objects.all() This is my app's urls.py from django.urls import path, include from rest_framework import routers from .views.race import RaceViewSet from .views.test import TestView router = routers.DefaultRouter() router.register(r'races', RaceViewSet) urlpatterns = [ path('', include(router.urls)), path('test', TestView.as_view(), name='test'), ] I got everything set correctly, and I can access the list method without issues using Postman Now Im aware of the CORS issue doesn't happen in Postman and installed 'django-cors-headers' to solve the CORS issue on my Angular app. settings.py ALLOWED_HOSTS = [] CORS_ORIGIN_WHITELIST = [ 'http://localhost:4200', # My angular server ] # Application definition INSTALLED_APPS = [ ... 'rest_framework', 'corsheaders', .. ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'corsheaders.middleware.CorsMiddleware', # CORS middleware 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] And it works, I made a test route to check everything and inside my angular app I called that method this is the test ViewSet from rest_framework.views … -
How to exclude captcha field from admin custom user change
forms.py class UserChangeForm(UserChangeForm): captcha = CaptchaField() class Meta: model = User fields = '__all__' admin.py class CustomUserAdmin(UserAdmin): add_form = UserCreationForm form = UserChangeForm model = User readonly_fields = ['created_at', 'updated_at'] ordering = ('email',) exclude = ('username',) list_display= [ 'email', 'first_name', 'last_name', 'middle_name', 'email', 'is_staff', 'is_active', 'date_joined', 'role', 'phone', 'convenient_time', 'status', 'created_at', 'updated_at', ] fieldsets = ( (None, { 'fields': ('password', 'captcha') }), ('Personal info', { 'fields': ('first_name', 'last_name', 'middle_name', 'email') }), ('Permissions', { 'fields': ( 'is_active', 'is_staff', 'is_superuser', 'groups', 'user_permissions' ) }), # ('Important dates', { # 'fields': ('last_login', 'date_joined') #no need to change dated for user # }), ('Additional info', { 'fields': ('role', 'phone', 'convenient_time', 'status', 'created_at', 'updated_at') }) ) add_fieldsets = ( (None, { 'fields': ('password1', 'password2') }), ('Personal info', { 'fields': ('first_name', 'last_name', 'middle_name', 'email') }), ('Permissions', { 'fields': ( 'is_active', 'is_staff', 'is_superuser', 'groups', 'user_permissions' ) }), ('Additional info', { 'fields': ('role', 'phone', 'convenient_time', 'status') }) ) I need captcha from field in view ONLY not need it in admin. exclude = ('username', 'captcha') cause "please correct the error below.". If I add captcha to fieldset and fill it form saves succesfully. Want to exclude captcha field from admin panel -
celery with RabbitMQ django
celery work fine on localhost RabbitMQ when i use AmazonMQ server celery don't receive the task: enter image description here celery.py from __future__ import absolute_import, unicode_literals import os from celery import Celery os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'auth.settings') app = Celery('auth') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() settings.py CELERY_BROKER_URL = 'amqps://<username>:<password>@<Broker_URL>' when i returns to localhost RabbitMQ all the task i sent when i connected with AmazonMQ received -
Why does Django admin render weird?
After hosting my Django project on PythonAnywhere, the Django Admin login page looks like this: I have run python manage.py collectstatic and this still happens. There are many errors in the Javascript console that include: Refused to apply style from 'example.com/static/admin/css/dark_mode.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled. The other errors also reference to MIME. This is my settings.py: STATIC_URL = "/static/" STATICFILE_DIRS = [BASE_DIR / 'static'] STATIC_ROOT = '/home/mywebsite/surveys/static' Can anyone tell me why this is happening? -
Title: Issue with Django factory_boy and handling RuntimeWarning for naive datetime values
While creating instance of XFactory I get RuntimeWarning for naive datetime values for field i.e field_x, but I don't get error when I run without using post_generation hook, What could be issue on this? from factory import post_generation from django.utils import timezone from datetime import date class XFactory(factory.django.DjangoModelFactory): class Meta: model = X field_x = factory.LazyFunction(timezone.now) # datetime field @post_generation def createY(obj, create, extracted, **kwargs): if not create: return YFactory(x=self, field_y=self.field_x.date()) class YFactory(factory.django.DjangoModelFactory): class Meta: model = Y field_y = factory.LazyFunction(date.today) # date field x = factory.SubFactory(XFactory)# fk relation with x x_instance = XFactory() # it throws RuntimeWarning for naive datetime values for field i.e field_x -
Django not returning JsonResponse after completing bulk_create()
Django does not return JsonResponse (or anything for that matter) after completing bulk_create(). Method is called using GET request. Here is a simplified code which I use: objs = Entry.objects.bulk_create(entries) print(len(objs)) return JsonResponse({'inserted': str(len(objs))}) This inserts entries into the database and I can see them in the table, len(objs) is visible in console, but I do not receive response. Process doesn't end and just hangs there. Code works fine when inserting entries one by one, but this takes too much time since there's 1M of them. Versions: Django 3.2.17, Python 3.10 -
Get foreign key related objects in Django
I have 3 models: class (models.Model): name = models.CharField(max_length=250, unique=True) def __str__(self): return self.name class AppealForm(models.Model): form_name = models.CharField(max_length=100) def __str__(self): return self.report_form_name class Appeal(models.Model): organization = models.ForeignKey(Organization, on_delete=models.SET_NULL, blank=True, null=True) appeal_form = models.ForeignKey(AppealForm, on_delete=models.CASCADE, blank=True, null=True) appeal_number = models.CharField(max_length=100, blank=True, null=True) applicant_first_name = models.CharField(max_length=100, blank=True, null=True) applicant_second_name = models.CharField(max_length=100, blank=True, null=True) date = models.DateField(blank=True, null=True) appeal_body = models.TextField() Objects of models: **Organization** |#|name| |-|-| |1|Apple| |2|Samsung| |3|Dell| AppealForm |#|form_name| |-|-| |1|Written| |2|Oral| Appeal |#|organization|appeal_form|appeal_number|applicant_first_name|applicant_second_name|date|appeal_body| |-|-|-|-|-|-|-|-| |1|Apple|Written|abc1|Oliver|Jake|06/22/2023|Test appeal body text| |2|Apple|Oral|abc12|Jack|Connor|05/22/2023|Test appeal body text| |3|Apple|Oral|abc123|Harry|Callum|04/22/2023|Test appeal body text| |4|Dell|Written|abc1234|Charlie|William|03/22/2023|Test appeal body text| |5|Dell|Oral|abc12345|George|Reece|02/22/2023|Test appeal body text| I want to generate a table like this below querying from Organization model: | # | Organization | Total amount of appeals | Written appeals amount | Oral appeals amount | | - | --- |--- |--- |--- | | 1 | Apple | 3 | 1 | 2 | | 2 | Samsung | 0 | 0 | 0 | | 3 | Dell | 2 | 1 | 1 | How the query will look like? Thanks in advance! -
Django Admin Panel: Page not found (404) after deploying to Vercel
I deployed my Django-Web-Application to Vercel. Everything works except opening the Add/Edit pages of specific models in the admin panel. I always get the error "page not found (404"). When I run the app on the local server, everthing works within the admin panel. I assume, that it has something to do with my App-Name "Aufträge" due to the "umlaut ä" in the name. But I don't know exactly. error I tried to compare the request url and the urls out of the application, But I can't understand why it is working in the test environmement. -
Avoid repetition of models in Django
I've a Django app that collects climatic data from different sources. Let's say for simplicity Temperature, Precipitation and Wind Speed, although in reality they are many more. I've a Django model for each of these magnitudes, representing a table that looks like (simplified version): datetime location id average 2022/3/10 10:25 1 27 2022/3/10 10:35 1 2022/3/10 10:37 2 9999 2022/3/10 10:40 3 27 With hundreds of thousands of rows, collecting data for many years and many locations, and growing. Now, this is the raw data: sometimes there is missing information (eg. row 2) and sometimes the data makes no sense (eg. row 3, with that 999). For this data to be useful for any purpose, it needs to be clean up and validated, and hourly, daily and monthly averages (for each location) calculated. The curated data has exactly the same fields that the raw data. So, I have 4 sets of identical models (raw, hourly, daily and monthly) for each of the magnitudes of interest, as well as identical filters and views. If this were just 3 magnitudes (Temperature, Precipitation and Wind Speed), it could be OK, but I have over 20 which results in A LOT of code repetition. … -
DJANGO: combobox doesn't print in textarea. Error in views.py or in html
In the home.html page I have a combobox and a textarea. I would like to achieve that if I click on an item in the combobox, using an (if) condition in views.py, I get the printout in the textarea. For example if I select "Red" then it must print "You chose red". Very simple. But there is something wrong with my code. It's probably the home.html file, or function def home in views.py file Problem: combobox(independent and not attached to a database) correctly browses items from list, but the condition doesn't apply. When I click on button, nothing happens. How can I execute the condition correctly and print in the textarea when I select the combobox item? I'm new to django, can you show me an answer with the code please? home.html <form method="post"> {% csrf_token %} {{ combobox }} <button type="submit">submit</button> </form> <form method="post"> {% csrf_token %} {{ textarea }} </form> views.py colours = ["Red", "Blue", "Black", "Orange"] @login_required def home(request): #Combobox if request.method == "POST": combobox = SimpleCombobox(request.POST) if combobox.is_valid(): print(combobox.cleaned_data) return redirect("home") else: combobox = SimpleCombobox() #TextArea if request.method == "POST": textarea = SimpleTextbox(request.POST) if textarea.is_valid(): print(textarea.cleaned_data) return redirect("home") else: textarea = SimpleTextbox() message = "" picked … -
django the second html page not concting to the existing one
i got the error , because I couldn't connect to other html pages, so please help me to debug the error. I want the output to show the connecting html page, but the out put idegate there is no such a path. app(view.py) from django.urls import path from django.views import View from .import views urlpatterns = [path('',views.index,name='index'), path('contact/', views.contact,name='contact') ]