Django : Get current url when init a widget in for

2019-03-04 03:47发布

问题:

I want to get the current url when I init my form to found within it a string I want to check. Depending on this string, I want to change the data I put in a radioselect widget. I would like to display different radioselect choices depending on the url.

class FunctionForm(forms.ModelForm):

def __init__(self, *args, **kwargs):

    # get url
    url=request.get_full_path
    # treat url
    string = treat_url(url)

    if (string=='ATC'):
        self.fields['function_name'].queryset= FUNCTION_ATC_CHOICES
    if (string=='ATS'):
        self.fields['function_name'].queryset= FUNCTION_ATS_CHOICES

    super(FunctionForm,self).__init__(*args,**kwargs)
    #function_name = forms.ChoiceField(widget=RadioSelect,choices=FUNCTION_ATC_CHOICES) 

class Meta :
    model = Function
    exclude =('session_number')

My view :

def add_function (request)
if request.method == 'POST': # If the form has been submitted...
    function_form = FunctionForm(request.get_full_path,request.POST)

回答1:

You just have to pass in the request object as a kwarg when you instantiate the form.