Home > Mobile >  How to send values from Django views function to Django forms class during runtime?
How to send values from Django views function to Django forms class during runtime?

Time:05-29

My Django Template:

{% extends 'main/base.html' %}
{%block title%}Delete List{%endblock%}

{%block content%}
    <form method="post" action="/delete/">
        {%csrf_token%}
        {{form}}
        <button type="sumbit" name="Delete List">Delete List</button>
    </form>
{%endblock%}

my function inside view:

def delete(response):
    if response.method=="POST":
        form1 = DeleteList(response.POST)
        print(f"delete button pressed: {form1.is_valid()}")#just checking
        if form1.is_valid():
            ""
            print("valid form: {}".format(form1.cleaned_data))#just checking
            return HttpResponseRedirect("/display")
    else:
        #form1 = DeleteList(10) -- iam trying to make this style work...and use a integer value from my database to set maxVaue of a field
        #Example: form1 = DeleteList(name="test",data2="somedata"...) -- i want this style to work cause I would pass more values to my forms class in future 
        form1 = DeleteList()
    return render(response,"main/deleteList.html",{"form":form1})

my django forms class:

class DeleteList(forms.Form):
    #i was trying to make this __init__ work but seems to be buggy
    """def __init__(self,maxValue:int, *args, **kwargs):
        super(DeleteList, self).__init__(*args, **kwargs)
        self.fields['id'] = forms.IntegerField(label="Enter id",min_value=1,max_value=maxValue)
    id = forms.IntegerField()"""    
    
    #below one is just static, iam trying to replace this with the above commented block of code
    id=forms.IntegerField(label="Enter id",min_value=1,max_value=10) #-- only this seems to work

Now if do form1 = DeleteList(<int value here>) and receive it on __init__ of forms class, I am able to get the values into form and set my IntegerField's max_value, it only seems to work when the form loads the first time, then when the form is submitted and while receiving the post data on my views function(DeleteList): form1.is_valid() is always false.

So how do i set my forms IntegerField's max_value from my django views function and still be able to receive my post method data back to the same view function and have form1.is_valid() return ture to continue with the form flow?

EDIT: and this https://docs.djangoproject.com/en/4.0/ref/forms/api/#django.forms.Form.initial does not help either, this does not seems to work for properties of the elements like IntegerField's max_value

CodePudding user response:

You need to pass the value down as a kwarg and remove it before sending down to Form Base class. Follow the example:

class DeleteList(forms.Form):
    def __init__(self, *args, **kwargs):
        caller = kwargs.pop('maxValue')
        # YOUR DESIRED LOGIC
        super(DeleteList, self).__init__(*args, **kwargs)

CodePudding user response:

I found a working solution, I just added my integer-i-want-to-use to the post method too and it all works fine

my django forms class is:

class DeleteList(forms.Form):
    def __init__(self,maxValue:int, *args, **kwargs):
        super(DeleteList, self).__init__(*args, **kwargs)
        self.fields['id'] = forms.IntegerField(label="Enter id",min_value=1,max_value=maxValue)
    id = forms.IntegerField()  

my Django views function:

def delete(response):
    if response.method=="POST":
        form1 = DeleteList(10,response.POST)#early this was just form1 = DeleteList(response.POST)
        print(f"delete button pressed: {form1.is_valid()}")#just checking
        if form1.is_valid():
            ""
            print("valid form: {}".format(form1.cleaned_data))#just checking
            return HttpResponseRedirect("/display")
    else:
        form1 = DeleteList(10)
    return render(response,"main/deleteList.html",{"form":form1})

so in POST doing this form1 = DeleteList(10,response.POST) seems to solve this problem for me

is this the best way to send data from view function to forms class?

from what i can read in the documentation , it points to this : https://docs.djangoproject.com/en/4.0/ref/forms/api/#django.forms.Form.initial , but this does not seem to work for changing IntegerField's max_value and it works for changing <any fields>'s value

it would be great If anyone can clarify on why Form.initial(mentioned on the documentation link) is not working for my case and is the method I am using the only way to set IntegerField's max_value ?

  • Related