开启代码之旅 Launch With Code
1404 浏览 6 years, 1 month
9 Get User IP Address from Requests
版权声明: 转载请注明出处 http://www.codingsoho.com/获取ip包括以下几个步骤
- Join添加ip字段
- 更新join form的显示,ip这个字段并不开放给用户
- 从request.META.get里获取ip
- 在form处理时把这个ip存进join
https://github.com/codingforentrepreneurs/Guides/blob/master/all/using_south_in_django.md
views.py
def get_ip(request):
try:
x_forward = request.META.get("HTTP_X_FORWORDED_FOR")
if x_forward:
ip = x_forward.split(',')[0]
else:
ip = request.META.get("REMOTE_ADDR")
except:
ip = ""
return ip
def home(request):
'''
form = EmailForm(request.POST or None)
if form.is_valid():
email = form.cleaned_data['email']
new_join, created = Joins.objects.get_or_create(email=email)
print new_join, created
'''
form = JoinForm(request.POST or None)
if form.is_valid():
new_join = form.save(commit = False)
email = form.cleaned_data['email']
new_join_old, created = Join.objects.get_or_create(email = email)
if created:
new_join_old.ip_address = get_ip(request)
new_join_old.save()
context = {"form":form}
template = "home.html"
return render(request, template, context)
class Join(models.Model):
email = models.EmailField(unique = True)
ip_address = models.CharField(max_length = 120, default = 'ABC')
timestamp = models.DateTimeField(auto_now_add = True, auto_now = False)
updated = models.DateTimeField(auto_now_add = False, auto_now = True)
def __unicode__(self):
return "%s " %(self.email)
class JoinForm(forms.ModelForm):
class Meta:
model = Join
fields = ['email',]
只显示email