Django设置默认表单值

oogrdqng  于 2022-12-14  发布在  Go
关注(0)|答案(9)|浏览(256)

我有一个模型如下:

class TankJournal(models.Model):
    user = models.ForeignKey(User)
    tank = models.ForeignKey(TankProfile)
    ts = models.IntegerField(max_length=15)
    title = models.CharField(max_length=50)
    body = models.TextField()

我也有一个模型形式为上述模型如下:

class JournalForm(ModelForm):
    tank = forms.IntegerField(widget=forms.HiddenInput()) 

    class Meta:
        model = TankJournal
        exclude = ('user','ts')

我想知道如何设置坦克隐藏字段的默认值。下面是我目前为止显示/保存表单的函数:

def addJournal(request, id=0):
    if not request.user.is_authenticated():
        return HttpResponseRedirect('/')

    # checking if they own the tank
    from django.contrib.auth.models import User
    user = User.objects.get(pk=request.session['id'])

    if request.method == 'POST':
        form = JournalForm(request.POST)
        if form.is_valid():
            obj = form.save(commit=False)

            # setting the user and ts
            from time import time
            obj.ts = int(time())
            obj.user = user

            obj.tank = TankProfile.objects.get(pk=form.cleaned_data['tank_id'])

            # saving the test
            obj.save()

    else:
        form = JournalForm()

    try:
        tank = TankProfile.objects.get(user=user, id=id)
    except TankProfile.DoesNotExist:
        return HttpResponseRedirect('/error/')
xe55xuns

xe55xuns1#

您可以使用Form.initial,这里将对此进行说明。
您有两个选项,可以在呼叫表单建构函式时填入值:

form = JournalForm(initial={'tank': 123})

或在表单定义中设置该值:

tank = forms.IntegerField(widget=forms.HiddenInput(), initial=123)
xpszyzbs

xpszyzbs2#

其他解决方案:创建表单后设置初始值:

form.fields['tank'].initial = 123
bsxbgnwa

bsxbgnwa3#

如果您从POST值创建modelform,则可以按以下方式分配initial:

form = SomeModelForm(request.POST, initial={"option": "10"})

https://docs.djangoproject.com/en/1.10/topics/forms/modelforms/#providing-initial-values

14ifxucb

14ifxucb4#

我有这个其他的解决方案(我张贴它的情况下,其他人像我一样使用以下方法从模型):

class onlyUserIsActiveField(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(onlyUserIsActiveField, self).__init__(*args, **kwargs)
        self.fields['is_active'].initial = False

    class Meta:
        model = User
        fields = ['is_active']
        labels = {'is_active': 'Is Active'}
        widgets = {
            'is_active': forms.CheckboxInput( attrs={
                            'class':          'form-control bootstrap-switch',
                            'data-size':      'mini',
                            'data-on-color':  'success',
                            'data-on-text':   'Active',
                            'data-off-color': 'danger',
                            'data-off-text':  'Inactive',
                            'name':           'is_active',

            })
        }

初始值在__init__函数中定义为self.fields['is_active'].initial = False

hgc7kmma

hgc7kmma5#

正如Django文档中所解释的,initial不是default

  • 字段的initial值应显示在HTML中。但是,如果用户删除此值,并最终为此字段返回一个空值,则initial值将丢失。因此,您无法获得 default 行为所期望的结果。
    *默认行为为:如果data参数不包含该字段任何值,则验证过程将采用的值。

要实现这一点,一种直接的方法是合并initialclean_<field>()

class JournalForm(ModelForm):
    tank = forms.IntegerField(widget=forms.HiddenInput(), initial=123) 

    (...)

    def clean_tank(self):
        if not self['tank'].html_name in self.data:
            return self.fields['tank'].initial
        return self.cleaned_data['tank']
i5desfxk

i5desfxk6#

我希望这能对你有所帮助:

form.instance.updatedby = form.cleaned_data['updatedby'] = request.user.id
sd2nnvve

sd2nnvve7#

我还遇到了在开发过程中需要在表单中设置默认值的问题。

initial={"":""}
form=ArticleModel(request.POST)
if form.has_changed():
    data = {i: form.cleaned_data[i] for i in form.changed_data}
    data.update({key: val for key, val in init_praram.items() if key not in form.changed_data})

使用form.has_changed,如果form.fields是必需的,则可以使用此方法

kg7wmglp

kg7wmglp8#

我如何将首字母添加到表单中:我读到了谢尔盖·戈洛夫琴科的回答。
所以我只是把它加到了if request.method == 'POST':的表单中,但是如果你想在发布表单之前看到它的值,那不是你要放它的地方,你需要把它放在else所在的表单中。
此处示例来自***views.py***

def myForm(request):
    kontext = {}

    if request.method == 'POST':
        # You might want to use clean_data instead of initial here. I found something on a stack overflow question, and you add clean data to the Forms.py, if you want to change the post data. https://stackoverflow.com/questions/36711229/django-forms-clean-data
        form = myModelForm(request.POST, initial={'user': request.user})
        if form.is_valid():
            form.save()
            return redirect('/')
    else:
        # you need to put initial here, if you want to see the value before you post it
        form = myModelForm(initial={'user': request.user})
    kontext['form'] = form
    return render(request, 'app1/my_form.html', kontext)
8cdiaqws

8cdiaqws9#

如果要添加初始值并发布其他值,则必须添加

或在请求后无.POST

form = JournalForm(request.POST or None,initial={'tank': 123})

如果您还想添加文件或图像

form = JournalForm(request.POST or None,request.FILES or None,initial={'tank': 123})

相关问题