How to make a modelform editable foreign key field in a django template?

Vladimir

I have a company model:

class Company(models.Model):
    companyId = models.IntegerField(unique=True, blank = True, null = True )
    address = models.ForeignKey(Address, blank = True, null = True )
    ...

and address model:

class Address(models.Model):
    address1 = models.CharField (max_length=300, blank = True, null = True)
    ...

I need to create an editable form for a foreign key and this is my code:

class CompanyForm(forms.ModelForm):
    address = forms.CharField(label='Address', max_length=500, required=False)
    ...

The view for that form is

<div class="control-group">
    <label class="control-label" for="id_address">{{ form.address.label }}</label>
   <div class="controls">
            {{ form.instance.address.address1 }}
  </div>
</div>

The address and label is displayed but I cannot modify the field. What would be an approach to actually make the field editable? Any help is appreciated!

ndpu

To save data from string field to fk you need to override form save method. And you can set initial state to string address field in __init__ method:

class CompanyForm(forms.ModelForm):
    s_address = forms.CharField(label='Address', max_length=500, required=False)

    def __init__(self, *args, **kwargs):
        super(CompanyForm, self).__init__(*args, **kwargs)
        self.fields['s_address'].initial = self.instance.address.address1

    def save(self, commit=True):
        model = super(CompanyForm, self).save(commit=False)
        saddr = self.cleaned_data['s_address']
        if saddr:
            if model.address:
                model.address.address1 = saddr
                model.address.save()
            else:
                model.address = Address.objects.create(address1=saddr)
                # or you can try to look for appropriate address in Address table first
                # try:
                #     model.address = Address.objects.get(address1=saddr)
                # except Address.DoesNotExist:
                #     model.address = Address.objects.create(address1=saddr)

        if commit:
            model.save()

        return model

    class Meta:
        exclude = ('address',) # exclude form own address field

Template:

<div class="control-group">
    {{ form.s_address }}
</div>

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Dev

Validate multiple related objects through foreign key field in Django ModelForm

From Dev

How to Stop Django ModelForm From Creating Choices for a Foreign Key

From Dev

Django foreign key in template

From Dev

Displaying foreign key attributes in ModelForm Django

From Dev

Django ModelForm - Create instance with foreign key

From Dev

foreign key as initial value not passed to the ModelForm in django

From Dev

Displaying foreign key attributes in ModelForm Django

From Dev

Hyperlink to not editable foreign key filed in django admin

From Dev

How to make a field which will be foreign key and primary key at the same time

From Dev

How to make a field which will be foreign key and primary key at the same time

From Dev

Django - accessing modelform field value in template

From Dev

How to hide a field in django modelform?

From Dev

Updating foreign key field in Django

From Dev

Updating foreign key field in Django

From Dev

How to make ARRAY field with foreign key constraint in SQLAlchemy?

From Dev

Django ModelForm make field from other fields

From Dev

Modelform prepopulate foreign key

From Dev

How to set a ModelForm field not editable based on other object?

From Dev

How to get image connected by Foreign Key via Template in django

From Dev

Django Template: How to display the value of Foreign Key in a values_list

From Dev

Django how to customize table name and foreign key field

From Dev

How to Export Foreign Key Field to Excel In Django Views.py?

From Dev

How do I reference other FIELD using foreign key in Django?

From Dev

Make Foreign Key (string field) nullable

From Dev

How to make an xml field non editable in JAXB

From Dev

How to add a form as field attribute in a django ModelForm

From Dev

Display foreign key value in django template

From Dev

Use foreign key as variable in Django template

From Dev

django change something in template based on foreign key

Related Related

  1. 1

    Validate multiple related objects through foreign key field in Django ModelForm

  2. 2

    How to Stop Django ModelForm From Creating Choices for a Foreign Key

  3. 3

    Django foreign key in template

  4. 4

    Displaying foreign key attributes in ModelForm Django

  5. 5

    Django ModelForm - Create instance with foreign key

  6. 6

    foreign key as initial value not passed to the ModelForm in django

  7. 7

    Displaying foreign key attributes in ModelForm Django

  8. 8

    Hyperlink to not editable foreign key filed in django admin

  9. 9

    How to make a field which will be foreign key and primary key at the same time

  10. 10

    How to make a field which will be foreign key and primary key at the same time

  11. 11

    Django - accessing modelform field value in template

  12. 12

    How to hide a field in django modelform?

  13. 13

    Updating foreign key field in Django

  14. 14

    Updating foreign key field in Django

  15. 15

    How to make ARRAY field with foreign key constraint in SQLAlchemy?

  16. 16

    Django ModelForm make field from other fields

  17. 17

    Modelform prepopulate foreign key

  18. 18

    How to set a ModelForm field not editable based on other object?

  19. 19

    How to get image connected by Foreign Key via Template in django

  20. 20

    Django Template: How to display the value of Foreign Key in a values_list

  21. 21

    Django how to customize table name and foreign key field

  22. 22

    How to Export Foreign Key Field to Excel In Django Views.py?

  23. 23

    How do I reference other FIELD using foreign key in Django?

  24. 24

    Make Foreign Key (string field) nullable

  25. 25

    How to make an xml field non editable in JAXB

  26. 26

    How to add a form as field attribute in a django ModelForm

  27. 27

    Display foreign key value in django template

  28. 28

    Use foreign key as variable in Django template

  29. 29

    django change something in template based on foreign key

HotTag

Archive