Answer the question
In order to leave comments, you need to log in
Assigning a value to a Django form field in a view?
There is a page with a table that contains database objects. I want to make it so that when you click on a record in this table, a new window opens with a form for editing this database object. I set everything up except for displaying the existing form fields. The fact is that the form is displayed empty, and in it (logically) there should be already filled fields in order to see what you are editing. Tell me how best to pass the value from the object to the form field. I tried to create a form in the view and pass an object to it as an instance, but for some reason only text fields are pulled up.
views.py
@login_required
def EditProjectView(request):
obj = Project.objects.get(id=request.GET.get('objId'))
form = EditProjectForm(instance=obj, objId=obj.id)
return render(request, 'editProject.html', {
'form': form
})
class EditProjectForm(forms.ModelForm):
class Meta:
model = Project
fields = [
'name',
'number',
'idKontr',
'idTip',
'idStatus',
'idKv',
'description'
]
widgets = {
'idKontr': forms.Select(attrs={
'class': 'form-control'
}),
'idTip': forms.Select(attrs={
'class': 'form-control'
}),
'idStatus': forms.Select(attrs={
'class': 'form-control'
}),
'idKv': forms.Select(attrs={
'class': 'form-control'
}),
}
objId = forms.IntegerField()
def __init__(self, *args, **kwargs):
super(EditProjectForm, self).__init__(*args, **kwargs)
self.fields['objId'].widget = forms.NumberInput(attrs={'class': 'd-none', 'id': 'edit_id_field'})
self.fields['name'].widget = forms.TextInput(attrs={'class': 'form-control'})
self.fields['description'].widget = forms.Textarea(attrs={'class': 'form-control'})
self.fields['name'].required = False
self.fields['number'].required = False
self.fields['idKontr'].required = False
self.fields['idTip'].required = False
self.fields['idStatus'].required = False
self.fields['idKv'].required = False
self.fields['description'].required = False
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question