我正在尝试从Django网站上的外部域捕获跟踪信息。外部域上的客户端加载了一个js片段:
(function() {
var img = new Image,
url = encodeURIComponent(document.location.href),
title = encodeURIComponent(document.title),
ref = encodeURIComponent(document.referrer);
img.src = '%s/track.gif?url=' + url + '&t=' + title + '&ref=' + ref;
})();
这会在/track.gif上创建一个图像获取请求回到我的服务器。如何让我的TrackView将get请求视为POST请求并将参数输入我的数据库?
其他信息
urls.py
urlpatterns = patterns('',
url(r'^browse_event$', BrowseEventView.as_view(), name='browse_event'),
url(r'^cart_event$', CartEventView.as_view(), name='cart_event'),
url(r'^product_view$', ProductView.as_view(), name='product_view'),
url(r'^track.gif$', TrackView.as_view(), name='track_view'),
)
models.py
class Track(CommonDateTime, models.Model):
domain = models.CharField(max_length=50)
url_name = models.CharField(max_length=200)
title = models.CharField(max_length=200)
ip = models.CharField(max_length=200)
referrer = models.CharField(max_length=200)
class Meta:
db_table = 'track_test'
verbose_name = 'Tracking pixel test'
verbose_name_plural = 'Tracking pixel tests'
forms.py
class TrackForm(forms.Form):
domain = forms.CharField()
url_name = forms.CharField()
title = forms.CharField()
ip = forms.CharField()
referrer = forms.CharFeld()
views.py
class TrackView(FormView):
form_class = TrackForm
success_url = '/'
def form_valid(self, form):
try:
track = Track.objects.get(domain = form.cleaned_data['domain'])
track.url_name = form.cleaned_data['url']
track.title = form.cleaned_data['title']
track.ip = form.cleaned_data['ip']
track.referrer = form.cleaned_data['referrer']
track.save()
except Track.DoesNotExist:
track = Track(
domain = form.cleaned_data['domain']
url_name = form.cleaned_data['url']
title = form.cleaned_data['title']
ip = form.cleaned_data['ip']
referrer = form.cleaned_data['referrer']
)
track.save()
return super(TrackView, self).form_valid(form)
答案 0 :(得分:1)
为什么需要POST请求? 只需使用简单的get() - 类函数视图实现GET请求。
您可以直接使用check query request.GET,或者如果您想使用表单,您可以使用request.GET作为参数来实例化它,但是恕我直言,没有真正的原因。
你可以这样做:
class TrackView(View):
def get(self, request):
try:
track,_ = Track.objects.get_or_create(domain = request.GET['domain'])
track.url_name = request.GET['url']
track.title = request.GET['title']
track.ip = request.GET['ip']
track.referrer = request.GET['referrer']
track.save()
return HttpResponse(status=200)
except KeyError:
return HttpResponse(status=400)