I have three mysql tables without pk’s assigned, table A contains unique names, B contains distinct names and value 1 (longer than table 1), and table C is distinct values of names, value 1 and value 2 (longer than table B). I am struggling to define models and form for these relationships to create a form (Django form or html select form) to do what django smart_selects promises to do. https://github.com/digi604/django-smart-selects, I have followed the documentation and many answers on the net. But my app is still not working. here is my code: there may be typo's or spacing issues on this post, but those are not the cause of errors in my app. I am using python 2.7, django 1, 10, 0 smart_selects is added to settings, project url (not app url), etc.
models.py
class Names(models.Model):
name = models.CharField(max_length=150, unique=True)
class Meta:
db_table = 'A'
class Foo(models.Model):
Name = models.ForeignKey(Names, to_field = 'name', db_column='name')# need to assign db_column or get error Name_id in fieldlist, it is possible that “to_field” is not needed here. But I am not sure
Val1 = models.BigIntegerField(blank=True, null=True)
class Meta:
db_table = 'B'
class Foo2(models.Model):
name = models.ForeignKey(Names, db_column='name', to_field="name", related_name = 'name_')
VAL1 = ChainedForeignKey(Foo, chained_field="name", chained_model_field="Name", db_column='val1')#again, need to define db_column name or get error VAL1_id not in field list
class Meta:
db_table = 'C'
forms.py -not currently using this form, please see view and html.
class SearchForm(ModelForm):
class Meta:
model = Foo2
fields = '__all__'
#The form left like is will render empty select boxes. I have to define
def __init__(self, *args, **kwargs):
super(SearchForm, self).__init__(*args, **kwargs)
self.fields['name'] = forms.ModelChoiceField(Foo2.objects.all().values_list('name', flat=True))
#other form lines removed.
and view.py
def index(request, name):
value = Foo2.objects.all().values('names', 'VAL1')
return render(request, 'index.html', {'form':value})
html
<form action="" method="POST">{% csrf_token %}
<h3>Filters</h3>
{% if form %}
<select>
{% for co in form %}
<option value="{{ co.names }}">{{ co.names }}</option>
{% endfor %}
</select>
<br>
<select>
{% for co in form %}
<option value="{{ co.VAL1 }}">{{ co.VAL1 }}</option>
{% endfor %}
</select>
{% endif %}
<br>
<input type="submit" value="Submit" class="submit" name="submit">
</form>
After writing the code, I have run:
Python manage.py makemigrations app_name
Python manage.py migrate --fake app_name
The application works, but the VAL1 select box is not filtered (smart_select functionality is not working). What I need to know if there is something wrong in my design of the models/apps.
thank you