[Answered ]-Create a django form object and save it

2👍

If you want to create a model instance (in this case a User) in a view from data that doesn’t come from some POST or GET data, then don’t use forms, but rather the model’s API.

For instance the User class provides this helper function (example taken from the documentation) :

from django.contrib.auth.models import User

user = User.objects.create_user('john', 'lennon@thebeatles.com', 'johnpassword')

More details here :
https://docs.djangoproject.com/en/1.7/topics/auth/default/#user-objects

and here :
https://docs.djangoproject.com/en/1.7/ref/contrib/auth/#django.contrib.auth.models.UserManager.create_user

This works for any model class. You can use is to create your guest user dynamically if you don’t know the client, while you would log him/her otherwise.

The part when you decide whether you know a client or not is actually interesting but I think it’s out of this question’s scope.

0👍

If I understand what you are trying to achieve, you can create a dictionary of form_data, and then instantiate the form passing in the dict.

form_data = { "key1": val1, "key2": val2, "key3": val3}
form = MyForm(data=form_data)

You could do this in the form_valid() method if you are using class-based views.

Leave a comment