1👍
The form class generated by a CreateView
(or any model form for that matter) does not have an _id
field for any foreign key. Instead, it has a field user
which is a ModelChoiceField
.
Furthermore, that logic should not be contained in your form. A form is merely a means of capturing and validating user input. Which user creates an object is not user input, and such logic should be in your view, e.g.:
class CreateTableView(generic.CreateView):
model = Vtable
fields = ['table_name']
def form_valid(self, form):
form.instance.user = self.request.user
return super(CreateTableView, self).form_valid(form)
1👍
In order to pass a custom value to the form, you’ll have to create your own form class and pass that into the view. The default form class that the view creates doesn’t know what to do with your user_id
argument, and that’s where the error comes from.
Here is an example on how to pass a custom form class, first the form class:
class MyForm(forms.ModelForm):
class Meta:
model = Vtable
def __init__(self, *args, **kwargs):
user_id = kwargs.pop('user_id') # Pop out your custom argument
super(MyForm, self).__init__(args, kwargs) # Initialize your form
# as usual
self.user_id = user_id # Add it as an instance variable
Then, in your view:
class CreateVTable(generic.CreateView):
form_class = MyForm
model = Vtable