如何根据当前模型实例设置初始值

时间:2015-08-03 00:22:36

标签: django forms django-models django-forms

我正在尝试创建一个编辑表单来使用Django编辑当前对象。我无法尝试获取对象的当前id,以便将初始值设置为对象的当前值。

我想创建一个编辑表单,在用户编辑字段之前已经显示当前数据。我该怎么做呢?

感谢。

my forms.py:

class AddfooditemForm(forms.Form):
    quantity = forms.CharField(label="Quantity")
    price_per_pound = forms.CharField(label="price_per_pound")
    expiration_date = forms.CharField(label="expiration_date")
    price_per_item = forms.CharField(label="price_per_item")


class AddNonFooditemForm(forms.Form):
    quantity = forms.CharField(label="Quantity")
    price_per_item = forms.CharField(label="price_per_item")


class EditfooditemForm(ModelForm):
    quantity = forms.CharField(label="Quantity")
    price_per_pound = forms.CharField(label="price_per_pound")
    expiration_date = forms.CharField(label="expiration_date")
    price_per_item = forms.CharField(label="price_per_item")

    def __init__(self, *args, **kwargs):
        super(EditfooditemForm, self).__init__(*args, **kwargs)
    class Meta:
        model = tasks
        fields = ['quantity', 'price_per_item', 'expiration_date', 'price_per_pound']


class Edit_non_food_itemForm(ModelForm):
    quantity = forms.CharField(label="Quantity")
    price_per_item = forms.CharField(label="price_per_item")

    def __init__(self, *args, **kwargs):
        super(Edit_non_food_itemForm, self).__init__(*args, **kwargs)
    class Meta:
        model = tasks
        fields = ['quantity', 'price_per_item']

my views.py:

@csrf_exempt
def add_item(request):

    if request.method == 'POST' and 'add_food_form' in request.POST:
        add_food_form = AddfooditemForm(request.POST)
        if add_food_form.is_valid():
            # Cleaned_data
            input_type = 'food'
            quantity = add_food_form.cleaned_data['quantity']
            price_per_pound = add_food_form.cleaned_data['price_per_pound']
            expiration_date = add_food_form.cleaned_data['expiration_date']
            price_per_item = add_food_form.cleaned_data['price_per_item']
            foodDict = {'price_per_item': price_per_item,
                        'quantity': quantity,
                        'price_per_pound': price_per_pound,
                        'expiration_date': expiration_date}
            foodData = pickle.dumps(foodDict)
            item = items(input_type=input_type, foodData=foodData)
            item.save()
        return HttpResponseRedirect(reverse('backup_app.views.items_listing'))


    if request.method == 'POST' and 'add_non_food_form' in request.POST:
        add_non_food_form = AddNonFooditemForm(request.POST)
        if add_non_food_form.is_valid():
            # Cleaned_data
            input_type = 'non_food'
            quantity = add_non_food_form.cleaned_data['quantity']
            price_per_item = add_non_food_form.cleaned_data['price_per_item']
            non_foodDict = {'quantity': quantity,
                            'price_per_item': price_per_item}
            non_foodData = pickle.dumps(non_foodDict)
            item = items(input_type=input_type, non_foodData=non_foodData)
            item.save()
        return HttpResponseRedirect(reverse('backup_app.views.items_listing'))

    else:

        'add_food_form': AddfooditemForm()
        'add_non_food_form': AddNonFooditemForm()

    return render(request, 'backup_app/items_listing.html', {'add_food_form': add_food_form,'add_non_food_form': add_non_food_form})

@csrf_exempt
def edit_item(request, item_id):
    item = items.objects.get(id=item_id)

    if request.method == 'POST' and 'edit_food_form' in request.POST:
        edit_food_form = EditfooditemForm(request.POST, instance=item)
        if edit_food_form.is_valid():
            print "valid"
            # Cleaned_data
            item.input_type = 'food'
            quantity = edit_food_form.cleaned_data['quantity']
            price_per_pound = edit_food_form.cleaned_data['price_per_pound']
            expiration_date = edit_food_form.cleaned_data['expiration_date']
            price_per_item = edit_food_form.cleaned_data['price_per_item']
            foodDict = {'price_per_item': price_per_item,
                        'quantity': quantity,
                        'price_per_pound': price_per_pound,
                        'expiration_date': expiration_date}
            item.foodData = pickle.dumps(foodDict)
            item.save()
        return HttpResponseRedirect(reverse('backup_app.views.items_listing'))

    if request.method == 'POST' and 'edit_non_food_form' in request.POST:
        edit_non_food_form = Edit_non_food_itemForm(request.POST, instance=item)
        if edit_non_food_form.is_valid():
            # Cleaned_data
            item.input_type = 'non_food'
            quantity = edit_non_food_form.cleaned_data['quantity']
            price_per_item = edit_non_food_form.cleaned_data['price_per_item']
            non_foodDict = {'quantity': quantity,
                            'price_per_item': price_per_item}

            item.non_foodData = pickle.dumps(non_foodDict)
            item.save()
        return HttpResponseRedirect(reverse('backup_app.views.items_listing'))
    else:
        context = {
            'edit_food_form': EditfooditemForm(instance=item),
            'edit_non_food_form': Edit_non_food_itemForm(instance=item)
        }
    return render(request, 'backup_app/items_listing.html', context)

