Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to programatically create a svg with different colors in python/django?
In telegram, when you have yet to upload your picture, they will programatically generate a logo based on your initials like the following I want something similar but as SVG and ICO for a Django web app. I only need 26 letters from A to Z. And I need to be able to change the fill color based on taiwindcss colors The letters itself would be white or black. Is there a programatical way to generate these svg and ico to be used in a Django webapp? I could not find any library that does this. I only need it as a square basically -
How to write a get response for two different models data in one response sorted by date?
I have two models: class A(models.Model): ... date=models.DateTimeField(auto_add_now=True) ... class B(models.Model): ... date=models.DateTimeField(auto_add_now=True) ... Both have date field in them. Now I want to write a get response so that I can get both of these model's data from the database sorted by date on the frontend. I have written model serializers with all fields for them. Now in the get response, I have written something like this: A = A.objects.all() B = B.objects.all() aSerializer = A_serializer(A, many=True) bSerializer = B_serializer(B, many=True) all = aSerializer.data + bSerializer.data all = sorted(all, key=lambda item: item['date'],reverse=True) return Response(all) I think I will not be able to do pagination and other stuff with this. Please let me know if there is any better approach to do this? -
Python coverage used in Django takes too long to execute even though it is run with --source flag option
I am using the Python package in combination with the Django testing framework and sometimes want to test only one app/directory/package stated in the coverage --source option. coverage run --source='custom_auth' manage.py test custom_auth.tests.TestAuth.test_authentication --keepdb Is this command the correct way to run only one test? I am also using --keepdb command to ignore recreating the database again. The test is executed in 0.147s, but something happens behind/before the test, and it takes about 3-5 minutes to start executing the test. -
Too many values to unpack in Django
My endpoint to edit a user in Django is implemented like this: @api_view(['PUT']) @permission_classes([IsAuthenticated]) def updateUser(request, pk): user = User.objects.get(pk) data = request.data user.first_name = data['name'] user.username = data['email'] user.email = data['email'] user.is_staff = data['isAdmin'] user.save() serializer = UserSerializer(user, many=False) return Response(serializer.data) My action in Redux to send a put request to Django is implemented like this: export const updateUser = (user) => async (dispatch, getState) => { try { dispatch({ type: USER_UPDATE_REQUEST }) const { userLogin: { userInfo } } = getState() const config = { headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${userInfo.token}` } } const { data } = await axios.put( `/api/users/update/${user._id}/`, user, config ) dispatch({ type: USER_UPDATE_SUCCESS, }) dispatch({ type: USER_DETAILS_SUCCESS, payload: data }) } catch (error) { dispatch({ type: USER_UPDATE_FAIL, payload: error.response && error.response.data.detail ? error.response.data.detail : error.message, }) } } I dispatch updateUser action on click of the button in my component like this: const submitHandler = (e) => { e.preventDefault() dispatch(updateUser({ _id: user._id, name, email, isAdmin })) } I get error from Django: ValueError: too many values to unpack (expected 2) Please help me understand where the problem is -
AWS RabbitMQ and Django Rest Framw: socket.gaierror: [Errno -2] Name or service not known
I am trying to a AWS rabbitmq using pika but I am unable to connect and get an error import pika params = pika.URLParameters("amqps://{uname}:{paswd}@<endpoint>") connection = pika.BlockingConnection(params) channel = connection.channel() def publish(): channel.basic_publish(exchange='', routing_key='bid_group', body='hello') The error is form connection = pika.BlockingConnection(params) Traceback (most recent call last): File "<console>", line 1, in <module> File "/home/rohan/Development/crm/lib/python3.10/site-packages/pika/adapters/blocking_connection.py", line 360, in __init__ self._impl = self._create_connection(parameters, _impl_class) File "/home/rohan/Development/crm/lib/python3.10/site-packages/pika/adapters/blocking_connection.py", line 451, in _create_connection raise self._reap_last_connection_workflow_error(error) File "/home/rohan/Development/crm/lib/python3.10/site-packages/pika/adapters/utils/selector_ioloop_adapter.py", line 565, in _resolve result = socket.getaddrinfo(self._host, self._port, self._family, File "/usr/lib/python3.10/socket.py", line 955, in getaddrinfo for res in _socket.getaddrinfo(host, port, family, type, proto, flags): socket.gaierror: [Errno -2] Name or service not known I was following https://www.youtube.com/watch?v=ddrucr_aAzA to set this up. I tried aws official docs https://docs.aws.amazon.com/amazon-mq/latest/developer-guide/amazon-mq-rabbitmq-pika.html and it gives the same response -
How can I add html in iframe for django
Tried looking into this from stackoverflow but I wasn't understanding and it also seems that django was updated, so the methods maybe different. I am a new user to django and I want to take an html file I have and put into the index.html as an iframe (not an included template, but specifically an iframe. This html has a lot of weird stuff in it and I need it in an iframe so I can test and see it it show up without affecting the index.html so just an iframe is all I need) I tried adding the html to the urls.py then adding the iframe to the html but it failed. urls.py from django.urls import path, re_path, include #from rest_framework import routers from . import views from django.views.generic import TemplateView # Define app name app_name = "frontend" # Set up rest framework router #router = routers.DefaultRouter() #router.register(r"sites", views.SiteViewSet, basename="sites") # Specify url patterns urlpatterns = [ #path("", include(router.urls)), path("", views.show_map, name = "showmap"), re_path("czwt/", TemplateView.as_view(template_name="cold_zones_with_tooltips.html"), name = "show_coldzone_map") ] inside the index.html <iframe id="serviceFrameSend" src="{% url 'frontend/cold_zones_with_tooltips' %}" width="1000" height="1000" frameborder="0"> error: Reverse for 'czwt.html' not found. 'czwt.html' is not a valid view function or pattern name. -
Foreign Key doesn't store parent table primary key value using MySQL and Django
I am working on a project using Django and MySQL and I am stuck in a situation where I want to store parent table primary key value into child table foreign key and this functionality is not performing well as it always store value NULL. I have two tables first one is user and second one is logs. Here are the details of my tables: `CREATE TABLE user ( id int NOT NULL primary key AUTO_INCREMENT, username varchar(255), email varchar(255), password varchar(255), );` CREATE TABLE logs ( id int NOT NULL primary key AUTO_INCREMENT, notifications varchar(255), FOREIGN KEY (user_id) int NULL REFERENCES user(id), on_delete = CASCADE, on_delete = UPDATE ); I have used query to set the parent table primary key value to NULL to create a relation between parent table and child table: "SELECT logs.user_id from logs LEFT JOIN user on user.id = logs.user_id WHERE user.id is NULL" After creating relation When I insert data in parent table the child table foreign key value stores NULL and not store parent table primary key value: "INSERT INTO user(id, username, email, password) VALUES("abc", "abc@gmail.com", "*****")" after INSERT query the user table looks like: ` id username email password `1 abc abc@gmail.com … -
How to use generic view with pk renamed
django.views.generic.detail.DetailView uses pk or slug from urls.py as the identifier. In my case, I have: urls.py: urlpatterns = [ path('<int:quiz_id>/results/', views.ResultsView.as_view()), ] Is there a way to use: class ResultsView(generic.DetailView): model = Quiz without changing quiz_id to pk (default name used for primary key)? I expect that there is some way to change the vague pk to something more descriptive. -
Viewing all the Comments for a post using modal in Django
I am working on implementing a social media website using Django.I want the users to view all the comments posted for a post using modals of Twitter Bootstrap. The comments aren't displaying if there are more than 1 post in my database if I use modals. The logic which I have written works completely fine if I don't nest them inside a modal and display it directly on the webpage after the caption of the post. But considering good UI design implementation I thought of nesting it inside a modal so as to enrich the user experience. Can someone help me out with this? The code for the same is pasted below: <a data-bs-toggle="modal" data-bs-target="#staticBackdrop" style="cursor: pointer;"> View all comments </a> <!-- Modal --> <div class="modal fade" id="staticBackdrop" data-bs-backdrop="static" data-bs-keyboard="false" tabindex="-1" aria-labelledby="staticBackdropLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <h1 class="modal-title fs-5" id="staticBackdropLabel">Comments</h1> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"> </button> </div> <div class="modal-body"> {% if not post.comments.all %} No Comments yet.. <a href="{% url 'add_comment' post.pk %}" >Add Comment</a> {% else %} {% for comment in post.comments.all %} <strong>{{ comment.name }}-{{ comment.date_added }}</strong> <br/> {{ comment.body }} <br/> <hr> {% endfor %} {% endif %} </div> <div class="modal-footer"> <button type="button" class="btn … -
How to properly hide application.fcgi within .htaccess file on shared hosting with https
Hello and thanks in advance, I have a django project working with fcgi on a shared hosting with ionos; I followed a tutorial from https://github.com/sparagus/django-shared-hosting-1and1 and it works pretty well. When I try "http://www.example.com/admin/" it works but the problem is that "https://www.example.com/admin/" redirects to "https://www.example.com/cgi-bin/application.fcgi/admin/" My .htaccess file looks like this AddHandler cgi-script .fcgi RewriteEngine on RewriteBase / RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^(.*)$ /cgi-bin/application.fcgi/$1 [QSA,L] How can I hide the "cgi-bin/application.fcgi" with https too? Thanks a lot for reading. I tried with flask docs aswell https://flask.palletsprojects.com/en/2.0.x/deploying/fastcgi/ but didn't works. -
How to make the dependant multiple choice field don't remove the previously selected choices from the choice field when depending field changes value?
I am working on Django forms. I have 2 choice fields, one is just a choice field and other one is multi choice field. The dropdown values of multi choice field depends upon the selection of choice field. Now, if I select a value from choice field, and then, selected 2-3 values from multi choice field regarding that earlier choice field, then, those selected values are displayed in choice field. Now my problem is, once I select the different choice from choice field, my previous selected choices from multi choice field gets deleted. One way is you can use .append() in jquery but the problem with this is it shows the choices from the previous selected choice field option. For eg: If by selecting previous choice value, I get 20 dropdown choices in multi select choice field (out of which I select 3 choices), then, by selecting some other choice value, I should be getting (let say only 5 choices), but I am getting 25 dropdown choices in multi select option. what I want is only 5 choices in drop down of multi select choice field with only 3 choices already present in the multi select choice field.. I hope … -
How to redirect print statement to log file and change print statement to logger in django python
I want to replace print statements to logger but without change print statement in application. And how can I redirect print statement to log file??? Below is my code. settings.py LOGGING = { "version": 1, "disable_existing_loggers": False, "formatters": { "simple": { "format": "%(asctime)s - %(name)s - %(levelname)s - %(message)s" }, "verbose": { "format": "%(asctime)s - %(name)s - %(levelname)s - %(funcName)s:%(lineno)d - %(message)s" } }, "handlers": { "console": { "class": "logging.StreamHandler", "level": "DEBUG", "formatter": "simple", "stream": "ext://sys.stdout" }, "debug": { "class": "logging.handlers.TimedRotatingFileHandler", "level": "DEBUG", "formatter": "verbose", "when": "D", # when='D', interval=7 were specified, then the log would be rotated every seven days. "interval": 7, "backupCount": 7, # Only kept last 7 days log files "filename": "log/debug.log", }, "info": { "class": "logging.handlers.TimedRotatingFileHandler", "level": "INFO", "formatter": "verbose", "when": "D", # when='D', interval=7 were specified, then the log would be rotated every seven days. "interval": 7, "backupCount": 7, # Only kept last 7 days log files "filename": "log/info.log", }, "error": { "class": "logging.handlers.TimedRotatingFileHandler", "level": "ERROR", "formatter": "verbose", "when": "D", # when='D', interval=7 were specified, then the log would be rotated every seven days. "interval": 7, "backupCount": 7, # Only kept last 7 days log files "filename": "log/error.log", }, }, "loggers": { "root": { "level": … -
Display counter of likes per post with Django is not working
I want to get a variable on the views.py file that retrieves the list of likes for each post. So, then on the HTML file, I would use .count so I can get the number of items on the list and finally be displayed on the DOM. I first made classes on models.py. There, I have 3 classes: User, Post, and Like. User is from the default User class from Django. Post is a class that gets information about the post like the author, description, and timestamp. And on the Like class, I get the user and post. from django.contrib.auth.models import AbstractUser from django.db import models class User(AbstractUser): pass class Post(models.Model): author = models.ForeignKey("User", on_delete=models.CASCADE, related_name="user") description = models.CharField(max_length=1000) timestamp = models.DateTimeField(auto_now_add=True) def __str__(self): return f"{self.id}: {self.author}" class Like (models.Model): user = models.ForeignKey("User", on_delete=models.CASCADE, default='', related_name="user_like") post = models.ForeignKey("Post", on_delete=models.CASCADE, default='', related_name="post_like") def __str__(self): return f"{self.id}:{self.user} likes {self.post}" Second, I made a function on views.py called "index". There, I get the whole list of posts (on the posts variable), then I tried to create the variable (totalLikesSinglePost), which should get the list of likes for each post. def index(request): posts = Post.objects.all().order_by("id").reverse() # Pagination Feature (OMIT THIS, IF YOU WANT) … -
SIMILARITY function triggered by Django
I'm implementing TrigramSimilarity full text search on my Django app. I installed the pg_trgm extension by migrating using Django. I can see the migration in my postgres table and I can use the SIMILARITY function when I run queries directly on the database. I get this error when I try to run a search on my app. I'm at a loss for what to do because when I get the error with this: but when I run a query directly on the database I get results: Initially I was using SearchQuery string in place of 'test' but changed it because I saw another answer suggesting that may be a problem. -
Django annotate by looking up a related field value
I am working on a package sorting system in Django. I need to look up the "sort code" of a set of "barcodes" This code works: class Order(models.Model): Zip = CharField(max_length=128, null=True, blank=True) class Barcode(models.Model): barcode = CharField(max_length=50, unique=True) Order = ForeignKey(Order, on_delete=models.SET_NULL) class SortCode(models.Model): name = CharField(max_length=50, unique=True) class SortZip(models.Model): zipcode = CharField(max_length=5, unique=True) sortcode = ForeignKey('SortCode', null=True, default=None, blank=True, on_delete=models.PROTECT) sortzip = SortZip.objects.filter(zipcode=OuterRef('Order__Zip')) barcodes = Barcode.objects.annotate(sortcode_value=Subquery(sortzip.values('sortcode__name'))) However, SortZip.zipcode only stores 5-digit zip codes, and Order.Zip sometimes contains zip+4, so I need to look up the SortZip from only the first 5 digits of Order.Zip: sortzip = SortZip.objects.filter(zipcode=OuterRef('Order__Zip')[:5]) barcodes = Barcode.objects.annotate(sortcode_value=Subquery(sortzip.values('sortcode__name'))) This causes the following error: TypeError: 'OuterRef' object is not subscriptable I have tried adding the following property to the Order model and using the property: class Order(models.Model): Zip = CharField(max_length=128, null=True, blank=True) @property def Zip5(self): return self.Zip[:5] ... sortzip = SortZip.objects.filter(zipcode=OuterRef('Order__Zip5')) barcodes = Barcode.objects.annotate(sortcode_value=Subquery(sortzip.values('sortcode__name'))) However, this gives a different error: django.core.exceptions.FieldError: Unsupported lookup 'Zip5' for BigAutoField or join on the field not permitted. -
try to authenticate login, submit nothing happened
login.html in (authenticate/login.html) {% extends "events/base.html" %} {% block content %} <h1>Login</h1> <br><br> <form action="" method="POST"> {% csrf_token %} <form> <div class="mb-3"> <label for="exampleInputUserName" class="form-label">User name</label> <input type="text" class="form-control" name="username"> </div> <div class="mb-3"> <label for="exampleInputPassword1" class="form-label">Password</label> <input type="password" class="form-control" name="password"> </div> </form> <input type="submit" value="Submit" class="btn btn-secondary"> </form> <br><br> {% endblock content %} when click the submit button nothing happened urls.py in (events) from django.urls import path from . import views urlpatterns = [ path('', views.home, name='home'), ] urls.py in (members) from django.urls import path from . import views urlpatterns = [ path('login_user/', views.login_user, name='login'), ] urls.py in (myclub_webesite) rom django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('events.urls')), path('members/', include('django.contrib.auth.urls')), path('members/', include('members.urls')), ] views.py in (members) from django.shortcuts import render, redirect from django.contrib.auth import authenticate, login, logout from django.contrib import messages def login_user(request): if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') user = authenticate(request, username=username, password=password) if user is not None: login(request, user) return redirect('home') else: messages.success( request, ("There Was An Error Logging In, Try Again...")) return redirect('login') else: return render(request, 'authenticate/login.html', {}) setting are put in members i have try use other code username = request.POST['username'] password = request.POST['password'] and … -
Unable to log in to Django admin panel after Railway deployment
I'm new to Django, and even newer to using Railway so please be kind. I've got a portfolio project that uses Django on the back end, and I was previously hosting on Heroku. I've attempted to move the deployment to Railway, and I've encountered a problem I can't figure out. Locally, I'm able to sign into the Django admin panel with the superuser credentials. When I attempt the same on the Railway deployment, I get a really long error that doesn't point to anything in my code. I've tried to research the error for a few days now, and I'm coming up blank. I honestly don't even have a direction to look for a solution. This is the error I see when I attempt to sign into the admin panel: (Happy to add other files, but I don't know what is relevant?) OperationalError at /admin/login/ connection to server at "localhost" (127.0.0.1), port 5432 failed: Connection refused Is the server running on that host and accepting TCP/IP connections? connection to server at "localhost" (::1), port 5432 failed: Cannot assign requested address Is the server running on that host and accepting TCP/IP connections? Request Method: POST Request URL: http://web-production-603f.up.railway.app/admin/login/?next=/admin/ Django Version: 4.0.6 … -
How to filter JSON Array in Django JSONField
How could I filter the whole row data which inventory id=2 This is the result data I want: sampleData = [ {'rate': 1, 'inventory': {'id': 1, 'name': 'inv1'}, 'inputQuantity': 4}, {'rate': 1, 'inventory': {'id': 2, 'name': 'inv2'}, 'inputQuantity': 10, 'parentInventory': 2} ] This is the sample database: inventoryList=[ [ {'rate': 1, 'inventory': {'id': 1, 'name': 'inv1'}, 'inputQuantity': 4}, {'rate': 1, 'inventory': {'id': 2, 'name': 'inv2'}, 'inputQuantity': 10, 'parentInventory': 2} ], [ {'rate': 4, 'inventory': {'id': 5, 'name': 'inv2'}, 'inputQuantity': 4}, {'rate': 3, 'inventory': {'id': 4, 'name': 'inv4'}, 'inputQuantity': 1} ], [ {'rate': 2, 'inventory': {'id': 5, 'name': 'inv1'}, 'inputQuantity': 5}, {'rate': 4, 'inventory': {'id': 6, 'name': 'inv2'}, 'inputQuantity': 10, 'parentInventory': 2} ], ] The filter be like: sampleLog.objects.filter(inventoryList__contains=[{"inventory":{'id': 2}}]) -
CSRF verification failed. Request aborted
Been working on my live server all day and just got it working, admin was working fine, i cleared cookies and suddenly i got the following error, and no fixes seem to be helping me. My website does have SSL yet so its still http(dont know if this has anything to do with it?) DEBUG = False CSRF_TRUSTED_ORIGINS = ['http://.*', 'http://example.com', 'http://www.example.com'] # HTTPS Settings SESSION_COOKIE_SECURE = True CSRF_COOKIE_SECURE = False SECURE_SSL_REDIRECT = False # HSTS Settings SECURE_HSTS_SECONDS = 31536000 SECURE_HSTS_PRELOAD = True SECURE_HSTS_INCLUDE_SUBDOMAINS = True This is the only form on my website that requires csrf_token and as you can see it already has it. -
Python gRPC request missing occasionally
I'm using gRPC in python with django and django-grpc-framework. And when I run the unittest, there is a piece of code in my models.py which producing weird problem: I request three gRPC requests, but only one reaches the server side. To simplified the problem, the following code explains the situation: class MyModel(models.Model): def some_method(self): for stub in [stub1, stub2, stub3]: resp = stub.RetractObject(base_pb2.RetractObjectRequest( app_label='...', object_type='...', object_id='...', exchange_id='...', remark='...', date_record='...', )) Here, the some_method is triggering under a django.test.TestCase unittest function, while the gRPC was connecting to a external running server instance. And the relating .proto files is as below: // base.proto // ... message CreditRecord { int64 id = 1; string username = 2; string app_label = 3; string flag = 4; string object_type = 5; int64 object_id = 6; int64 amount = 7; int64 balance = 8; string remark = 9; string date_record = 10; string exchange_id = 11; int64 retract_ref = 12; } message RetractObjectRequest { string app_label = 1; string object_type = 2; int64 object_id = 3; string exchange_id = 4; string remark = 5; string date_record = 6; } // ... // stub1 - stub3 has the similar structure below syntax = "proto3"; package mjtest.growth; import … -
How to return only 1 (single) record via Django Rest Framework API? (problem with many=False)
I have a simple Django Rest Framework API that I would like to return only 1 record. However, when I set many=False, it no longer works. How can I fix this? Here's the API: (serializer & model below) class Expense_View_API(APIView): permission_classes = [IsAuthenticated, ] def get(self, request): param_xid = request.GET.get('id','') if param_xid != "": expenses_recordset = Expenses.objects.filter(xid=param_xid) serializer = Expenses_Serializer(expenses_recordset, many=True) return Response(serializer.data, status=status.HTTP_200_OK) else: return Response("BAD REQUEST: Missing 'id' Parameter", status=status.HTTP_400_BAD_REQUEST) It returns: (good except that I don't want the square list brackets) [ { "xid": 111, "xdate": "2021-02-15T00:00:00Z", "xseller": "Amazon", "xamount": "30.00", } ] Problem: When I set serializer = Expenses_Serializer(expenses_recordset, many=False), it now returns this null data and drops my xid field. Why? { "xdate": null, "xseller": null, "xamount": null, } I want it to return: { "xid": 111 "xdate": "2021-02-15T00:00:00Z", "xseller": "Amazon", "xamount": "30.00", } Here's my serializer and data model: class Expenses_Serializer(serializers.ModelSerializer): class Meta: model = Expenses fields = ('xid', 'xdate', 'xseller', 'xamount') class Expenses(models.Model): xid = models.AutoField(db_column='xID', primary_key=True) # Field name made lowercase. xdate = models.DateTimeField(db_column='xDate', blank=True, null=True) # Field name made lowercase. xseller = models.CharField(db_column='xSeller', max_length=50, blank=True, null=True) # Field name made lowercase. xamount = models.DecimalField(db_column='xAmount', max_digits=19, decimal_places=2, blank=True, null=True) # Field name … -
How to implement a derived select in Django? The purpose is to narrow down before more expensive operations
We are working on a reporting table of a transaction dataset assembled with dynamic EAV attributes by the left outer join operators. The sample SQL query below contains a snippet of limit 20 OFFSET 27000 simulating a pagination scenario of displaying a page of 20 records in the middle of the overall data set sized nearly 30 thousand rows. With Django ORM, we started the QuerySet from the Model object and filtered its active_objects before appending the left outer join operators, with the below snippet: transaction = Transaction.active_objects.filter( product_id=product_id ).order_by('-id').all()[27000:27020] As a default system behaviour of Django, I guess, the ORM put the WHERE clause at the rear of the the SQL query. As a result, the MariaDB v10.5 database performs all the left outer join operators on the overall data set before it applies the filtering condition. The running time is nearly 20 seconds in our test setting. We made a hand-written improvement to the SQL query and reduced the running time to under one second. The change is moving the WHERE clause up to immediately following the FROM transaction clause, and moreover, wrapping it inside the brackets ( ) to make the database engine treat it as a … -
Assign a type to JSONField in Django
I'm using a property of type JSONField in my model: from django.db import models class MyClass(models.Model): variables = models.JSONField() I want to avoid as much as possible using strings to access variables properties, is there any way to specify the type of variables, so that I can use obj.variables.prop_name rather than obj.variables['prop_name']? -
Django and pgAdmin not aligned
I was trying to change the order of the table columns in a postgreSQL table. As I am just starting, it seemed easier to manage.py flush and create a new DB with new name and apply migrations. I can see the new DB in pgAdmin received all the Django models migrations except my app model/table. I deleted all migrations folder (except 0001_initial.py) and still, when I run python manage.py makemigrations I get: No changes detected But the model class table is not in the DB. When I try to migrate the app model it says: Operations to perform: Apply all migrations: admin, auth, contenttypes, sessions Running migrations: No migrations to apply. Is there any way to delete all tables, makemigrations and migrate and postgres get all the tables? Any idea why postgreSQL/pgAdmin cannot get my Django app model/table? -
Django pdf template count severity per row
I am using Django but I am stuck with the PDF report. There are three severity which are "Damage to Property", "Fatal" and "Non-Fatal". Download of PDF is working but but in my PDF report, I would want for every distinct address, it will count each severity (the number of Damage to Property, Fatal or Non-fatal). How can I achieve this? This is what the table will look like: Date | Time | Address | Damage to Property | Fatal | Non-Fatal Model class IncidentGeneral(SoftDeleteModel): PENDING = 1 APPROVED = 2 REJECTED = 3 STATUS = ( (PENDING, 'Pending'), (APPROVED, 'Approved'), (REJECTED, 'Rejected') ) IF_DUPLICATE = ( ('Duplicate', 'Duplicate'), ('Possible Duplicate', 'Possible Duplicate'), ('Not Duplicate', 'Not Duplicate') ) WEATHER = ( ('Clear Night', 'Clear Night'), ('Cloudy', 'Cloudy'), ('Day', 'Day'), ('Fog', 'Fog'), ('Hail', 'Hail'), ('Partially cloudy day', 'Partially cloudy day'), ('Partially cloudy night', 'Partially cloudy night'), ('Rain', 'Rain'), ('Rain', 'Rain'), ('Wind', 'Wind'), ) LIGHT = ( ('Dawn', 'Dawn'), ('Day', 'Day'), ('Dusk', 'Dusk'), ('Night', 'Night'), ) SEVERITY = ( ('Damage to Property', 'Damage to Property'), ('Fatal', 'Fatal'), ('Non-Fatal', 'Non-Fatal'), ) user = models.ForeignKey(User, on_delete=models.CASCADE, editable=False, null=True, blank=True) generalid = models.CharField(max_length=250, unique=True, null=True, blank=True) upload_id = models.ForeignKey(UploadFile, on_delete=models.CASCADE, editable=False, null=True, blank=True) description = …