简体   繁体   中英

Why is my function returning the object identity instead of the 'ip' variable?

Upon saving User sign up form, I expect to save an ip address of the user, but my view function won't return a string . I get the object identity of the get_client_signup_ip function instead:

<function get_client_signup_ip at 0x04461810>

forms.py:

    from django import forms
from captcha.fields import ReCaptchaField

from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm

from django.http import HttpRequest

from django.contrib.gis.geoip2 import GeoIP2

from . import views

from .models import CustomUser

class UserCreateForm(UserCreationForm):
    email = forms.EmailField(required=True)
    captcha = ReCaptchaField()

    class Meta:
        model = CustomUser # this makes the UserCreateForm always save data to the custom user model
        fields = ("username", "email", "password1", "password2")


    def save(self, commit=True, request=True): # user object (customuser) form is called to save with commit=true, so it gets teh ip and saves.
        user = super(UserCreateForm, self).save(commit=False)
        user.email = self.cleaned_data["email"]
        user.origin_ip = views.get_client_signup_ip(request)
        if commit:
            user.save()
        return user

views.py

def get_client_signup_ip(request):
    g = GeoIP2()
    x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
    if x_forwarded_for:
        ip = x_forwarded_for
        ip2 = '192.227.139.106'
        city = g.city(ip2)
    else:
        ip = request.META.get('REMOTE_ADDR')
        ip2 = '192.227.139.106'
        city = g.city(ip2)

    return ip

urls.py

from django.urls import path

from . import views

urlpatterns = [
    path('signup/', views.SignUp.as_view(), name='signup'),
    path('signup/', views.get_client_ip, name='signup_ipaddress')

]

I expect to see an ip address in the User's origin_ip field. Instead I get an string representation for the get_client_sign_up function.

How can I get my view function get_client_sign_ip to return a string?

To get the value you need to call it as method views.get_client_signup_ip() instead of views.get_client_signup_ip .

user.origin_ip = views.get_client_signup_ip(request)

Also, for simply getting ip from a function you don't need the HttpResponse(ip) from a method.

def get_client_signup_ip(request):
    ..........

    return ip

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM