Django custom forms with models, also with 'choices' as values, how should I approach this problem?
django forms is giving me a pretty bad headache...
I've been struggling with this for 2 hours now.
I wanted to make a custom form for a model to be able to add objects to it and also be able to move the fields as I want to (instead of using form.as_p (or form|crispy), I wanted to put the entire form in a grid-like table using a custom pattern, not only putting one under another) but whenever I put a choicefield (which is either a choicefield or a foreignkey) their values are empty and also, 3 out of 4 formfields are actually shown, one remains the default.
It contains fields='__all__'
with 3 choicefields and 1 floatfield each with a label, nothing more.
To show the forms in html I used
{% for field in form.visible_fields %}
{{ field.label_tag }}
{{ field.errors }}
{{ field }}
{{ field.help_text }}
{% endfor %}
which works well. Am I trying to solve the problem in a wrong way? I'll come back to this topic tomorrow, I'll need some rest now but I don't understand why passing a choices=TheModel # or # choices=TheModel.ojbects.all()
breaks the entire thing.
Is there a website or a youtube channel that shows some solutions to those problems?
I lokoed up a bunch of sites and videos but they never access foreign keys as values to forms(dropdowns), never make grouped dropdowns (which I made and is working without custom forms).
Choices needs to be a tuple like this:
[
('CHOICE_ONE', 'choice_one')
]
So, you could create the choices list like this (Lets assume TheModel
has a name
field.)
choices = [(i.id, i.name) for i in TheModel.objects.all()]
The second value will be displayed to the user, the first one will be set in the database.
You could use a ModelChoiceField:
class FooMultipleChoiceForm(forms.Form):
foo_select = forms.ModelMultipleChoiceField(queryset=None)
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields['foo_select'].queryset = ...
https://docs.djangoproject.com/en/4.1/ref/forms/fields/#modelchoicefield