GVKun编程网logo

我的defaultdict(list)将不会显示在模板上,但会在我的视图中显示

30

在本文中,我们将带你了解我的defaultdict在这篇文章中,我们将为您详细介绍我的defaultdict的方方面面,并解答list将不会显示在模板上,但会在我的视图中显示常见的疑惑,同时我们还将给

在本文中,我们将带你了解我的defaultdict在这篇文章中,我们将为您详细介绍我的defaultdict的方方面面,并解答list将不会显示在模板上,但会在我的视图中显示常见的疑惑,同时我们还将给您一些技巧,以帮助您实现更有效的android-EditText将不会显示在ListView上方、Android软键盘不会在2.2/2.3中显示,但会在3.0中显示、asp.net-mvc-3 – ModelState.AddModelError不显示在我的视图、DefaultDimension 未显示在表单上

本文目录一览:

我的defaultdict(list)将不会显示在模板上,但会在我的视图中显示

我的defaultdict(list)将不会显示在模板上,但会在我的视图中显示

我想知道为什么defaultdict(list)当我在views.py中测试它时会显示出来,但是当我去显示模板上的数据时,却什么也没得到,甚至没有错误。

有什么建议?

这是我的views.py-Confirm_list是我的defaultdict(list)

def confirmations_report(request, *args, **kwargs):from investments.models import Investment, InvestmentManagerfrom reports.forms import ConfirmationsFormfrom collections import defaultdictimport ho.pisa as pisaimport cStringIO as StringIOimport os.pathconfirm_list = defaultdict(list)context = {}if request.POST:    form = ConfirmationsForm(request.POST)    if form.is_valid():        start_date = form.cleaned_data[''start_date'']        end_date = form.cleaned_data[''end_date'']        investments = Investment.objects.all().filter(contract_no = "",maturity_date__range=(start_date, end_date)).order_by(''financial_institution'')        for i in investments:            confirm_list[i.financial_institution.pk].append({                ''fi'':i.financial_institution,                ''fi_address1'': i.financial_institution.address1,                ''fi_address2'': i.financial_institution.address2,                ''fi_city'': i.financial_institution.city,                ''fi_prov'': i.financial_institution.state_prov,                ''fi_country'': i.financial_institution.country,                ''fi_postal'': i.financial_institution.postal,                ''primary_owner'': i.plan.get_primary_owner().member,                ''sin'': i.plan.get_primary_owner().member.client.sin,                ''type'': i.product.code,                ''purchase_amount'': i.amount,                ''purchase_date'': i.start_date,            })            context[''investments''] = investments        context[''confirmlist''] = confirm_list        for key, value in confirm_list.items():            print key, value        context[''inv''] = investments    if request.POST.has_key(''print_report_submit''):        context[''show_report''] = True        context[''mb_logo''] = os.path.join(os.path.dirname(__file__), "../../../media/images/mb_logo.jpg")        html = render_to_string(''reports/admin/confirm_report_print.html'', RequestContext(request,context))        result = StringIO.StringIO()        pdf = pisa.pisaDocument(StringIO.StringIO(html.encode("ISO-8859-1")), result)        response = HttpResponse(result.getvalue(), mimetype=''application/pdf'')        response[''Content-Disposition''] = ''attachment; filename=unreceived-confirmations.pdf''        return responseelse:    form = ConfirmationsForm()context[''form''] = formreturn render_to_response(''reports/admin/confirm_report.html'', RequestContext(request, context))

但是当我这样做时:

for key, value in confirm_list.items():            print key, value

在我的模板上像这样:

{% extends ''reports/admin/base.html'' %}{% load humanize %}{% block report_html %}<h3>Unreceived Confirmations Report</h3><form method="post" action=""><table>    <tr>        <td>            <strong> {{ form.start_date.label }}</strong> {{ form.start_date }}            <strong>{{ form.end_date.label }}</strong> {{ form.end_date }}        </td>    </tr></table><input type="submit" value="View Report">    <input type="submit" name="print_report_submit" value="Print Report"/></form>    {% for key, value in confirmlist.items %}        {{ key }} - {{ value }}    {% endfor %}{% endblock %}

