简体   繁体   中英

How to save IP of user after submitting the django custom form

I wrote my own form for editing of profile and need to save ip of user, who edit profile, but not really understand how to do this. I know, that ip we can get from request.META['REMORE_ADDR'] but where to put this and how to save to my db... Will be very glad if you could help.

models.py

class Profile(models.Model):
   user = models.OneToOneField(User, unique=True)
   first_name = models.CharField(max_length=200)
   last_name = models.CharField(max_length=200)
   date_of_birth = models.DateField()
   biography = models.TextField()
   contacts = models.CharField(max_length=200)
   ip_address = models.GenericIPAddressField(null=True)

forms.py

class UserEditProfile(forms.ModelForm):
    first_name = forms.CharField( max_length=30)
    last_name = forms.CharField( max_length=30)
    date_of_birth = 
    forms.DateField(widget=SelectDateWidget(years=BIRTH_YEAR_CHOICES))
    biography = forms.Textarea()
    contacts = forms.CharField()


    def __init__(self, *args, **kw):
        super(UserEditProfile, self).__init__(*args, **kw)
        self.fields['first_name'].initial = self.instance.first_name
        self.fields['last_name'].initial = self.instance.last_name
        self.fields['date_of_birth'].initial = 
        self.instance.date_of_birth
        self.fields['biography'].initial = self.instance.biography
        self.fields['contacts'].initial = self.instance.contacts


        self.fields.keyOrder = [
            'first_name',
            'last_name',
            'date_of_birth',
            'biography',
            'contacts'
            ]

    def save(self, *args, **kw):
        super(UserEditProfile, self).save(*args, **kw)
        self.instance.first_name = self.cleaned_data.get('first_name')
        self.instance.last_name = self.cleaned_data.get('last_name')
        self.instance.date_of_birth = 
        self.cleaned_data.get('date_of_birth')
        self.instance.biography = self.cleaned_data.get('biography')
        self.instance.contacts = self.cleaned_data.get('contacts')
        self.instance.save()

    class Meta:
        model = Profile
        fields = (
            'first_name',
            'last_name',
            'date_of_birth',
            'biography',
            'contacts'
        )
        exclude = ['user', 'ip_address']

view.py

def edit_profile(request):
    user = Profile.objects.get(id=request.user.id)

    if request.method == "POST":
        form = UserEditProfile(request.POST, instance=user)

        if form.is_valid():
            form.save(commit=False)
            return redirect('profile')
    else:
        form = UserEditProfile(instance=user)
        args = {'form': form}
        return render(request, 'edit.html', args)

You cannot pass request object into form directly. That's not the way it works. If you need to associate any request attributes to your model instances, you should do it in the views.

You could collect the request.META['REMOTE_ADDR'] which gives the IP info of the logged in user in the view and associate it to your instance` in the view itself.

You could do this in your form.is_valid() method,

if form.is_valid():
    profile = form.save(commit=False)
    profile.ip_address = request.META['REMOTE_ADDR']
    profile.user = request.user
    profile.save()
    return redirect('profile')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM