Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django modelform and passing extra parameter

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.

models.py

class SignUp(models.Model):
    ....
    ip = models.IPAddressField()

views.py

def my_view(request):
    form = SignUpForm(request.POST, ip_addr=get_client_ip(request))

forms.py

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
like image 279
Hellnar Avatar asked May 19 '26 10:05

Hellnar


1 Answers

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

like image 75
Timmy O'Mahony Avatar answered May 22 '26 01:05

Timmy O'Mahony



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!