预填充Django表单

编程入门 行业动态 更新时间:2024-10-25 12:24:52
本文介绍了预填充Django表单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在尝试从查询中获取Django表单,但我一直使用错误的方式。查看了一些示例,但是我做的有些不同。这是我的代码

I'm trying to have a Django Form from a query, but I keep doing it the wrong way. Checked out a few examples, but I'm doing it a bit different. Here's my code,

Le Form

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))

sho pping_list 行确实导致许多错误。

The shopping_list line is really leading to many errors.

推荐答案

您要将对象作为实例 。如果我正确理解您的代码,并且您有一个名为 item的项目:

You want to pass the object into the form as "instance". If I understand your code correctly and you had a single Item named "item":

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

在这种情况下,您似乎需要模型表单集,因此您可以一次编辑多个项目。然后,您将传递 items 变量作为 queryset参数。

In this case though, it looks like you want a model formset so you can edit multiple items at once. Then you would pass your items variable in as the "queryset" parameter.

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

Actual solution is for a different problem,

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

更多推荐

预填充Django表单

本文发布于:2023-08-05 20:49:18,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1307978.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:表单   Django

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!