Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
" ' " (Single Quote) got converted to ' How do I replace it or fix it?
I sent a Dictionary to Django Template, Its " ' " got converted to ' How do I convert or Replace it? I have tried using replace function, It doesn't work. Dictionary_passed = {"-" : "100", "GERMANY" : "1500"} In the HTML template I got {'-':'100','GERMANY&#39:'1500' } on Dictionary_passed.replace(''', ''), I get: {&#39l-':100, 'GERMANY':1500} -
TypeError: record_club_minutes() missing 2 required positional arguments: 'purchase' and 'fund'
I'm making an app in which students can input their club data and create minutes for their respective clubs. Right now, I'm running into some trouble trying to pass these two variables from one form into another; it keeps on giving the TypeError above. Any help is greatly appreciated! routes.py @login_required def generate_minutes(user_id): user = User.query.get_or_404(user_id) # TODO: use the same form form = record_club_name_form(user) if form.validate_on_submit(): # send user to the record_club_minutes club = form.club_list.data purchitems = form.purchaseitems.data funditems = form.funditems.data return redirect(url_for('clubs.record_club_minutes', user_id=user_id, club_id=club.id, purchase=purchitems, fund=funditems)) return render_template('record_club_name.html', title='Record', form=form, user=user) #THERE MAY BE BUGS HERE @clubs.route("/record_minutes/<int:user_id>/<int:club_id>/record", methods=['GET', 'POST']) @login_required def record_club_minutes(user_id, club_id, purchase, fund): user = User.query.get_or_404(user_id) club = Club.query.get_or_404(club_id) members = club.members form = create_club_minutes_form(club, purchase, fund) # form.purchaseform.entries = purchase # form.fundform.entries = fund if form.validate_on_submit(): minute = Minutes(club_id=club_id, date=form.date.data, time=form.time.data, location=form.location.data, minute=form.notes.data) db.session.add(minute) for index, field in enumerate(form.attendance): if field: attendance = Attendance(student_name=members[index].firstname + members[index].lastname) minute.attendance.append(attendance) db.session.commit() flash('Minutes successfully recorded', 'success') return redirect(url_for('clubs.view_club_name', user_id=user.id)) return render_template('record_minutes.html', title='Record', form=form, user=user, club=club, members=members) Here is forms.py for the record_club_minutes(user_id, club_id, purchase, fund) above. def create_club_minutes_form(club, purchase, fund): num_members = len(club.members) class ClubMinutesForm(FlaskForm): date = DateField('Meeting Date (mm/dd/year)', validators=[DataRequired(), DateRange(max = date.today())], format = '%m/%d/%Y') time = … -
Django app is not connecting with remote database
I have a Django app running on hosting server. I am using postgres database which is running on different server. The app is working properly in my local machine but in hosting server, the app is running but any functionality is not working which is associated with database. For example, user can not authenticated while login even the username and password is correct. My settings for database DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'DB_NAME', 'USER': 'USER', 'PASSWORD': '*****', 'HOST': 'IP_ADDRESS', 'PORT': 'PORT', } } N:B I have given permission to the postgres database. I can access the db from local machine Django version 2.2.5 -
How can i extract single Models db into template in django without for loop?
I am wondering how to extract single model database in django template? i can do with for loop but i want a single model db in templates -
Why I can't save the edit of a Django ModelForm blog?
I was doing the Python Crash Course Ex. 19-1: Blogs, and I'm now stuck at saving the edit of any blog. I tried plugging in the .errors code in the blog.html (for showing each blog) but it shows nothing, so I guess my templates has no field errors (?) Here're some codes I believe crucial for solving the not-saving-the-edit problem. The new_blog function in views.py works fine so I'll skip it. The edit_blog function in views.py: def edit_blog(request, blog_id): idk = BlogPost.objects.get(id = blog_id) if request.method != "POST": form = BlogForm(instance = idk) else: form = BlogForm(instance = idk, data = request.POST) if form.is_valid(): form.save() return HttpResponseRedirect(reverse('blogs:blogs')) content = {"editing_blog": form, "psst": idk} return render(request, 'blogs/edit_blog.html', content) new_blog.html: {% extends "blogs/all.html" %} {% block content %} <p>Write a new blog:</p> <form action="{% url 'blogs:new_blog' %}" method='post'> {% csrf_token %} <table border="1"> {{ new_blog }} </table> <p></p> <button name="submit">Submit</button> </form> {% endblock content %} edit_blog.html: {% extends "blogs/all.html" %} {% block content %} <p>Edit the blog:</p> <form action="{% url 'blogs:blog' psst.id %}" method='post'> {% csrf_token %} <table border="1"> {{ editing_blog }} </table> <p></p> <button name="submit">Save changes</button> </form> {% endblock content %} No matter how I change the title, or content, or … -
get the main image of a table with left join in django orm
class Products(models.Model) nombre = models.CharField( max_length = 255, blank = True ) class ProductsImages(models.Model) idProducto = models.ForeignKey( 'Products', related_name = 'imagesProduct', on_delete = models.CASCADE, ) principal = models.BooleanField( default = False ) url = models.ImageField( upload_to = '', blank = True ) for item in Products.objects.values( 'id', 'nombre', 'imagesProduct__id', 'imagesProduct__url' ).filter( imagesProduct__principal = True ): I need to make a left join with a main image and if I don't have the image show null. So far I get all the images and I just need the main one. -
SyntaxError: positional argument follows keyword argument in multiple filter elements query
Keep getting below error. File "/app/community/views.py", line 643 app_1 | (Q(roster_id=rid) | Q(roster__parent_id=rid)), app_1 | ^ app_1 | SyntaxError: positional argument follows keyword argument In this line of code inside a view (views.py). CommunityRosterMembers.objects.filter( community_id=cid, (Q(roster_id=rid) | Q(roster__parent_id=rid)), (Q(rsvp_vote=1) | Q(rsvp_vote=2)) ) The model I am using is: class CommunityRosterMembers(models.Model): community = models.ForeignKey('Community', blank=False, null=False, related_name='community_roster_member_ref_set', on_delete=models.CASCADE) roster = models.ForeignKey('roster.Roster', blank=False, null=False, related_name='roster_community_member_ref_set', on_delete=models.CASCADE) flag = models.ForeignKey('CommunityRosterFlags', blank=False, null=False, related_name='community_roster_flag_ref_set', on_delete=models.CASCADE) member = models.ForeignKey('members.MemberInfo', blank=False, null=False, related_name='community_member_roster_ref_set1', on_delete=models.CASCADE) request_by = models.ForeignKey('members.MemberInfo', blank=True, null=True, related_name='community_requester_roster_ref_set', on_delete=models.CASCADE) date_rsvp_requested = models.DateField(default=timezone.now()) date_rsvp_response = models.DateField(default=timezone.now()) rsvp_vote = models.IntegerField(default=0,blank=False)#0 - Pending, 1 - Accepted, 2 - Maybe, 3 - Declined attendance = models.IntegerField(default=0,blank=False)#0 - Pending, 1 - Attended, 2 - Absent, 3 - Missed def __str__(self): return self.roster.title -
Error generation due to settings.py in django
-Created a project in django with 'CustomUser' model derived from 'AbstractUser' in an app 'users' -Below is the settings file snippet. INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'rest_framework.authtoken', 'crispy_forms', 'users', I get following error while running python manage.py makemigrations command with unsuccessful migration. ValueError: The field authtoken.Token.user was declared with a lazy reference to 'users.user', but app 'users' doesn't provide model 'user'. After much trial and error, I have removed 'rest_framework.authtoken' from the Installed app and the migration error disappeared and my site become functional. Problem is I want to user rest_framework and token based authorisation but if I keep 'rest_framework.authtoken' in settings, migration is not taking place. Please help -
Django's view of its models is inconsistent with the actual database
We have a system consisting of a Django server connected to a PostgreSQL database, and some AWS Lambda functions which need to access the database. When an admin saves a model (PremiumUser - contains premium plan information that needs to be read by the Lambdas), we want to set up a schedule of CloudWatch events based on the saved information. Those events then trigger other Lambdas which also need to directly access the database, as the database state may change at any time and they should work off the most recent state of the database. The issue is that Django seems to think it has saved the values, but when the Lambdas read the database the expected values aren't there. We have tried using Django's post_save signal, calling the Lambdas inside the triggered function; we have tried overriding Django's default PremiumUser.save method to perform super(PremiumUser, self).save(*args, **kwargs), and only then call Lambdas (in case the post_save signal was getting triggered too early); and we have tried overriding the PremiumUser.save method and calling super(PremiumUser, self).save(*args, **kwargs) in the context of an atomic transaction (ie with transactions.atomic():). When we call the Lambdas a few seconds after the admin dashboard has updated, they … -
Bootstrap Modal Not Working on Paginated Datatable Django
I have a datatable where for each row there is a button which launches a bootstrap modal window to edit the record. I thought everything was working well, until I noticed that it only works for the first ten (initially visible) records. Beyond that the button doesn't do anything, but I'm not sure why. Could someone please help me clear this up? JS controlling this all the way at the bottom. index.html <div class="table-responsive"> <table id="main_table" class="table table-striped table-bordered" cellspacing="0" style="width="100%"> <thead> <tr> <th></th> <th style="width:3%;">Reference</th> <th style="width:7%;">Ultimate Consignee</th> <th style="width:5%;">Vessel</th> <th style="width:7%;">Booking #</th> <th style="width:5%;">POL</th> <th style="width:15%;">DOL</th> <th style="width:5%;">POE</th> <th style="width:5%;">Pickup #</th> <th style="width:5%;">Sales Contact</th> <th style="width:5%;">Trucking Co</th> <th style="width:2%;">Total Cases</th> <th style="width:2%;">Total FOB</th> <th style="width:5%;">Freight Forwarder</th> <th style="width:5%;">Proforma</th> </tr> </thead> <tbody> {% for order in orders %} <tr> <td> <!-- Update book buttons --> <button type="button" class="update-book btn btn-sm btn-primary" style="color: #FFCF8B; border-color: #FFCF8B; background-color: #FFF;" data-id="{% url 'order_update' order.pk %}"> <span class="fa fa-pencil"></span> </button> </td> <td>{{ order.reference }}</td> <td>{{ order.ultimate_consignee }}</td> <td>{{ order.vessel }}</td> <td>{{ order.booking_no }}</td> <td>{{ order.POL }}</td> <td>{{ order.DOL }}</td> <td>{{ order.POE }}</td> <td>{{ order.pickup_no }}</td> <td>{{ order.sales_contact }}</td> <td>{{ order.trucking_co }}</td> <td>{{ order.total_cases }}</td> <td>{{ order.total_fob }}</td> <td>{{ order.freight_forwarder }}</td> <td> {% if … -
Django Models Processing information using Business Logic
I have been trying to create a basic finance application using Django Frameworks that allows a user to input basic information such as their state, marriage status, etc in order to process the information with my django model, and spit out the processed answers such as the State Tax Rate, Federal Tax Rate, etc. I have had no problem getting the information from the user using my templates, views, forms, and models, but I have been running into trouble when trying to process the information. I have done my research and it seems that the best place to use "business logic" is in the models. However, I just can't seem to process my users information in order to have my model return an updated State tax rate value from my StateTax method in my models.py file. Here is my code below: Models.py: class Financer(models.Model): STATE_CHOICES=( ('AL','Alabama'), ('CA','California'), ('VA','Virginia') State=models.CharField(max_length=10,choices=STATE_CHOICES) StateTaxRate=models.IntegerField(default=0) def StateTax(self): if self.State in no_tax_states: self.StateTaxRate=3 self.save() elif self.State in variable_tax_states: self.StateTaxRate=2 self.save() elif self.State in flat_tax_states: self.StateTaxRate=1 self.save() def __str__(self): return self.State (This is a barebones version of my model in which I am trying to send the State information to my StateTax method in order to process … -
How can I create a view of database models in ascending order?
I have a model which looks like: from django.db import models from django.db.models import Avg # Create your models here. class Course(models.Model): name = models.CharField(max_length=254, default='') description = models.TextField() price = models.DecimalField(max_digits=6, decimal_places=2) image = models.ImageField(upload_to='images') def average_rating(self): return self.review_set.aggregate(Avg('rating'))['rating__avg'] def __str__(self): return self.name And I would like to create a view that would present each entry in ascending/decending order of it's average rating. I already have other views that do work like: def price_ascend(request): courses=Course.objects.order_by('price') return render(request, "courses.html", {"courses": courses}) However when trying a similar approach with the average rating: def rating_ascend(request): courses=Course.objects.order_by('average_rating') return render(request, "courses.html", {"courses": courses}) I run into this error: Cannot resolve keyword 'average_rating' into field. Choices are: description, id, image, name, orderlineitem, price, review Why doesn't this work? In my HTML I have: {% for course in courses|dictsortreversed:"average_rating" %} {{ course.average_rating | floatformat }} {% endfor %} This works and shows the average rating of each course. This is code where the Review class is defined from django.db import models from courses.models import Course # Create your models here. class Review(models.Model): RATING_CHOICES = ( (1, '1'), (2, '2'), (3, '3'), (4, '4'), (5, '5'), ) course = models.ForeignKey(Course) pub_date = models.DateTimeField('date published') user_name = models.CharField(max_length=100) … -
Is there a library that allows for auto populating the rows with class instances?
I'm working on a homework question and I have created different instances of how a pizza can be priced based on the size and the type. The issue I'm running into is that while the table view is useful, it isn't what I wanted and I read you can customize it way more in views.py but I don't see anything that can populate a table in a way where it can filter duplicates as in I have 2 cheese pizzas, one is in the large size and one small with their own pricing. Since it doesn't know anything about the headers. If I did use the listdisplay it will still show duplicates. Question I have is that do I have to manually change the logic flow in the HTML file itself? As in if field_name == the same while checking if the content of the td is the same, don't fill, and fill price if the td is empty. Does that mean I have to use some JS code? This just seems like such a common table issue that I think I must be missing something here (someone must have built a library to go specify your headers and row … -
Using wagtailmenus I want to regroup the main menu and seperate out items that have children vs items that don't have children
I'm build a custom main menu for wagtailmenus. When I get all the items, I want to presort the list of items into two groups. Items with children and items without children. I was thinking of using Django's regroup but I'm a little lost as to how to think about this. Here's what I'm thinking right now: {% regroup menu_items by has_children_in_menu as items %} {% if items %} <ul> {% for it in items %} <li>{{ has_children_in_menu.grouper }} # this would be the name of the parent <ul> {% for imenu in has_children_in_menu.list %} <li>{{ imenu.title }}</li> # the child {% endfor %} </ul> </li> {% endfor %} </ul> {% else %} <ul> {% for parent_item in menu_items %} <li>{{ parent_item.title }}</li> {% endfor %} </ul> {% endif %} Does this make sense? Am I crazy? Maybe I'm thinking about this wrong. What suggestions do you have? -
Ajax form submit and errors to appear in template in JSON format (django)
I have a django site: js $("#contactForm").submit(function(event){ event.preventDefault(); //prevent default action var post_url = $(this).attr("action"); //get form action url var form_data = $(this).serialize(); //Encode form elements for submission $.getJSON( post_url , form_data,function( response ) { //iterate json response $.each( response, function(key, val) { $("#msgSubmit").append( val + "<br />"); //append results to element }); }); }); views.py def contact_form(request): form = ContactForm(request.POST or request.GET) if form.is_valid(): data = { 'success': True, } status = 200 else: data = { 'success': False, 'errors': form.errors.get_json_data(), } status = 400 return JsonResponse(data, status=status) html <form id="contactForm" method="get" action="{% url 'contact-form' %}"> ... <button type="submit">Submit</button> </form> <div id="msgSubmit"></div> When I submit the form: If there is no validation errors, I get 'true' appearing at #msgSubmit. If there is an error, I get nothing. I want JSON errors to appear at #msgSubmit. -
How to get result with ORM from queryset
I want to get result with ORM of Django. But I cannot get result with ORM. I just tried with 'select_related("field_name")'. but doesn't work.. Actually, I don't know using ORM well haha... and.. This Query is my needs SELECT sol.idx, sol.sol_name, sol.sol_warning, sol.user_num_id, sol.auto_run_server, ur.user_ip, pc.cpu_usage, pc.mem_usage, pc.disk_usage FROM solution AS sol INNER JOIN ems.user AS ur ON sol.user_num_id = ur.user_num INNER JOIN pc_status AS pc ON sol.user_num_id = pc.user_num_id; result row is ... idx, sol_name, sol_warning, user_num_id, auto_run_server, user_ip, cpu_usage, mem_usage, disk_usage so.. I used code is " Solution.objects.select_related('user_num') " But I cannot get same result. here are my python codes. models.py class User(models.Model): user_num = models.IntegerField(primary_key=True, auto_created=True) user_ip = models.CharField(max_length=20) user_name = models.CharField(max_length=10) user_pwd = models.CharField(max_length=10) class Meta: db_table = 'user' class Solution(models.Model): idx = models.IntegerField(primary_key=True, auto_created=True) sol_name = models.CharField(max_length=50) sol_warning = models.IntegerField() user_num = models.ForeignKey(User, on_delete=models.CASCADE) auto_run_server = models.IntegerField() class Meta: db_table = 'solution' class PcStatus(models.Model): pc_idx = models.IntegerField(primary_key=True, auto_created=True) cpu_usage = models.IntegerField(default=0) mem_usage = models.IntegerField(default=0) disk_usage = models.IntegerField(default=0) user_num = models.ForeignKey(User, on_delete=models.CASCADE) class Meta: db_table = 'pc_status' -
how to send a message over websocket at a certain time
I am new to websockets and have just now gotten a working websocket connection in my application. I am trying to have the server check once per minute in the database to find upcoming tournaments, and for each player connected to a websocket that is registered in a tournament starting that minute, send a message that tournament with ID xxxxx is starting now. I have the following tournaments/consumers.py: from channels.generic.websocket import WebsocketConsumer import json class TournamentLobbyConsumer(WebsocketConsumer): def connect(self): self.accept() def disconnect(self, close_code): pass def receive(self, text_data): text_data_json = json.loads(text_data) message = text_data_json['message'] print("The websocket received a message: '%s'" % message) tournaments/routing.py: from django.conf.urls import url from . import consumers websocket_urlpatterns = [ url('ws/tournaments/$', consumers.TournamentLobbyConsumer), ] tournaments/templates/index.html: <!DOCTYPE html> <html> <head> <meta charset="utf-8"/> <title>Tournament Lobby</title> </head> <script> var chatSocket = new WebSocket( 'ws://' + window.location.host + '/ws/tournaments/'); chatSocket.onmessage = function(e) { // var data = JSON.parse(e.data); // var message = data['message']; alert("message received from websocket") }; chatSocket.onclose = function(e) { console.error('Chat socket closed unexpectedly'); }; </script> {% if tournaments %} <ul> {% for tournament in tournaments %} <li><a href="{% url 'tournament_detail' tournament.id %}"> {{ tournament.name }} {{ tournament.start_time }}</a></li> {% endfor %} </ul> {% else %} <p>No tournaments are available</p> {% … -
coreapi action create, No current document
I'm trying to post using coreapi and Django Rest Framework. I'm following this tutorial, which is based on the official one. Coreapi download the schema in a folder (PATH) which is not the current one, instead of logging some info as in the tutorial. $ coreapi get http://127.0.0.1:8000/schema/ <DownloadedFile 'PATH', open 'rb'> Then: $ coreapi action snippets list No current document. Use `coreapi get` to fetch a document first. And similarly I'm not able to post: $ coreapi credentials add 127.0.0.1 admin:testpass123 --auth basic Added credentials 127.0.0.1 "Basic YWRtaW46d2lsbGlhbTE=" $ coreapi action snippets create --param title="Example" --param co de="print('hello, world')" No current document. Use `coreapi get` to fetch a document first. I've tried to copy the schema file in the current directory in which the "coreapi action" command is executed, but no improvements. -
Join three serializers django
Right now I have a RelatedFileSerializer and a RequirementsSerializer. When I query the RequirementsSerializer, I would like it to return all the relatedfiles, and all the User information (email, first name, last name) for the relatedfiles, in place of the user ID that is being returned from the fire serializer. It properly returns the related files right now, but not the user information... views.py queryset = Controls.objects.filter(requirement_version=requirement) serializers.py class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('email', 'first_name', 'last_name') class RelatedFileSerializer(serializers.ModelSerializer): user = UserSerializer(many=False, read_only=True) class Meta: model = RelatedFiles fields = ('id', 'control', 'file', 'filename', 'uploaded_by_user', 'organization', 'note', 'uploaded_at') extra_kwargs = { 'uploaded_by_user': {'write_only': True}, 'organization': {'write_only': True}, } class RequirementsSerializer(serializers.ModelSerializer): relatedfiles_set = RelatedFileSerializer(many=True, read_only=True) class Meta: model = Controls fields = ('id', 'sorting_id', 'relatedfiles_set', 'requirement') -
Markdown is optional but my project already has Markdown 2.6 installed, get prepocessor error
I have Markdown 2.6 installed on my project and it is not feasible to update to version 3.0+ at this time. I see that Markdown 3.0+ is required, but because I have 2.6 it still successfully imports? As a result, in compat.py it successfully imports Markdown, however it breaks on line 213 because the highlight markdown preprocessor now uses register instead of add. The error is: Exception Type: AttributeError Exception Value: 'OrderedDict' object has no attribute 'register' Exception Location: /docker_venv/lib/python3.6/site-packages/rest_framework/compat.py in md_filter_add_syntax_highlight, line 213 How can I get around this? Is there a way to disable Markdown? Relevant issues/PRs I found: https://github.com/encode/django-rest-framework/pull/6722 https://github.com/encode/django-rest-framework/pull/6412 Thanks! -
how to pass a variable to a celery task
I want to pass a variable to a celery task, how to do this? From this code(POST method). class ArticleView(APIView): def get(self, request, task_id): task = current_app.AsyncResult(task_id) response_data = {'task_status': task.status,} if task.status == 'SUCCESS': response_data['results'] = task.get() return Response({"HTML-tags": response_data['results']}) def post(self, request): url = request.data.get('URL') print(url) task = demo.delay(url) return Response(task.id) To this: @shared_task def demo(url): page = requests.get(url) tree = html.fromstring(page.content) all_elms = tree.cssselect('*') all_tags = [x.tag for x in all_elms] baba = Counter(all_tags) return baba My attempt was unsuccessful.Error: TypeError: demo() takes 0 positional arguments but 1 was given. -
table "appname_modelname" already exists , migrate doesnt create new table
when i create a new model inside models.py and run : python manage.py makemigrations appname #worked python manage.py migrate #doesnt worked i got this error table "storage_OldModel" already exists i also checked this question Django migrate : doesn't create tables but there wasnt something to help me out this is the traceback please if someone know a solution please let me know -
Using filter_vertical or filter_horizontal for a CharField with choices
I'm searching for a way to use Django's .filter_vertical for a CharField (one that is passed a choices argument) rather than a ManyToManyField. Django's .filter_horizontal/.filter_vertical attributes produce a nice JavaScript "filter" interface in the admin UI: # models.py from django.db import models class Country(models.Model): code = models.SlugField(max_length=2, primary_key=True) name = models.CharField(max_length=64, db_index=True, unique=True) class MyModel(models.Model): countries = models.ManyToManyField(Country, blank=True) # ... other fields here # admin.py from django.contrib import admin @admin.register(MyModel) class MyModelAdmin(admin.ModelAdmin): # ... other attributes here filter_vertical = ("countries",) This generates a form widget like: However, I'd like to use this for a CharField that is passed a list of choices: class MyModel(models.Model): countries = models.CharField( max_length=2, blank=True, choices=[ ("us", "United States"), ("tz", "Tanzania"), # and so on ] ) # ... other fields here This doesn't work as it stands, because .filter_horizontal and .filter_vertical requires that the field be a ManyToManyField. So, to rephrase the question a bit more specifically: since it looks like .filter_vertical and .filter_horizontal use a FilteredSelectMultiple widget for that field, how could I properly use this widget for a CharField? -
writing Django custom model field
I want to write a custom field that shows size of an item. like: "small", "medium", "large", "extra large". It have to be optional like IntegerField. this is what I want it to be. I don't know where and what should I do. -
Transforming HTML table populated by database query into matrix-like summary table
I have an HTML table that contains transaction-style information(date, category, and value) for each row. I would like to change this table from being a simple row-by-row table into a matrix-style summary table, taking in a group by query from my database and displaying the group by parameters as the column and row headers. Query: SELECT MONTH(date) as month, category, value FROM transactions GROUP BY month, category Current Table (using a query without the group by): Month || Category || Value ------------------------------ Jan || Produce || 10 Jan || Poultry || 20 Feb || Poultry || 30 Feb || Poultry || 20 Desired Table: || Jan || Feb ------------------------------ Produce || 10 || 0 Poultry || 20 || 50 I have no trouble reading the data into my table or displaying it, but I have been struggling to figure out how to format or display a table or some alternative HTML object in the matrix-style I have described. This is the HTML code to create my current table. I am using Django as my framework (hence the django syntax {{}} to populate my table). This does not seem like a Django problem to me, so I am not including any …