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.)
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)
class CreateCampaign(generic.CreateView): model = MyModel template_name = "...PATH..." form_class = MyModelForm success_url = '...PATH...'
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 and the specifications of the CreateView, 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:
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"]
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.