我什么都没有。

这是在views.py中测试时得到的输出示例

33 [{''fi_address1'': u''Scotiabank FAS'', ''fi_country'': u''Canada'', ''fi_address2'': u''20 Queen Street West, Suite 2600'', ''fi_city'': u''TORONTO'', ''fi'': <FinancialInstitution: NATIONAL TRUST>, ''fi_prov'': u''Ontario'', ''fi_postal'': u''### ###'', ''purchase_amount'': Decimal(''30000.00''), ''purchase_date'': datetime.date(2011, 6, 27), ''type'': u''GIC'', ''sin'': u''###/###/###'', ''primary_owner'': <Member: #, #>}]

答案1

小编典典

发生这种情况的原因是Django模板语言执行变量查找的方式。当您尝试遍历字典项时,

{% for key, value in confirmlist.items %}

Django首先为进行字典查找confirmlist[''items'']。由于是defaultdict,因此返回一个空列表。

这也是一个残酷的陷阱,我也被刺痛了!

要变通解决此问题,请将您的defaultdict转换为字典,然后再将其添加到模板上下文中。

context[''confirmlist''] = dict(confirm_list)

或者,正如sebastientrottier在他对类似问题的回答中所解释的那样,设置default_factoryNone在添加到模板上下文之前。

confirm_list.default_factory = Nonecontext[''confirmlist''] = confirm_list

android-EditText将不会显示在ListView上方

android-EditText将不会显示在ListView上方

我有一个ListView活动,并且我想在其上方显示一个EditText(最后是一个按钮).

我相信我的xml很好,但是由于某种原因,EditText没有显示. ListView占据整个屏幕:(

我的XML如下所示:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
    <EditText
        android:id="@+id/newitemtext"
    android:layout_height="wrap_content"
    android:layout_width="fill_parent"
    android:hint="@string/add_new_item"
    android:maxLines="1"
    />
    <ListView
        android:id="@+id/android:list"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
    />
    <TextView
        android:id="@+id/android:empty"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/inBox_no_items"
    />
</LinearLayout>

有任何想法吗?

注意:在Eclipse中xml文件的布局选项卡中,将显示EditText.当我在模拟器中运行应用程序时,它不会.

感谢您的时间

更新:

这是我在onCreate方法中设置内容视图的地方

m_aryNewListItems = new ArrayList<MyListItem>();
m_Adapter = new Mylistadapter(this,R.layout.layout_list,m_aryNewListItems);
setlistadapter(m_Adapter);

这是我扩展的ArrayAdapter:

private class Mylistadapter extends ArrayAdapter<MyListItem> {

// items in the list
private ArrayList<MyListItem> m_items;

// constructor
public Mylistadapter(Context context,int textViewResourceId,ArrayList<MyListItem> items) {
        super(context,textViewResourceId,items);
        this.m_items = items;
}

// get specific list item
public MyListItem getItem(int position) {
    if (m_items.size() > position) {
        return m_items.get(position);
    }
    else {
        return null;
    }
}

/*
 * Update screen display
 */
@Override
public View getView(int position,View convertView,ViewGroup parent) {

    // get the View for this list item
    View v = convertView;
    if (v == null) {
        LayoutInflater vi = (LayoutInflater)getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        v = vi.inflate(R.layout.layout_list_item,null);
    }

    // get the next MyListItem object
    MyListItem lstItem = m_items.get(position);

    // set up the list item
    if (lstItem != null) {
        TextView txtItem = (TextView) v.findViewById(R.id.list_itemname);
        TextView txtQty = (TextView) v.findViewById(R.id.list_itemqty);
        TextView txtPlace = (TextView) v.findViewById(R.id.list_place);

        // set item text
        if (txtItem != null) {
            txtItem.setText(lstItem.getItemName());
        }

        // set qty text
        String strQtyText = "Qty: ";
        if (txtQty != null && lstItem.getItemQty() != -1) {
            BigDecimal bd = new BigDecimal(lstItem.getItemQty());
            strQtyText += bd.stripTrailingZeros().toString();
            if(lstItem.getItemQtyUnitId() != -1) {
                strQtyText += " " + lstItem.getItemQtyUnitTextAbbrev();
            }
        }
        else {
            strQtyText += "--";
        }
        txtQty.setText(strQtyText);

        // set place text
        if (txtPlace != null && lstItem.getPlaceName() != null) {
            txtPlace.setText(lstItem.getPlaceName());
        }
    }

    // return the created view
    return v;
}

}

最佳答案
将android:layout_weight =“ 1”添加到ListView xml

所以,这个东西:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:gravity="bottom"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="horizontal"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content">

        <EditText android:id="@+id/filter"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:singleLine="true"
            android:inputType="textAutoComplete"
            android:layout_weight="1"
            />

        <Button android:id="@+id/sort"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/sort"
            />

        <Button android:id="@+id/add_all"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/add_all"
            />

        <Button android:id="@+id/add"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/add"
            />
    </LinearLayout>

    <GridView android:id="@+id/myGrid"
        android:layout_width="fill_parent" 
        android:layout_height="fill_parent"
        android:layout_weight="1"

        android:verticalSpacing="15dp"
        android:horizontalSpacing="10dp"

        android:numColumns="auto_fit"
        android:columnWidth="60dp"

        android:gravity="center"
        />

</LinearLayout>

产生这个:

Android软键盘不会在2.2/2.3中显示,但会在3.0中显示

Android软键盘不会在2.2/2.3中显示,但会在3.0中显示

我的应用适用于 Android 2.2及更高版本.在其中,我使用 ActionbarSherlock来允许3.0之前的设备使用操作栏.我在操作栏中使用了EditText来允许用户输入文本进行搜索.

使用模拟器,使用Android 4.0和4.1(我没有尝试3.x,因为它不是平板电脑应用程序),当选择EditText时,软键盘会根据需要弹出.但不是这样使用Android 2.2或2.3.3,它只是不显示.

EditText的代码很简单:

item.setActionView(R.layout.collapsible_edittext);
etInput = (EditText) item.getActionView().findViewById(R.id.etInput);   
etInput.requestFocus();

布局:

<?xml version="1.0" encoding="utf-8"?>
<EditText xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/etInput"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:hint="@string/search_hint"
    android:lines="1" 
    android:maxLines="1"
    android:inputType="textFilter|textNoSuggestions"
    android:imeOptions="actionSend"/>

现在我尝试在etInput.requestFocus();之后立即使用此代码段专门显示软键盘,但它没有区别:

InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(etInput,InputMethodManager.SHOW_IMPLICIT);

我试图弄清楚这是ActionbarSherlock的问题还是更普遍的Android问题.我在一篇活动中搜索了许多关于强制软键盘显示的文章,但还没有找到解决方案.

谢谢

解决方法

我有同样的问题……一切正常,直到我在HTC Nexus One上测试.我最终将以下代码添加到附加到AciontBarSherlock menuItem的onActionExpandListener.
item.setonActionExpandListener(new OnActionExpandListener() {

    @Override
    public boolean onMenuItemActionExpand(MenuItem item) {
    // post delayed to allow time for edittext to become visible
    mHandler.postDelayed(new Runnable() {
        @Override
        public void run() {
        mSearchText.clearFocus();
        showKeyboard();         
        mSearchText.requestFocus();
        }
    },400);

    return true;
    }

    @Override
    public boolean onMenuItemActionCollapse(MenuItem item) {
    hideKeyboard();
    return true;
    }
});

private void showKeyboard() {
 if (android.os.Build.VERSION.SDK_INT < 11) {
    mInputManager.toggleSoftInput(InputMethodManager.SHOW_FORCED,InputMethodManager.HIDE_IMPLICIT_ONLY);
 } else {
    mInputManager.showSoftInput(mSearchText,InputMethodManager.SHOW_IMPLICIT);
 }
}

private void hideKeyboard() {
 if (android.os.Build.VERSION.SDK_INT < 11) {
   mInputManager.hideSoftInputFromWindow(getActivity().getwindow().getCurrentFocus().getwindowToken(),0);      
 } else {
    mInputManager.hideSoftInputFromWindow(getActivity().getCurrentFocus().getwindowToken(),InputMethodManager.HIDE_NOT_ALWAYS);
 }  
}

asp.net-mvc-3 – ModelState.AddModelError不显示在我的视图

asp.net-mvc-3 – ModelState.AddModelError不显示在我的视图

我有以下视图,其中创建10 ajax.beginform,但我面临的问题是,在创建对象期间发生错误,那么ModelState.AddModelError将不会显示在视图上,虽然我已设置@ Html.ValidationSummary(true)
视图如下
@model Medical.Models.VisitLabResult

@for (int item = 0; item < 10; item++)
{
    <tr id = @item>
    @using (Ajax.BeginForm("Createall","VisitLabResult",new AjaxOptions
    {
        HttpMethod = "Post",UpdateTargetId = item.ToString() + "td",InsertionMode = InsertionMode.Replace,LoadingElementId = "progress2",OnSuccess = string.Format(
            "disableform({0})",Json.Encode(item)),}))
    {  
        @Html.ValidationSummary(true)

        @Html.AntiForgeryToken()
        <td>
            @Html.DropDownList("LabTestID",String.Empty)
            @Html.ValidationMessageFor(model => model.LabTestID)
        </td>
        <td>
            @Html.EditorFor(model => model.Result)
            @Html.ValidationMessageFor(model => model.Result)
        </td>

        <td>
            @Html.EditorFor(model => model.DateTaken)
            @Html.ValidationMessageFor(model => model.DateTaken)
        </td>

        <td>
            @Html.EditorFor(model => model.Comment)
            @Html.ValidationMessageFor(model => model.Comment)
        </td>

        <td>
            <input type="submit" value="Create" />
        </td>

        <td id = @(item.ToString() + "td")>
        </td>
    }
    </tr>
    }
</table>

而我定义ModelState.AddModelError的action方法如下: –

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Createall(VisitLabResult vlr,int visitid = 28)
{
    try
    {
        if (ModelState.IsValid)
        {
            var v = repository.GetVisit(visitid);
            if (!(v.EligabletoStart(User.Identity.Name))){ 
                return View("NotFound"); 
            }
            vlr.VisitID = visitid;
            repository.AddVisitLabResult(vlr);
            repository.Save();

            return Content("Addedd Succsfully");
        }
    }
    catch (dbupdateException)
    {
        JsonRequestBehavior.AllowGet);
        ModelState.AddModelError(string.Empty,"The Same test Type might have been already created,go back to the Visit page to see the avilalbe Lab Tests");
    }
}

所以我可以在我的视图中显示ModelState.AddModelError。

解决方法

我会敦促你改变你的try {} catch(){}

并首先检查是否存在给定id的访问
并且如果这样简单地返回具有添加的模型误差的模型

if (visitExists)
    {
         ModelState.AddModelError("CustomError",go back to the Visit page to see the avilalbe Lab Tests");
         return View(vlr);    
    }
    //Other code here

将您的AddModelError更改为

ModelState.AddModelError("CustomError",go back to the Visit page to see the avilalbe Lab Tests");

在你看来简单地添加一个

@Html.ValidationMessage("CustomError")

然后当你返回你的模型时,错误会显示你放置了@ Html.ValidationMessage …

DefaultDimension 未显示在表单上

DefaultDimension 未显示在表单上

如何解决DefaultDimension 未显示在表单上?

有一种情况,即 DefaultDimension 字段未显示在表单上。我花了一整天的时间试图解决这个问题,但没有运气。但是,我设法在 Marija Petroska 的提示下修复了它。

解决方法是将表单设计的“Set Company”属性设置为“Yes”。

ps:我试图用 #defaultdimension 标签标记这个问题,但它需要“至少 1500 声望”,抱歉。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

今天的关于我的defaultdictlist将不会显示在模板上,但会在我的视图中显示的分享已经结束,谢谢您的关注,如果想了解更多关于android-EditText将不会显示在ListView上方、Android软键盘不会在2.2/2.3中显示,但会在3.0中显示、asp.net-mvc-3 – ModelState.AddModelError不显示在我的视图、DefaultDimension 未显示在表单上的相关知识,请在本站进行查询。

本文标签: