问题
I have a Django application and I wanna create an update form with ModelForm but I have to get the fields
parameter from user_profile
model. So I have created my form and view such as below.
forms.py;
class UpdateForm(forms.ModelForm):
class Meta:
model = Data
fields = []
def __init__(self, *args, **kwargs):
input_choices = kwargs.pop('input_choices')
super(UpdateForm, self).__init__(*args,**kwargs)
self.fields = input_choices
views.py;
@login_required(login_url = "user:login")
def updateData(request,id):
features = request.user.profile.selected_features
instance = get_object_or_404(Data,id = id)
form = UpdateForm(request.POST or None, input_choices=features, instance=instance)
if form.is_valid():
data = form.save(commit=False)
data.author = request.user
data.save()
return redirect("data:dashboard")
return render(request,"update.html",{"form":form})
However, I'm getting a list indices must be integers or slices, not str
error in the return render(request,"update.html",{"form":form})
line. There is an issue with the fields
parameter but I couldn't find anything.
How can I pass the fields
parameter from view to ModelForm?
回答1:
You can use modelform_factory to create a form with dynamic fields
from django.forms import modelform_factory
@login_required(login_url = "user:login")
def updateData(request,id):
features = request.user.profile.selected_features
instance = get_object_or_404(Data, id=id)
UpdateForm = modelform_factory(Data, fields=features)
form = UpdateForm(request.POST or None, instance=instance)
If features
is a queryset, you'll probably have to use something like features.values_list('name', flat=True)
to get just the names of the fields
来源:https://stackoverflow.com/questions/62870567/creating-updateform-by-using-modelform-in-django