Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
pywin32 installation error in python django
when I try to install "pywin32" in virtualenvironment through vscode terminal in linux(aws server), it shows error. But successfully installed in local machine. python version : 3.8.8 django version : 3.2 os : linux try to install pypiwin32 -
Bootsrap modal Making alignment issue
I am using Django and bootstrap-4 and having an issue with the bootstrap modal's position. I have placed the modal outside a section and trying to get it on click of a HREF <section> <p class="small">By signing up you are agreeing to our <a data-target="#myModal" data-toggle="modal" style="font-weight: 600;" class="ml-1">Terms & Condtions</a>.</p> </section> <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLongTitle" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLongTitle">Modal title</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> By using our e-commerce website, you agree to comply with all applicable laws and regulations. </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> <button type="button" class="btn btn-primary">Save changes</button> </div> </div> </div> </div>``` this is the whole code of the file, I want the `modal` to position correctly based on the screen. so that the `modal` can be seen without any issues at any `scroll position`. [![this shows how the final result looks like](https://i.stack.imgur.com/K3SYx.png)](https://i.stack.imgur.com/K3SYx.png) -
Django how to anotate number of attempts in Queryset
I have the model like: class Order(models.Model): order_id = models.CharField(max_length=100) title = models.TextField(max_length=600) title_2 = models.TextField(max_length=100) attempts = models.ForeignKey('self', blank=True, null=True, on_delete=models.PROTECT) driver = models.ForeignKey(Driver, blank=True, null=True, on_delete=models.SET_NULL) updated_at = models.DateTimeField(blank=True, default=datetime.datetime.now()) And what I want to achive in my anotation I need a number of attempt based on older updated_at value. But active order have attempts=None. How I can correctly anotate the number of attempt ? -
How to customize `/static/` location for Jupyter Lab on NGINX
I have a server (Ubuntu 20) running NGINX for reverse proxy. I have a Django app accessible thru the the https://URL/app location, and it's static content is aliased at /var/www/static-collected. This works fine. I'm attempting to setup Jupyter Lab at https://URL/jupyter, but it's unable to find the /static content, ie the CSS and images (Jupyter logo). I've setup Jupyter Lab with NGINX plenty of times, but never with another app that is using /static. I've tried copying the Jupyter static files (located @ .../dist-packages/jupyter_server/static) to the static location used by the Django app, thinking Jupyter would look there given the NGINX setup. I've also tried editing the c.LabServerApp.static_dir property in the config to point directly at the Jupyter static files but no luck so far. I'm not sure if this should be solved thru NGINX config, Jupyter config, or both. Any ideas would be appreciated! Here's my NGINX config: server { root /var/www/html; server_name URL; # managed by Certbot location /jupyter/ { proxy_pass http://localhost:8888/; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection upgrade; proxy_set_header Host $host; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_cache_bypass $http_upgrade; } location /app/ { proxy_pass http://localhost:8000/; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection upgrade; proxy_set_header Host $host; proxy_cache_bypass $http_upgrade; } … -
How to count pages from .doc wuthpython on django
I'm using django. In the view I have created a function that passes a file to it and the function returns the number of pages and the type of file. Works correctly. Now I want to add that it can also count the pages of ".doc" but I have tried it in several ways and I can't. I have tried to do it with "win32com" but when installing it gives me an error. If it's not possible, how should I do it? Maybe first convert it to ".docx" and then count the pages? This is my function: def count_pages(file_content, filename): file_extension = os.path.splitext(filename)[1] if file_extension.lower() == ".pdf": pdf_reader = PyPDF2.PdfReader(file_content) num_pages = len(pdf_reader.pages) file_type = "PDF" elif file_extension.lower() == ".docx": text = docx2txt.process(BytesIO(file_content)) num_pages = text.count("\f") + 1 file_type = "Word" elif file_extension.lower() == ".pptx": prs = Presentation(BytesIO(file_content)) num_pages = len(prs.slides) file_type = "PowerPoint" elif file_extension.lower() == ".xlsx": wb = load_workbook(BytesIO(file_content)) num_pages = len(wb.sheetnames) file_type = "Excel" else: num_pages = 0 file_type = "Unknown" return num_pages, file_typ -
Maintain auth session when POSTing from external site - Django
I have a django app which receives data (a user ID) in a POST request and displays relevant content on screen. The app requires user auth before displaying the page with content. The POST request comes from a form on a different site but the user is required to authenticate every time that a POST request is made. I've created a similar form within the site which doesn't require auth each time. Is it a standard thing for requests coming from an external site to need auth every time? -
How to listen real time database from Firebase in Django Admin
I have a Flutter project that receives push notifications from a Django Panel. Within the Flutter project, I have a function that sends push notifications to specific users. Now, I want to extend this functionality to send notifications to my Django Admin and display them as desktop notifications. I have explored Firebase's documentation but couldn't find a way to listen to the Real-Time Database from my Django Panel. Is it possible to achieve this integration between Flutter, Firebase, and Django? If so, what approaches or alternatives should I consider? Here's what I've tried so far: Reviewed the Firebase documentation for any relevant information. Searched online for similar use cases but couldn't find a suitable solution. Any guidance or suggestions would be greatly appreciated! -
Incorrect client IP with Django, Gunicorn, nginx
I've been trying to fix that issue for 5 hours using some possible solutions to the known problem, but it didnt occured. I want to log (django logging extension) requests from client with saving client's IP. Unfortunately, instead of client IP I get internal IP of the Docker's gateway. nginx.conf server { server_tokens off; listen 80; server_name 127.0.0.1; location / { proxy_redirect off; proxy_set_header Host $host; proxy_set_header REMOTE_ADDR $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; proxy_pass http://microservice_backend:8000; } location ~/(media|static)/ { root /var/html; } } Also I'm using django-xff's middleware and function to extract IP def get_client_ip(request) -> str: x_forwarded_for = request.META.get('HTTP_REMOTE_ADDR') if x_forwarded_for: ip = x_forwarded_for.split(',')[0] else: ip = request.META.get('REMOTE_ADDR') return ip At the beginning "client's IP" was 172.22.0.1. After using django-xff it's 192.168.0.1. It seems to me that somehow $remote_addr; at nginx contains an incorrect IP. request.META does not contains client IP at all (it was $remote_addr with value 172.22.0.1) I'm very upset because of that. Hope someone could help me! -
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