开发者

Expanding on django forms

I have a modelform, which has three required fields: user, network, and position. The position is pulled by request.POST, and the other two will be supplied outside of it. This is what I currently have:

form = StartForm(request.POST)
form.save()

Obviously, this form is not validating, because I haven't provided the user 开发者_如何学Pythonand network instances. How do I add this additional information to the form? Conceptually, I'm looking for something like this:

form = StartForm(request.POST + user_id=10, network_id=20)
form.save()


Can't you do something similar to: form = StartForm(position = request.POST, user_id = 10, network_id = 20)? You might have to print the value for request.POST since I think it's actually a list. So just find out what position is in the request.POST


There are two options there:

  1. user and network fields are not allowed to come from request.POST. For example if user should be the currently logged in user which comes from request.user.

    In that case you can do:

    class StartForm(form.models.ModelForm):
    
        class Meta:
            model = MyModel
            fields = ["position", ] # You don't include user and network to the form
    
    form = StartForm(request.POST, instance=MyModel(user=user, network=network))
    

    So you initialize the form with a model which has pre-filled fields.

  2. user and network fields are allowed to come from request.POST. Then you do:

    form = StartForm(request.POST, initial={"user": user, "network": network})
    

    Note that in this case user and network fields may be overriden by values which come from request.POST.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