[英]Record IP Address with Form Submission Django
我正在尝试使用django-ipware
记录通过 Django 提交表单的某人的 IP 地址。
该表单是一个 ModelForm。 这是 model:
# models.py
from django.db import models
class Upload(models.Model):
email = models.EmailField()
title = models.CharField(max_length=100)
language = models.ForeignKey('about.channel', on_delete=models.CASCADE, default='Other')
date = models.DateField(auto_now_add=True)
file = models.FileField()
ip_address = models.GenericIPAddressField()
这是表格:
# forms.py
class UploadForm(forms.ModelForm):
class Meta:
model = Upload
fields = ['email', 'title', 'language', 'file']
labels = {
'email': 'E-Mail',
'title': 'Video Title',
'file': 'Attach File'
}
获取 IP 地址的业务逻辑非常简单,但我尝试将其放置在不同的位置,但没有成功。 我应该将逻辑放在哪里,以便与其他表单数据一起提交?
# views.py
from ipware.ip import get_real_ip
ip = get_real_ip(request)
我在基于 function 的视图中做到了这一点。 我有一个名为submit_happiness
的视图 function ,它提交了一个名为Survey_Form
的表单。 在提交表单之前,我的submit_happiness
视图获取 IP 并将该字段添加到表单中。 该表格提交给我的Rating
model。 我的Rating
model 有一个名为ip
的字段。
我的 submit_happiness 视图 function 在这里。
def submit_happiness(request):
form = Survey_Form(request.POST or None)
ip = str(get_client_ip(request)) # I got the IP here!!!!!!!!!!
saved_ip_query = Rating.objects.filter(ip=ip)
message = False
if saved_ip_query:
message = ('I already have a survey from IP address '
f'{ip}. You might have submitted a survey.')
if form.is_valid():
new_rating = form.save(commit=False)
new_rating.ip = ip
form.save()
form = Survey_Form() # clears the user's form input
context = {
'form': form, 'message': message
}
return render(request, "ratings/submit_happiness.html", context)
根据上面@David Smolinksi 的建议,我是这样解决这个问题的:
#view.py
def upload(request):
ip = str(get_real_ip(request)) # Retrieve user IP here
if request.method == 'POST':
form = UploadForm(request.POST, request.FILES)
if form.is_valid():
new_upload = form.save(commit=False) # save the form data entered on website by user without committing it to the database
new_upload.ip_address = ip # add the ip_address requested above to all the other form entries as they map to the model
new_upload.save() # save the completed form
return redirect('upload')
else:
form = UploadForm()
context = {
'form': form
}
return render(request, 'content/upload.html', context)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.