1

I have a simple problem with ModelChoiceField , I have a Classification class with four fields (name, price1, price2, price3) , I added an edit button and its working perfectly , i added the name on edit page as a ModelChoiceField , My problem is that am trying to force select the name value when edited so the user will only be able to change prices values .

I read the doc about ModelForm which led me to this https://docs.djangoproject.com/en/2.2/ref/forms/api/#django.forms.Form.initial

I tried initial= but it did not worked as i though it would. Any idea of either dynamically select the value or just print the name without allowing the user to change it would be great .

here is my code , views.py

def edit_class(request, name):
    classifications = Classification.objects.all()
    devices = Devices.objects.all()
    inst = Classification.objects.get(name=name)
    if request.method == 'POST':
        classification = EditClassForm(request.POST, instance=inst)
        if classification.is_valid():
            classification.save()
            return redirect("/classifications.html")

    else:
        classification = EditClassForm()
    return render(request, 'classifications.html',
                  {"form": classification, "classifications": classifications, "devices": devices})

forms.py

class EditClassForm(forms.ModelForm):
    class Meta(object):
        model = Classification
        fields = ("name", "price1", "price2", "price3")

    def __init__(self, *args, **kwargs):
        super(EditClassForm, self).__init__(*args, **kwargs)
        self.fields['name'] = forms.ModelChoiceField(queryset=Classification.objects.all(), initial=0)
        self.fields['name'].widget.attrs.update({'class': "form-control"})
        self.fields['price1'].widget.attrs.update({'class': "form-control", 'value': 0})
        self.fields['price2'].widget.attrs.update({'class': "form-control", 'value': 0})
        self.fields['price3'].widget.attrs.update({'class': "form-control", 'value': 0})

urls.py

urlpatterns = [url(r'^editclass/(?P<name>\d*\S*)/$', views.edit_class, name='edit_class'),]

in template am using only {{form.name}} .

George
  • 2,292
  • 2
  • 10
  • 21

0 Answers0