如何在django中获取用户的IP?
我有这样的观点:
# Create your views
from django.contrib.gis.utils import GeoIP
from django.template import RequestContext
from django.shortcuts import render_to_response
def home(request):
g = GeoIP()
client_ip = request.META['REMOTE_ADDR']
lat,long = g.lat_lon(client_ip)
return render_to_response('home_page_tmp.html',locals())
Run Code Online (Sandbox Code Playgroud)
但我得到这个错误:
KeyError at /mypage/
'REMOTE_ADDR'
Request Method: GET
Request URL: http://mywebsite.com/mypage/
Django Version: 1.2.4
Exception Type: KeyError
Exception Value:
'REMOTE_ADDR'
Exception Location: /mysite/homepage/views.py in home, line 9
Python Executable: /usr/bin/python
Python Version: 2.6.6
Python Path: ['/mysite', '/usr/local/lib/python2.6/dist-packages/flup-1.0.2-py2.6.egg', '/usr/lib/python2.6', '/usr/lib/python2.6/plat-linux2', '/usr/lib/python2.6/lib-tk', '/usr/lib/python2.6/lib-old', '/usr/lib/python2.6/lib-dynload', '/usr/local/lib/python2.6/dist-packages', '/usr/lib/python2.6/dist-packages', '/usr/lib/pymodules/python2.6']
Server time: Sun, 2 …Run Code Online (Sandbox Code Playgroud) 我试图在Django中以原子方式递增一个简单的计数器.我的代码看起来像这样:
from models import Counter
from django.db import transaction
@transaction.commit_on_success
def increment_counter(name):
counter = Counter.objects.get_or_create(name = name)[0]
counter.count += 1
counter.save()
Run Code Online (Sandbox Code Playgroud)
如果我正确理解Django,这应该将函数包装在事务中并使增量原子化.但它不起作用,并且在计数器更新中存在竞争条件.如何使这些代码成为线程安全的?
什么是@property在Django?
这是我的理解:@property是一个类中方法的装饰器,用于获取方法中的值。
但是,据我所知,我可以像平常一样调用该方法,它就会得到它。所以我不确定它到底是做什么的。
文档中的示例:
from django.db import models
class Person(models.Model):
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
birth_date = models.DateField()
def baby_boomer_status(self):
"Returns the person's baby-boomer status."
import datetime
if self.birth_date < datetime.date(1945, 8, 1):
return "Pre-boomer"
elif self.birth_date < datetime.date(1965, 1, 1):
return "Baby boomer"
else:
return "Post-boomer"
@property
def full_name(self):
"Returns the person's full name."
return '%s %s' % (self.first_name, self.last_name)
Run Code Online (Sandbox Code Playgroud)
如果存在与不存在有什么区别?
有一个让我感到烦恼的问题,我想做的就是当我请求detail.html时,Post模型的视图将在访问计数中加1,该怎么做?谢谢。
博客/models.py
class Post(models.Model):
views = models.PositiveIntegerField(default=0)
Run Code Online (Sandbox Code Playgroud)
博客/views.py
def detail(request):
return render(request, 'blog/detail.html')
Run Code Online (Sandbox Code Playgroud)