How to disable a field in an UpdateView

I have a model called Stuff:

# models.py
class Stuff(models.Model):
    owner = models.ForeignKey(...)
    ... some other fields ...

I intend to use an UpdateView to let owners edit their stuff:

# views.py
class StuffUpdateView(UpdateView):
    model = Stuff
    fields = '__all__'
    template_name_suffix = "_update"

Is there a way to set owner.disabled=True from the view?

For the context, I started with the design below, which works but is not as robust and django-nic as the UpdateView.

# models.py
class StuffForm(ModelForm):
    class Meta:
        model = Stuff
        fields = "__all__"
# views.py
def update(request, pk):
    stuff, created = Stuff.objects.get_or_create(pk=pk)
    if created:
        stuff.save()
    form = StuffForm(instance=stuff)
    form.fields.get('owner').disabled = True
    return render(request, 'some_template.html', {'form': form})

First,

This isn’t necessary at all. The get_or_create saves the newly-created stuff in the database. You can safely remove those two lines.

But no, there is absolutely nothing wrong with how you’re disabling the field.

As a matter of style, I would probably write form.fields['owner'].disabled = True because if that field didn’t exist you’d get an error anyway.

Thanks Ken.

I removed the calls to save() after get_or_create(...).

Regarding the use of UpdateView, I ended up with the following solution:

# views.py
class StuffUpdateView(UpdateView):
    model = Stuff
    form_class = StuffForm
    form_class.base_fields['owner'].disabled = True
    template_name_suffix = "_update"

I find it a bit awkward to declare and use a StuffForm only to disable one field, but at least it works.

If that field is always going to be disabled in that form, you can define it as disabled within the form. That would be a lot cleaner than what you have here.

(The docs already warn you about changing the base_fields attribute, and putting any type of code like that at the class level is a general anti-pattern.)