【问题标题】:Pre-populating Django Forms预填充 Django 表单
【发布时间】:2012-07-20 01:34:26
【问题描述】:

我正在尝试从查询中获取 Django 表单,但我一直以错误的方式进行操作。检查了几个例子,但我做的有点不同。这是我的代码,

表格

class ItemForm(ModelForm):

    class Meta:
        model = Item
        exclude = ('deleted')

以及部分视图

def index(request):
    user = User
    try:
        last_modified_list = ShoppingList.objects.filter(deleted='0').filter(owner=user).latest('date_modified')
        items = Item.objects.filter(shopping_list=last_modified_list).filter(deleted='0')
    except ObjectDoesNotExist:
        items = Item.objects.filter(deleted='0')

    last_used_currency = ExtendedUser.objects.filter(owner=user)

    #currency = forms.CharField(initial=last_used_currency.last_currency)
    try:
        last_used_shoppinglist = ShoppingList.objects.filter(deleted='0').filter(owner=user).latest('date_modified')
    except ObjectDoesNotExist:
        last_used_shoppinglist = datetime.datetime.now()

    item_form = ItemForm (request.POST or None)
    item_form.fields["shopping_list"]=last_used_shoppinglist




    if item_form.is_valid():
        name =  item_form.cleaned_data['name']
        bought =  item_form.cleaned_data['bought']
        currency = item_form.cleaned_data['currency']
        price = item_form.cleaned_data['price']
        date_added = item_form.cleaned_data['date_added']
        date_modified = item_form.cleaned_data['date_modified']
        date_bought = item_form.cleaned_data['date_bought']
        shopping_list = item_form.cleaned_data['shopping_list']
        quantity = item_form.cleaned_data['quantity']
        deleted = item_form.cleaned_data['deleted']

    return render_to_response ('base.html',{'user':user,'items':items,'item_form':item_form}, context_instance=RequestContext(request))

shopping_list 行确实导致了很多错误。

【问题讨论】:

    标签: django django-forms


    【解决方案1】:

    您想将对象作为"instance" 传递到表单中。如果我正确理解您的代码并且您有一个名为“item”的项目:

    ItemForm(request.POST or None, instance=item)
    

    不过,在这种情况下,您似乎想要一个model formset,这样您就可以一次编辑多个项目。然后,您可以将 items 变量作为“queryset”参数传递。

    编辑:实际解决方案是针对不同的问题,

    item_form.fields["shopping_list"].initial = last_used_shoppinglist
    

    【讨论】:

    • 不,不创建模型实例。我试图让 shopping_list 从查询购物清单模型中获取初始值,当没有找到值时,使用今天的日期预先填充该字段。
    • 问题是您将last_used_shoppinglist 分配给表单字段,这不是您想要的。试试 item_form.fields["shopping_list"].initial = last_used_shoppinglist
    猜你喜欢
    • 1970-01-01
    • 2012-08-14
    • 2010-10-30
    • 2023-02-10
    • 2022-01-01
    • 2019-03-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多