Cannot implement anything within def __init__ of any modelform

Hi

I am facing up with a problem about how to implement any code in def init(self, *args, **kwargs): within my class inherited from forms.ModelForm class.

It seems that this method wasn’t overridden from my code at all, as a result, I cannot do something within this method on form.py. conversely, I do like that within a method on view.py file

I prefer doing in def init rather than function in view.py

The figure is shown my result
On the left-hand side, the field has been initialized within modelform class,the right-hand side has set within view.py instead.
Noticeable point is that I have passed an initial value through form=InventoryForm(initial={‘project’: project_obj}) as well.
so I don’t sure whether or not that thing cause any code within__init__ mehtod didn’t work.
please closely pay attention to my initial value form.fields[‘serial_no’].initial = "aaaa"
How to fix this issue

These are my code
model.py

class Inventory(models.Model):
#company=models.ForeignKey(Company,on_delete=models.CASCADE)
project=models.ForeignKey( Project,on_delete=models.CASCADE,verbose_name="Project")

serial_no=models.CharField("Serial Number",max_length=100,unique=True)

product_type=models.ForeignKey( Product_Type,on_delete=models.CASCADE,verbose_name="Product Type")
brand=models.ForeignKey( Brand,on_delete=models.CASCADE,verbose_name="Brand")
model = models.ForeignKey( Model, on_delete=models.CASCADE,verbose_name="Model")
partner = models.ForeignKey(Partner, on_delete=models.CASCADE, null=True, blank=True,verbose_name="Partner")

datacenter=models.ForeignKey(DataCenter, on_delete=models.CASCADE,null=True, blank=True,verbose_name="DataCenter")
branch=models.ForeignKey(Branch, on_delete=models.CASCADE,null=True, blank=True,verbose_name="Branch")
customer_support = models.ManyToManyField(Customer, related_name='customer_support',verbose_name="List Customer Support")


function=models.ForeignKey(Function, on_delete=models.CASCADE,null=True, blank=True,verbose_name="Function")

customer_warranty_start=models.DateField("Customer Warranty Start", null=True, blank=True)
customer_warranty_end = models.DateField("Customer Warranty End ",null=True, blank=True)
customer_sla = models.ForeignKey(SLA, on_delete=models.CASCADE,related_name='customer_sla',null=True, blank=True,verbose_name="Customer-SLA")

yit_warranty_start = models.DateField("Yit Warranty Start",null=True, blank=True)
yit_warranty_end = models.DateField("Yit Warranty End",null=True, blank=True)
yit_sla = models.ForeignKey(SLA, on_delete=models.CASCADE, related_name='yit_sla', null=True, blank=True,verbose_name="Yit-SLA")

product_warranty_start = models.DateField('Product Warranty Start',null=True, blank=True)
product_warranty_end = models.DateField("Product Warranty End",null=True, blank=True)
product_sla = models.ForeignKey(SLA, on_delete=models.CASCADE, related_name='product_sla', null=True, blank=True,verbose_name="Product-SLA")

cm_serviceteam = models.ForeignKey(ServiceTeam, on_delete=models.CASCADE, related_name='cm_serviceteam',verbose_name="CM-Team")
pm_serviceteam=models.ForeignKey(ServiceTeam, on_delete=models.CASCADE, related_name='pm_serviceteam',verbose_name="PM-Team")

remark=models.TextField("Remark/Note" ,null=True, blank=True,help_text="Other about VMWare_OEM_SAID,Express_Service_Code,Chassis_Serial_No,Used,Machine_Type")

is_active=models.BooleanField(default=True)

devicename_hostname=models.CharField("Device/Host Name",max_length=100,null=True, blank=True)

def __str__(self):
    return f'{self.serial_no}-{self.model.model_name}-{self.branch.branch_name}'

view.py

def add_inventory(request,proj_id):

project_obj=get_object_or_404(Project, pk=proj_id)
list_inventory = Inventory.objects.filter(project_id=proj_id)

if( request.method =="GET"):
   form = InventoryForm(initial={'project': project_obj})
   form.fields['serial_no'].initial = "aaaa"

else: # Post Data after submit
   form = InventoryForm(request.POST)
   if form.is_valid():
       form.save()
       messages.success(request, 'Inventory hase bee created successfully.')
   else:
       messages.error(request,form.errors)

context={'form':form,'project': project_obj}
return render(request, 'app/inventory_add.html', context)

form.py

class InventoryForm(forms.ModelForm):
class Meta:
    model=Inventory
    fields= '__all__'
    def __init__(self, *args, **kwargs):
        super(InventoryForm, self).__init__(*args, **kwargs)
        self.fields['serial_no'].initial = "aaa"

Many thanks.
Pongthorn

Just a couple side comments while I think about how to answer your questions.

When you’re posting multiple lines of code, please enclose the code between lines consisting of only three backtick - ` characters. This means you’ll have a line of only ```, followed by your code, followed by another line of ```.
(You could go back and edit this post to do that with your fragments above. Part of the reason I’m asking for this is that in code above, the forum software has “outdented” your field definitions in your model, making it look invalid. Since Python is white-space sensitive, making sure the formatting is correct is an issue.)

If you have a code fragment that you’re including in line in your post, enclose it within single backticks - `. This keeps the code from being interpreted by the forum software as special formatting.

Also, please don’t post screen captures of text, they’re not readable on a lot of devices.

Now, having said all the above, I’m going to say that the issue here is that your code is working, you’re just overriding it. You are defining the form with the initial value of the field in the form definition, but you’re binding the form to the project_obj, which is going to override the initial attribute.

From the docs for initial: These values are only displayed for unbound forms, and they’re not used as fallback values if a particular value isn’t provided.

Ken

The issue was already fixed.
I have something wrong in model.py and I fixed.

Thank you for your recommendation about form initial as your link reference.