Reputation: 64793
I want to populate my modelform to include the IP address, however I'm not able to set the ip as I want, it simply returns "This field is required" for IP address.
class SignUp(models.Model):
....
ip = models.IPAddressField()
def my_view(request):
form = SignUpForm(request.POST, ip_addr=get_client_ip(request))
class SignUpForm(ModelForm):
class Meta:
model = SignUp
def __init__(self, *args, **kwargs):
self.ip_addr = kwargs.pop('ip_addr', None)
super(SignUpForm, self).__init__(*args, **kwargs)
def clean_ip(self):
return self.ip_addr
Upvotes: 3
Views: 4331
Reputation: 31951
I don't think you should use clean_ip
here. You are not cleaning it anyhow. Either use initial in your view or override save
method.
Upvotes: 0
Reputation: 53981
You haven't actually set an initial value for the ip form field meaning it's empty. Try:
def __init__(self, *args, **kwargs):
super(SignUpForm, self).__init__(*args, **kwargs)
self.fields['ip'].initial = kwargs.pop('ip_addr', None)
The clean_ip
method is for validation upon submission of the form and is only called after form.is_valid()
is called. It should check that the value of the field is a valid ip
Upvotes: 4