Django表单每次输出默认字段值

时间:2018-04-11 21:46:07

标签: python django

这是我的模特/表格:

from django.shortcuts import render
from django.http import HttpResponse
from django.contrib.auth.decorators import login_required
from ico_login.models import UserAddress 
from coinbase.wallet.client import Client


@login_required()
def generate_address_btc(request, *args, **kwargs):
    client = Client('api', 'key')
    r = client.get_addresses('account_id')
    address = r['data'][0]['address']
    # next 2 lines changed
    request.user.user_address.address = str(address)
    request.user.user_address.save()

return HttpResponse(address)

视图

class AdvertisePost(Post):
    position = models.IntegerField(default=DURATION_CHOICES[2][0], choices=DURATION_CHOICES)
    duration = models.IntegerField(default=48)

    def __str__(self):
        return self.title


class AdvertisePostForm(forms.ModelForm):
    position = forms.ChoiceField(widget=forms.RadioSelect, required=False, choices=DURATION_CHOICES)
    duration = forms.IntegerField(widget=forms.NumberInput(attrs={'type':'range', 'step': '1', 'min': '1', 'max': '148'}), required=False)

    class Meta:
        model = AdvertisePost
        fields = [
            ...
            'position',
            'duration'
        ]

和我的模板

def options(request):
    options_form = AdvertisePostForm(request.POST or None, request.FILES or None)

    if options_form.is_valid():
        instance = options_form.save(commit=False)
        print(instance.duration) #prints 8 every time (default value)
        print(instance.position) #prints 48 every time (default value)

    context = {
        'options_form': options_form
    }

    return render(request, 'advertising/options.html', context)

即使我更改了值,它每次都会输出相同的默认值。知道为什么会这样,以及如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

  

这个save()方法接受一个可选的commit keyword参数   接受True或False。如果使用commit = False调用save(),   然后它将返回一个尚未保存到的对象   数据库。在这种情况下,您可以在结果上调用save()   模型实例。如果要进行自定义处理,这非常有用   保存之前的对象,或者如果要使用其中一个   专业的模型保存选项。默认情况下,commit为True。

您正在获取具有默认值的实例。 在Django Docs - Save Method

中查看更好