简体   繁体   中英

How can I resolve my variable's unexpected output?

I have a variable in django named optional_message . If I debug the variable then it says Swenskt but when I try to print the variable on my page the following comes out: (u'Swenskt',) and the variable can't be tested for its length etc. What should I do if I only want the variable to be Swenskt and not (u'Swenskt',) ? Why is it a tuple when my other variable isn't?

The backend code is:

    optional_message = form.cleaned_data['optional_message'],
    optional_message_en = form.cleaned_data['optional_message_en']
    if tutoring_language == 'en' and optional_message == '':
        optional_message=optional_message_en

    if tutoring_language == 'sv' and optional_message_en == '':
        optional_message_en=optional_message


    return render(request, "survey/confirm_survey.html", {
        "context": course.context,
        "tutoring_language": tutoring_language,
        "trans_lang": trans_lang,
        "start_date": _short_date_format(form.cleaned_data['start_date']) + ' ' + form.cleaned_data[
            'start_date'].strftime("%Y"),
        "end_date": _short_date_format(form.cleaned_data['end_date']) + ' ' + form.cleaned_data['end_date'].strftime(
            "%Y"),
        "email": request.user.email,
        "form": form,
        "admin_roles": _get_admin_roles(request, course.context),
        "process_id": process_id,
        "enable_progress_bar": str(settings.ENABLE_PROGRESS_BAR).lower(),
        "extra_questions": form.cleaned_data['extra_questions'],
        "optional_message": optional_message,
        "optional_message_en": optional_message_en,
        "template": template,
        'subgroups': subgroup_dicts
    })

My django template code is

                {%  if optional_message|length > 1 %}
                <li>
                    {% trans "Svenska" %}:
                </li>
                <li>
                    {{ optional_message }}
                </li>
                <br/>
                {%  endif %}

Update

The following code fixed it, but why? Why is the variable a tuple when the other variable isn't?

        {%  if optional_message %}
        <li>
            {% trans "Svenska" %}:
        </li>
        <li>
            {{ optional_message.0 }}
        </li>
        <br/>
        {%  endif %}

The form code is:

optional_message = forms.CharField(
    widget=forms.Textarea(attrs={'rows':4, 'cols':15}),
    label=_(u'Valfritt meddelande till studenter:'),
    required=False,
)

Remove the comma on your first line of code, this turns it into a tuple

 optional_message = form.cleaned_data['optional_message'],

should be

 optional_message = form.cleaned_data['optional_message']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM