Django ModelForm-防止在视图中保存

时间:2018-07-31 23:39:30

标签: django django-forms django-views

我正在尝试使用ModelForm保存模型。

forms.py

class PurchaseForm(forms.ModelForm):

    weight = forms.IntegerField()

    class Meta:
        model = Purchase
        fields = ["number", "pieces"]

views.py

if request.method == "POST":
    form = PurchaseForm(request.POST)
    if form.is_valid():
        purchase = form.save(commit=False)
        purchase.contract = Contract.objects.get(number=slug)
        weight = form.cleaned_data.get('weight')
        if check_weight(weight, purchase.contract):
            weight_type = purchase.contract.supplier.market.weights
            purchase.lbs, purchase.kgs = generate_weights(weight, weight_type)
            purchase.save()

在上面的视图中,如果check_weight函数返回False,则需要阻止保存模型。 此功能需要相关对象的一些数据。我在解决这个问题上遇到了麻烦。我该怎么办?

1 个答案:

答案 0 :(得分:1)

如果我正确地理解了您的问题,这将会起作用,

from django.http import HttpResponse


def my_form_view(request):
    if request.method == "POST":
        form = PurchaseForm(request.POST)
        if form.is_valid():
            purchase = form.save(commit=False)
            purchase.contract = Contract.objects.get(number=slug)
            weight = form.cleaned_data.get('weight')
            if check_weight(weight, purchase.contract):
                weight_type = purchase.contract.supplier.market.weights
                purchase.lbs, purchase.kgs = generate_weights(weight, weight_type)
                purchase.save()
                return HttpResponse("save success")
            return HttpResponse("'check_weight' returned False")
    else:  # if a GET (or any other method) we'll create a blank form
        form = PurchaseForm()
    return render(request, 'some_html_template.html', {'form': form})