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:
user
andnetwork
fields are not allowed to come fromrequest.POST
. For example ifuser
should be the currently logged in user which comes fromrequest.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.
user
andnetwork
fields are allowed to come fromrequest.POST
. Then you do:form = StartForm(request.POST, initial={"user": user, "network": network})
Note that in this case
user
andnetwork
fields may be overriden by values which come fromrequest.POST
.
精彩评论