Hayden
Hayden

Reputation: 498

Record IP Address with Form Submission Django

I am trying to use the django-ipware pacakge to record the IP address of someone submitting a form submission via Django.

The form is a ModelForm. Here's the 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()

Here is the form:

# 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'
        }

The business logic for getting the IP address is pretty simple, but I've tried placing it in different locations with no luck. Where should I place the logic so it will be submitted along with the other form data?

# views.py
from ipware.ip import get_real_ip

ip = get_real_ip(request)

Upvotes: 0

Views: 828

Answers (2)

Hayden
Hayden

Reputation: 498

Per @David Smolinksi's suggestion from above, here's how I solved this issue:

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

Upvotes: 0

David Smolinski
David Smolinski

Reputation: 534

I did that in a function based view. I have a view function called submit_happiness that submits a form called Survey_Form. Before submitting the form, my submit_happiness view gets the IP and adds that field to the form. The form is submitted to my Rating model. My Rating model has a field called 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)

Upvotes: 1

Related Questions