I’m trying to create a table in a database where one field has empty values that a user needs to input. The entire table with the missing field should display. I built the following template:
table.html
<form method = "post">
<input type="submit" value="Submit">
{% csrf_token %}
<table>
<tr>
<th>Header 1</th>
<th>Input Header</th>
<th>Header 2</th>
<th>Header 3</th>
</tr>
{{ formset.management_form }}
{% for form in formset %}
{% for field in form %}
<tr>
<td>{{ field.field1 }}</td>
<td>{{ form }}</td> // this is my input field as a dropdown
<td>{{ field.field2 }}</td>
<td>{{ field.field3 }}</td>
</tr>
{% endfor %}
{% endfor %}
</table>
</form>
forms.py
from django.forms.widgets import Select
from django import forms
from .models import DbTable
from .models import Choices
class DbTableForm(forms.ModelForm):
class Meta:
CHOICES = Choices.objects.all().order_by("the_choice")
model = DbTable
fields = ["input_field"]
widgets = {
'input_field': Select(choices=([['', '']] + [[x.pkid, x.analyst] for x in CHOICES])),
}
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.queryset = DbTable.objects.filter(input_field__exact='')
views.py
def table_unassigned(request):
DbTableFormSet = modelformset_factory(DbTable, form=DbTableForm)
if request.method == 'POST':
formset = DbTableFormSet(request.POST)
if formset.is_valid():
formset.save(commit=True)
else:
formset = DbTableFormSet()
return render(request, 'table.html', {'formset': formset})
So I can see the dropdown for every record so the user can choose one and post it back but I can’t see the other fields and I can’t figure out how to show the other fields from the model.
Before I could see the data but only if I created a query object like:
data = DbTable.objects.filter(input_field__exact='')
But I’m not sure if I should do that. I was then sending the form and the data back with:
return render(request, 'table.html', {'form': form, 'data':'data'})
I could see the data for the model and have an input field but it seemed it was de-coupled so I moved everything to modelformset and now I can’t get at all the other fields in the model.
I’m just trying to create something like:
Header Field 1 | Input Field | Header Field 2 | Header Field 3 |
---|---|---|---|
Data 1 | Input Widget | Data 2 | Data 3 |
Data 4 | Input Widget | Data 5 | Data 6 |
How do you access the data of the model and display the values?
UPDATE
models.py
class DbTable(models.Model):
field1 = models.CharField(db_column='Field1', max_length=40, blank=True, null=True)
field2 = models.CharField(db_column='Field2', max_length=11, blank=True, null=True)
input_field = models.CharField(db_column='InputField', max_length=9, blank=True, null=True)
field3 = models.AutoField(db_column='Field3', primary_key=True)
class Meta:
managed = False
db_table = 'My_Table'
This is basically what the model looks like. Field3 is the primary key.