我有一个模型如下:

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/')

当前回答

我希望这能帮助到你:

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

其他回答

如果你想添加初始值并发布其他值,你必须添加以下内容:

或请求后无。帖子

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

如果你也想添加文件或图像

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

你可以使用Form。首字母,这里有解释。

你有两个选择,要么填充值时调用表单构造函数:

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

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

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

如果你从POST创建modelform,初始值可以这样分配:

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

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

我希望这能帮助到你:

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

在开发过程中,我还遇到了在表单中设置默认值的需要。我的解决方案是

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})

使用的形式。Has_changed,if form。字段,您可以使用此方法