Django:保存到模型领域

时间:2011-01-19 10:47:42

标签: django forms views save models

另一个django问题。我有这样的编辑表格。查看代码中的current_status。

已更新:

def edit_item(request, client_id = 0, item_id = 0):
    client = None
    item = None
    status = None
    contact = None
    status_id = request.POST.get('status_id', None)
    contact_id = request.POST.get('contact_id', None)
    save_item = request.POST.get('save_item', None)
    save_status = request.POST.get('save_status', None)
    try:
        client = models.Client.objects.get(pk = client_id)
        item = models.StorageItem.objects.get(pk = item_id)
    except:
        return HttpResponseNotFound()
    try:
        status = models.Status.objects.get(pk = status_id)
        contact = models.Contact.objects.get(pk = contact_id)
    except:
        pass
    if request.method == 'POST':
        form = forms.ItemForm(request.POST, instance = item)
        if form.is_valid() and save_item is not None:
            form.save(True)
            request.user.message_set.create(message = "Item {0} has been updated successfully.".format(item.tiptop_id))
            return HttpResponse("<script language=\"javascript\" type=\"text/javascript\">window.opener.location = window.opener.location; window.close();</script>")

        if status is not None and contact is not None and save_status is not None:
            current_status = models.ItemStatusHistory(item = item, contact = contact, status = status,
                                                          user = request.user)
            item.current_item_status_date = date.today()
            item.save()
            current_status.save()
            request.user.message_set.create(message = "Item status has been updated successfully.")
    else:
        form = forms.ItemForm(instance = item)
        title = str(client) + ' : Edit Item'
    status_list = models.Status.objects.all()
    return render_to_response('edit_item.html', {'form':form, 'title':title, 'status_list':status_list, 'item':item}, context_instance = RequestContext(request))

current_status保存表单编辑时的最新日期。我还想做的是将此值保存到此模型字段中。

  class StorageItem(models.Model):
       current_item_status_date = models.DateField()

1 个答案:

答案 0 :(得分:3)

ItemForm是否为ModelForm(请参阅Django Model Forms)?

如果是这样form.save()将返回一个模型实例。然后,您可以根据需要编辑其字段。例如。

my_obj = form.save()
my_obj.current_item_status_date = datetime.date.today()
my_obj.save()

如果没有,则只需创建模型的新实例并保存字段值。

my_obj = StorageItem(current_item_status_date=datetime.date.today())
my_obj.save()