Setting the initial value for a readonly Choice (ForeignKey) field

Related searches

I'm trying to make a CreateView have a readonly field with a set value, but I'm unable to make that work.

I have a model with a ForeignKey to another model:

class CompanyNote(TimeStampedModel):
    company = models.ForeignKey(Company)
    note = models.TextField(blank=True)

And I have a CreateView:

class CompanyNoteCreateView(CreateView):
    model = models.CompanyNote
    form_class = CompanyNoteForm

That uses a custom ModelForm:

class CompanyNoteForm(forms.ModelForm):

    company = forms.ChoiceField(
        widget=forms.widgets.Select(attrs={'readonly': 'readonly'}))

    class Meta:
        model = models.CompanyNote

As you see, the widget for the field in question is readonly. This is because I pick up the company as a part of the URL, as in company/1/note/add . I have no trouble picking up the "1" and finding the right company object, but I don't know how to set the readonly field.

I tried:

def get_initial(self):
    initial = super(CompanyNoteCreateView, self).get_initial()
    initial['company'] = self.get_company().id
    return initial

But that didn't work. The Widget is empty, which may be the problem. Perhaps I'm barking up the wrong tree here. Any ideas welcome.

Have you tried setting the attribute in the Form's Meta class?

I experienced an issue where Form attributes were not applied for Model Fields if set in the base class definition, but they worked correctly in the Meta class:

class CompanyNoteForm(forms.ModelForm):
    class Meta:
        model = models.CompanyNote
        widgets = {'company': forms.widgets.Select(attrs={'readonly': True,
                                                          'disabled': True})}

Otherwise check this answer out.

Worst case scenario, make company a hidden field?

Model field reference | Django documentation, I'm trying to make a CreateView have a readonly field with a set value, but I'm unable to make that work. I have a model with a ForeignKey to another model:� A foreign key is a key used to link two tables together. This is sometimes also called as a referencing key. A Foreign Key is a column or a combination of columns whose values match a Primary Key in a different table. The relationship between 2 tables matches the Primary Key in one of the tables with a Foreign Key in the second table.

Use a ModelChoiceField

class CompanyNoteForm(forms.ModelForm):
    company = forms.ModelChoiceField(queryset=models.Company.objects.all(), widget=forms.widgets.Select(attrs={'readonly': 'readonly'}))

Form fields | Django documentation, If choices are given, they're enforced by model validation and the default form widget will be a database table with a ForeignKey . choices is meant for static data that doesn't change much, if ever. Note The primary key field is read-only. So even if you set a value for this field when creating the object, it will be ignored. I have a form that is connected to a SharePoint list. One of the fields is a choice field. I would like to have a default value for that field. I can set a default for the field in SharePoint, but it does not carry over to the form. I don't see a way to set a default in PowerApps. Thanks in advance.

I could not find this answer anywhere, that I could actually get to work. But I found a different approach. Set the field to be hidden with forms.HiddenInput() widget. Then the value you pass in from the view will be assigned but the user cannot access it.

widgets = {'field_name': forms.HiddenInput()}

I'm using ModelForm class so my syntax might be different from yours.

Creating forms from models — Django 3.1 documentation, By default, each Field class assumes the value is required, so if you pass an empty Set the Form.use_required_attribute attribute to False to disable it. you must remember to pass in required=False when creating the BooleanField . Allows the selection of a single model object, suitable for representing a foreign key. For fields like ForeignKey that map to model instances, defaults should be the value of the field they reference (pk unless to_field is set) instead of model instances. The default value is used when new model instances are created and a value isn’t provided for the field.

In Django forms, how do I set a field to read-only (or disabled) so that, Each model field has a corresponding default form field. ForeignKey is represented by django.forms.ModelChoiceField , which is a ChoiceField whose choices are a model QuerySet . The blank choice will not be included if the model field has blank=False and an explicit default value (the default value will be initially� Versions: Python 3.7; Django 2.1; ManyToManyFields confuse a lot of people.The way you relate objects to each other using a many-to-many relationship is just different enough from dealing with ForeignKeys and just uncommon enough in day-to-day Django development that it's easy to forget all the little tricks for dealing with them.

When creating a new entry using a form, all fields should be enabled - however, some ForeignKey(User) class ItemForm(ModelForm): class Meta: model = Item This creates problems, such as the selection box can still be 2) The second method - resets the field to its initial value in the purge method:. The initial argument lets you specify the initial value to use when rendering this Field in an unbound Form. To specify dynamic initial data, see the Form.initial parameter. The use-case for this is when you want to display an “empty” form in which a field is initialized to a particular value.

I was not aware that making a field read-only would make the field visible to all recipients. The setting you mentioned is the one I was thinking of. If that setting is enabled, when you send an envelope with a tag that has an initial value, other recipients in the envelope should be able to see that value (whether the field is read-only or

  • Have you tried setting choices in your widget?
  • @drewman: As the choices are dynamic, that wouldn't work. But the solution to that is the ModelChoiceField mentioned by Nathaniel.
  • It also solves the initial value problem, and it's slightly "cleaner" than setting the form field, so this is a good solution. The widget is still not actually read only, so I still need a ReadOnlySelectWidget, and also to make the field read-only as per other questions and answers.
  • For a Select you need to set also the disabled attribute as specified in this answer
  • That works, in as much that I can now set the initial value. Funnily enough, it's not read_only though (neither in Firefox nor in Chrome). It looks readonly, and Firefox even shows a little "Not allowed" mouse pointer. But it's not readonly...
  • It might remove it altogether, but what if you add to class Meta: an exclude of exclude = ('company',) I'm not able to try this right now so it might remove the company altogether.
  • Weirdly enough that just moves the field to the bottom of the form. I think it gets added back since it's required. I'll probably override the SelectWidget to handle readonly more sensibly.