How to use GenericIPAddressField ?

GenericIPAddressField is used for input of IP address in the database. One can input User IP address, IPv4, etc. Till now we have discussed how to implement GenericIPAddressField but how to use it in the view for performing the logical part. To perform some logic we would need to get the value entered into the field into a python string instance. To get GitHub code of working GenericIPAddressField, click here In views.py, 

Python3




from django.shortcuts import render
from .forms import GeeksForm
 
# Create your views here.
def home_view(request):
    context = {}
    form = GeeksForm(request.POST or None)
    context['form']= form
    if request.POST:
        if form.is_valid():
            temp = form.cleaned_data.get("geeks_field")
            print(type(temp))
    return render(request, "home.html", context)


Now let’s try entering some other data into the field.

 

You can clearly see it is asking for entering a valid IP address. Let’s try entering valid IP address now.

  

Now this data can be fetched using corresponding request dictionary. If method is GET, data would be available in request.GET and if post, request.POST correspondingly. In above example we have the value in temp which we can use for any purpose. You can check that data is converted to a python string instance in geeks_field. 

GenericIPAddressField – Django Forms

GenericIPAddressField in Django Forms is a text field, for input of IP Addresses. It is field containing either an IPv4 or an IPv6 address. The default widget for this input is TextInput. It normalizes to a Python string. It validates that the given value is a valid IP address. 

GenericIPAddressField takes following optional arguments:

  • protocol :- Limits valid inputs to the specified protocol. Accepted values are both (default), IPv4 or IPv6. Matching is case insensitive.
  • unpack_ipv4 :- Unpacks IPv4 mapped addresses like ::ffff:192.0.2.1. If this option is enabled that address would be unpacked to 192.0.2.1. Default is disabled. Can only be used when protocol is set to ‘both’.

Syntax

field_name = forms.GenericIPAddressField(**options)

Similar Reads

Django form GenericIPAddressField Explanation

Illustration of GenericIPAddressField using an Example. Consider a project named geeksforgeeks having an app named geeks....

How to use GenericIPAddressField ?

...

Core Field Arguments

...

Contact Us