[英]How to save IP of user after submitting the django custom form
我寫了自己的表格來編輯配置文件,需要保存編輯配置文件的用戶的ip,但並不真正了解如何執行此操作。 我知道,我們可以從request.META['REMORE_ADDR']
獲取該IP,但是將其放置在何處以及如何保存到我的數據庫...如果您可以提供幫助,將非常高興。
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)
您不能將request
對象直接傳遞到表單中。 那不是它的工作方式。 如果需要將任何request
屬性與模型實例相關聯,則應在視圖中進行。
您可以收集request.META['REMOTE_ADDR'] which gives the IP info of the logged in user in the view and associate it to your
該request.META['REMOTE_ADDR'] which gives the IP info of the logged in user in the view and associate it to your
與視圖本身中的實例request.META['REMOTE_ADDR'] which gives the IP info of the logged in user in the view and associate it to your
。
您可以在form.is_valid()
方法中執行此操作,
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')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.