1

models.py

class MyModel(models.Model):
    company = models.ForeignKey(Company, db_column="company", default=None, on_delete=models.DO_NOTHING, null=True)

forms.py

class myform(forms.ModelForm): 
       company = forms.CharField(label="company",
                              widget=forms.TextInput(attrs={'readonly':True}),
                              required=True)

admin.py

class MymodelAdmin(admin.ModelAdmin):
        def get_form(self, request, obj=None, **kwargs):
           url = request.get_full_path()
           if obj:
               self.form = MyModelUpdateForm
           else:
               self.form = MyModelCreateForm
           ModelForm = super(MyModeladmin, self).get_form(request, obj, **kwargs)

           class ModelFormMetaClass(ModelForm):
               def __new__(cls, *args, **kwargs):
                   kwargs['request'] = request
                return ModelForm(*args, **kwargs)

           return ModelFormMetaClass

ValueError: Cannot assign "'pgEmlMkkkCWnJ1I'": "Mymodel.company" must be a "Company" instance.

90's_jaddu
  • 53
  • 8
  • "'pgEmlMkkkCWnJ1I'" what is this value !? Is there other code handling this? – Alvi15 Nov 26 '20 at 10:27
  • it is actually looking for company instance to be saved while update but as i am making company as readonly field, it is getting the id('pgEmlMkkkCWnJ1I') of the company instead. – 90's_jaddu Nov 26 '20 at 10:34
  • If you have foreign key then you can't have Charfield in form. It must be foreign field. – rahul.m Nov 26 '20 at 10:35
  • and instance must be model object not string – rahul.m Nov 26 '20 at 10:35
  • you need `company__id=...` instead of `company=...` somewhere in your view. – Alvi15 Nov 26 '20 at 10:36
  • Yes i do agree but not sure how to apply readonly on foreign key fields while Updating the form. – 90's_jaddu Nov 26 '20 at 10:37
  • Have you tried modifying the `clean` method of the `company` field to return a `Company` instance? https://docs.djangoproject.com/en/3.2/ref/forms/validation/#cleaning-a-specific-field-attribute – Mugoma Apr 14 '21 at 08:24

0 Answers0