add selected in form option

Hello all

What I am trying to do sounds simple but I can’t make it to work… I didn’t find any solution on this forum.

  • I have this form with < select > and some < options > from the database
  • When the user selects a new option the form submits automatically with javascript, makes a save or update in the view and then renders the same page again
  • Now I want the created/updated field to be selected by outputting < option selected > so I loop trough the database and I want to set the variable

What is the best approach for this?

When I try {% with selected = "selected %} I can’t use that variable outside the for loop.
I tried {% firstof “selected” as selected %} and {% trans “selected” as selected %} but didn’t work.

Thanks for the reply.

What do you mean by:

Now I want the created/updated field to be selected

What is the “created/updated” field?

It’s going to be a whole lot easier to work through this if you post the view and template involved here, so we can see what you’ve got so far.

When you post code and template snippets, please insert them between lines containing only 3 backticks - ```. (Make sure you use the backtick - ` and not the apostrophe - '.) That means you would have one line with the 3 backticks, your code, and then one more line with just the 3 backticks. This allows this forum software to format your code nicely:

# The line above this is just ```
def function(parm):
    return parm
# The line after this is just ```

The view:

@login_required
def dashboard(request, dienststaat_id, datum):
    template = "dashboard/dashboard.html"
    context = {}

    # variabelen vullen
    try:
        lidmaatschap = DienststaatMembership.objects.get(user=request.user.id, favoriet=True)
    except ObjectDoesNotExist:
        lidmaatschap = None
    
    context ['lidmaatschap'] = lidmaatschap

    if lidmaatschap:
        dienststaat = Dienststaat.objects.get(id=lidmaatschap.dienststaat.id)
   
    context ['dienststaat'] = dienststaat
    context ['diensttijden'] = Diensttijd.objects.filter(dienststaat=dienststaat_id)
    context ['diensten'] = Dienst.objects.filter(begindatum=datum)
    context ['eenheden'] = Eenheid.objects.filter(dienststaat=dienststaat)
    context ['gekoppeldeeenheden'] = GekoppeldeEenheid.objects.filter(eenheid__dienststaat = dienststaat_id)
    context ['vandaag'] = timezone.now()
    context ['morgen'] = timezone.now() + timedelta(days=1)
    context ['overmorgen'] = timezone.now() + timedelta(days=2)
    context ['driedagen'] = timezone.now() + timedelta(days=3)
    context ['vierdagen'] = timezone.now() + timedelta(days=4)
    context ['vijfdagen'] = timezone.now() + timedelta(days=5)
    context ['zesdagen'] = timezone.now() + timedelta(days=6)
    
    return render(request, template, context)

The template:

<div id="collapse{{ diensttijd.id }}" class="accordion-collapse collapse card" aria-labelledby="heading{{ forloop.counter }}" data-parent="#accordionDiensten">
                                <div class="accordion-body card-body col-lg-10">
                                    {% if diensten.count > 0 %}
                                        {% for dienst in diensten %}
                                            <div class="row">
                                                {% if diensttijd.aanvang == dienst.tijd %}
                                                    <div class="col-lg-1">{{ dienst.eenheid }}
                                                        <form id="koppelform{{dienst.id}}" action="{% url 'dashboard:koppel_eenheid_aan_dienst' dienststaat.id dienst.id vandaag|date:'Y-m-d' %}" method="POST"> 
                                                            {% csrf_token %}
                                                                <div class="form-group">
                                                                <select onchange="document.getElementById('koppelform{{dienst.id}}').submit();" class="form-control" id="selectEenheid" name="selecteenheid">
                                                                    {% for eenheid in eenheden %}
                                                                        {% if forloop.first %}
                                                                            <option>--------</option>
                                                                        {% endif %} 
                                                                        <option>{{ eenheid.naam }}</option>
                                                                    {% endfor %}
                                                                </select>
                                                            </div>
                                                        </form>
                                                    </div>
                                                    {% for gekoppeldeeenheid in gekoppeldeeenheden %}
                                                        {% if dienst.naam == gekoppeldeeenheid.dienst.naam %}
                                                            <div class="col-lg-2">{{ gekoppeldeeenheid.eenheid }}</div>
                                                        {% endif %}
                                                    {% endfor %}
                                                    
                                                    <div class="col-lg-5">{{ dienst.naam }}</div>
                                                    <div class="col-lg-2">{{ dienst.memo_medew }}</div>
                                                {% endif %}
                                            </div>
                                        {% endfor %}
                                    {% else %}
                                        Er zijn geen collega's ingepland.                                                            
                                    {% endif %}
                                </div>

(Hmmm… I wish I had learned some Dutch when I worked for AEGON so many years ago…)

If I’m understanding this all correctly, it’s in this line:

<option>{{ eenheid.naam }}</option>

That you would want to change to something like:

<option {% if "some condition" %}selected{% endif %}>

(I will admit, I’m having a tough time understanding what all you’re trying to do here - I hope I’m not misinterpreting things too badly.)

Sorry for not being very clear about the problem … :slight_smile:
Your reply did help me. When I tried again to make the if statement it worked! I checked if the option value was the same as the value in database and it got selected. I am still having trouble to get database fields from related models in the template. I have done something like this:

object.relatedmodel_set.get.field 

Is that the correct way?

Thank you very much for helping me

I think the issue you may run into with that is that relatedmodel_set could end up being a list and not a single item, so relatedmodel_set.get.field may not work. You might need to iterate over that and do something with each instance - getting the field from the instance each time through the loop.

When I’m not sure how I want to access something in a template, I’ll frequently do some exploring in the Django shell. (or shell_plus using django_extensions) I find that to be the easiest way to check what expressions to use and to see what I’m going to get.

Ok Ill look into that. Thanks a lot!