Hi all,
I want to add an entry to a Model by using a CreateView, but would like to specify one single formfield by the class based view and not by the user.
Here is my approach where the user specifies the field “my_foreign_key” which works fine. (I simplified the code for making it easier to read.)
MyModel:
class MyModel(models.Model):
field1 = models.CharField('Field1', max_length=200, unique=True)
field2 = models.CharField('Field2', max_length=200, unique=True)
my_foreign_key = models.ForeignKey(SomeOtherModel, on_delete=models.CASCADE)
CreateView:
class CreateCampaign(generic.CreateView):
model = MyModel
template_name = "...PATH..."
form_class = MyModelForm
success_url = '...PATH...'
MyFormView
class MyModelForm(ModelForm):
class Meta:
model = MyModel
fields = ["field1", "field2", "my_foreign_key"]
@property
def helper(self):
helper = FormHelper()
helper.layout = Layout(
Field('field1'),
Field('field2'),
Field('my_foreign_key'),
)
return helper
This works fine. But now I would like to set the “my_foreign_key” formfield by the CreateView, for putting in a variable instead of some user input. Reading through the documentation, this thread[1] and the specifications of the CreateView[2], I assume that the “get_form_kwargs” function is what I am looking for.
But changing the code doesn’t really work for me:
The updated CreateView:
CreateView:
class CreateCampaign(generic.CreateView):
model = MyModel
template_name = '...PATH...'
form_class = MyModelForm
success_url = '...PATH...'
def get_form_kwargs(self):
kwargs = super().get_form_kwargs()
kwargs['my_foreign_key'] = 42
return kwargs
class Meta:
model = MyModel
fields = ["field1", "field2", "my_foreign_key"]
Updated MyFormView
class MyModelForm(ModelForm):
def __init__(self, *args, **kwargs):
self.my_foreign_key = kwargs.pop('my_foreign_key', None)
super().__init__(*args, **kwargs)
...
When I delete the “my_foreign_key” formfield from MyModelForm, I receive the following error:
django.db.utils.IntegrityError: NOT NULL constraint failed: myapp.my_foreign_key
Playing around for ~2 hours, I either get this error, or, if I don’t delete the “my_foreign_key” from the “fields” list in “class Meta”, I receive an invalid form.
So I’m interesed if my approach is going into the right direction.
BR
[1] altering queryset in a field of generic CreateView form - #5 by KenWhitesell
[2] CreateView -- Classy CBV