1 个答案:

答案 0 :(得分:1)

尝试这样的事情:

<强> forms.py:

class ChangeForm(forms.ModelForm):

    class Meta:
        model = MyModel
        fields = ['field1', 'field2']

    def __init__(self, *args, **kwargs):
        self.user = kwargs.pop('user')
        super(ChangeForm, self).__init__(*args, **kwargs)

<强> views.py:

# To render multiple forms, repeat the process
def account_settings(request):
    change_form = ChangeForm(request.POST or None,
                             instance=request.user, user=request.user)
    change_form_2 = ChangeForm2(request.POST or None)

    if request.method == 'POST':
        if change_form.is_valid():
            change_form.save()
        if change_form_2.is_valid():
            change_form_2.save()

    context = {
        'change_form': change_form,
        'change_form_2': change_form_2
    }
    return render(request, 'change_form.html', context)

这应该会给你当前的数据。

注意:根据需要更改属性。如果您发布代码,我可以帮助您。但是,我不知道你在做什么,但上面应该是一个很好的模板。

修改

<强> views.py:

@csrf_exempt
def add_item(request):
    add_food_form = AddfooditemForm(request.POST or None)
    add_non_food_form = AddNonFooditemForm(request.POST or None)

    if request.method == 'POST':
        if add_food_form.is_valid():
            input_type = 'food'
            quantity = add_food_form.cleaned_data['quantity']
            price_per_pound = add_food_form.cleaned_data['price_per_pound']
            expiration_date = add_food_form.cleaned_data['expiration_date']
            price_per_item = add_food_form.cleaned_data['price_per_item']
            foodDict = {'price_per_item': price_per_item,
                        'quantity': quantity,
                        'price_per_pound': price_per_pound,
                        'expiration_date': expiration_date}
            foodData = pickle.dumps(foodDict)
            item = items(input_type=input_type, foodData=foodData)

        if add_non_food_form.is_valid():
            input_type = 'non_food'
            quantity = add_non_food_form.cleaned_data['quantity']
            price_per_item = add_non_food_form.cleaned_data['price_per_item']
            non_foodDict = {'quantity': quantity,
                            'price_per_item': price_per_item}
            non_foodData = pickle.dumps(non_foodDict)
            item = items(input_type=input_type, non_foodData=non_foodData)

        item.save()

        # This needs to be a url name
        return HttpResponseRedirect(reverse('url_name_here'))

    context = {
        'add_food_form': add_food_form,
        'add_non_food_form': add_non_food_form
    }

    # Make this its own template
    return render(request, 'backup_app/items_add.html', context)


@csrf_exempt
def edit_item(request, item_id):
    item = items.objects.get(id=item_id)
    edit_food_form = EditfooditemForm(request.POST or None,
                                      instance=item)
    edit_non_food_form = Edit_non_food_itemForm(request.POST or None,
                                                instance=item)

    if request.method == 'POST':
        if edit_food_form.is_valid():
            item.input_type = 'food'
            quantity = edit_food_form.cleaned_data['quantity']
            price_per_pound = edit_food_form.cleaned_data['price_per_pound']
            expiration_date = edit_food_form.cleaned_data['expiration_date']
            price_per_item = edit_food_form.cleaned_data['price_per_item']
            foodDict = {'price_per_item': price_per_item,
                        'quantity': quantity,
                        'price_per_pound': price_per_pound,
                        'expiration_date': expiration_date}
            item.foodData = pickle.dumps(foodDict)

        if edit_non_food_form.is_valid():
            item.input_type = 'non_food'
            quantity = edit_non_food_form.cleaned_data['quantity']
            price_per_item = edit_non_food_form.cleaned_data['price_per_item']
            non_foodDict = {'quantity': quantity,
                            'price_per_item': price_per_item}

            item.non_foodData = pickle.dumps(non_foodDict)

        item.save()

        # This needs to be a url name
        return HttpResponseRedirect(reverse('url_name_here'))
    else:
        context = {
            'edit_food_form': EditfooditemForm(instance=item),
            'edit_non_food_form': Edit_non_food_itemForm(instance=item)
        }

    # Make this its own template
    return render(request, 'backup_app/items_edit.html', context)


def items_listing(request):
    # Any data you want to post about the listed items
    return render(request, 'backup_app/items_listing.html', {})