1
I have an expense form that has a field to select the category, but I need the options to be obtained from the database.
These days this is mine forms.py
:
from django import forms
from .models import Expense
class ExpenseForm(forms.ModelForm):
class Meta:
model = Expense
fields = '__all__'
In the views.py
can create a query to return the categories:
def get_expense_categories():
with connection.cursor() as cursor:
cursor.execute(""" select * from units_accountplan;""")
categories = dictfetchall(cursor)
This table units_accountplan
has a simple structure:
id | Category
1 | Petrol
2 | Electricity
You can use this query to fill in the form options, or some other way to do this?
This table is inside Django’s data models or is outside the application?
– Giovanni Nunes
is outside the application, is another Django project that shares the same database, so I can not access directly by model
– Leila
Since it is a database of another application the most appropriate solution would be to create a REST API in the first application providing the table data
accountplan
, hence recover this data directly in HTML via Javascript (It is that I am considering the fact that one day these two applications may no longer be in the same DBMS).– Giovanni Nunes