I’m not sure how to tackle this problem – I’ve tried a bunch of things but the outcome is that I get a “too many values to unpack” error after submitting the form.
This is a simple demo of the models that are in play:
class Supplier(models.Model):
name = models.CharField(max_length=100)
class SupplierLocation(models.Model):
supplier = models.ForeignKey(Supplier)
location = models.CharField(max_length=100)
class Product(models.Model):
supplier = models.ForeignKey(Supplier)
name = models.CharField(max_length=100)
price = models.DecimalField(decimal_places=2,max_digits=10)
What I’m trying to do is produce a form that has 2 lots of radio buttons. SupplierLocation.location is the labels and SupplierLocation.id would be the value for the radio button. Likewise Product.name would be the label and Product.id would be the value for the radio button. The idea is that I want to group them into blocks sorted by Supplier.id so that the html looks something like this:
<div>
<table>
<tr class="{{ Supplier.name }} hidden">
<td>{{ location.name }}</td>
<td><input type="radio" name="location_id" value="{{ location.id }}" /></td>
</tr>
</table>
<table>
<tr class="{{ Supplier.name }} hidden">
<td>{{ product.name }}</td>
<td>{{ product.price }}</td>
<td><input type="radio" name="product_id" value="{{ product.id }}" /></td>
</tr>
</table>
</div>
Obviously there would be multiple rows in both tables and I’m pretty sure that I should be able to use a widget in place of the hardcoded input fields however I’m puzzled how to achieve the custom form. The idea is that all the fields are hidden when the page loads and when a supplier is chosen from a link on the page the fields are made visible with JS.
I’m unsure what the form should look like and whether I should be using a modelform or a standard form. In my current test I have a form that looks like this:
forms.py
class ProductLocationForm(forms.Form):
PRODUCT_CHOICES = [(p.id, p.name) for p in Product.objects.all()]
LOCATION_CHOICES = [(l.id, l.name) for l in SupplierLocation.objects.all()]
product = forms.ChoiceField(widget=forms.RadioSelect, choices=PRODUCT_CHOICES)
location = forms.ChoiceField(widget=forms.RadioSelect, choices=LOCATION_CHOICES)
This gives me the products and locations but is missing the groupings by supplier or any way of isolating the supplier so I can hide/show them with JS.
Any help would be awesome.
You can use
ModelChoiceFieldinstead of constructingchoicesmanually. Then you’ll have aquerysetattribute for the field and will be able to something like that in the templates: