【问题标题】:Record IP Address with Form Submission Django使用表单提交 Django 记录 IP 地址
【发布时间】:2025-12-03 23:10:01
【问题描述】:

我正在尝试使用django-ipware pacakge 记录通过 Django 提交表单的某人的 IP 地址。

表单是一个模型表单。这是模型:

# 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)

【问题讨论】:

    标签: python django python-3.x django-forms


    【解决方案1】:

    我是在基于函数的视图中做到这一点的。我有一个名为submit_happiness 的视图函数,它提交一个名为Survey_Form 的表单。在提交表单之前,我的submit_happiness 视图会获取 IP 并将该字段添加到表单中。表单提交给我的Rating 模型。我的Rating 模型有一个名为ip 的字段。

    My submit_happiness view function is here.

    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)
    

    【讨论】:

      【解决方案2】:

      根据上面@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)
      

      【讨论】: