0

Im create with:

class FooForm(forms.ModelForm):
    class Meta:
        model = foo
        fields = '__all__'

an auto form of the model. this works fine. When i now render the fields with:

{% for field in formfields %}
    {{ field}}
{% endfor %}

create me this a field for the foreignkey, like a selectfield:

<select name="foo" required id="id_foo">
  <option value="">---------</option>
  <option value="1">A</option>
  <option value="2" selected>B</option>
  <option value="3">C</option>
  <option value="4">D</option>

I want but like to display only the selected option like a label:

B

My temporary solution is that I get the name in view.py via string processing and transfer it to the html.

optionname = str(Form['foo'][PFL['foo'].value()])
name = optionname.split(">")[1].split("<")[0]

I'm really dissatisfied with this solution...

Tesla
  • 1
  • 1

1 Answers1

0

If you want to just display a value instead of a <select> element then you have two options:

  1. Render the field as normal but set the form field as readonly so that it can't be edited, you can then style it differently so that it's obvious to the user that it can't be changed

  2. Just render the value of the form field with {{ field.value }} within a <p> element or something - just be mindful that this will not be passed to your form through request.POST unless you have an input. If you need to pass the value to the form then you can hide the input somewhere in the form so it doesn't mess with your form validation.

0sVoid
  • 2,547
  • 1
  • 10
  • 25
  • i have tries the two options: 1) i create the form (and the fields) automatically, so that i can not use the param readonly. how i can change the form fields in the view? 2) the tag {{ field.value }} give me the index from the selected option. i would have to use something {{ field[field.value] }} or {{ field.(field.value) }} but the syntax is not working. – Tesla Jul 17 '22 at 17:47
  • Here's how you can make a form field readonly: https://stackoverflow.com/questions/324477/in-a-django-form-how-do-i-make-a-field-readonly-or-disabled-so-that-it-cannot – 0sVoid Jul 17 '22 at 18:42
  • also readonly show a selected element – Tesla Jul 17 '22 at 19:12