1

I have want to have an endpoint which is called by a third party which the parameter names they will use can't be changed. The submitted data contains parameters with the character . (e.g. hub.token) along with others.

I had wanted to create a Django form to validate the callback but how does one write a form class which will bind to the request. Without noticing the problem I tried hub.token which does not work as hub dictionary does not exist. I then tried hub_token in the hope Django would recognise the intent.

Having a period in the attribute is valid as in HTML form submission the name is taken the controls name attribute which can contain periods.

Is there an easy way to handle this situation without having to access each field in the view?


forms.py

from django import forms

class RegisterEndpointForm(forms.Form):
    hub.token = forms.CharField()

views.py

...
register_request = RegisterEndpointForm(request.GET)
if register_request.is_valid()
    pass
...

Community
  • 1
  • 1
Christopher Hackett
  • 5,547
  • 1
  • 27
  • 39

2 Answers2

0

I don't thin you can set attributes containing dots. You could try a couple things. You could set the field as hub_token, then replace the dot with an underscore in request.GET. for example:

data = request.GET
data['hub_token'] = data['hub.token'] 
del data['hub.token']
register_request = RegisterEndpointForm(data)
…

You could also try setting the field dynamically on form init. For example:

class RegisterEndpointForm(forms.Form):
    def __init__(self, *args, **kwargs):
        super(RegisterEndpointForm, self).__init__(*args, **kwargs)
        self.fields['hub.token'] = forms.CharField()
jproffitt
  • 5,677
  • 26
  • 41
  • Thanks, I think the from `__init__` option is best. I tried to avoid duplication the field names so have instead replaced all periods with underscores. – Christopher Hackett Sep 18 '13 at 09:13
0

I have used the __init__ method suggested by @jproffitt but replace all keys containing periods with underscores.

class RegisterEndpointForm(forms.Form):
    hub_verify_token = forms.CharField()
    [...]
    def __init__(self, *args, **kwargs):
        super(RegisterEndpointForm, self).__init__(*args, **kwargs)
        all_fields = self.data.copy()
        for key, value in all_fields.iteritems():
            safe_key = key.replace('.', '_')
            if safe_key != key:
                    self.data[safe_key] = value
Christopher Hackett
  • 5,547
  • 1
  • 27
  • 39