I am currently having an issue in saving data to database. What I am planning to do is I have an ip field denoting the ip address and a few other fields. These other fields are to be added to database using ModelForm. And when the form is submitted the ip address is saved along with the form data. But when i go to my admin page the ip field is empty.
model.py
class Restaurant(models.Model):
ip = models.CharField(max_length=45)
name = models.CharField(max_length=100)
owner = models.CharField(max_length=100)
city = models.CharField(max_length=50)
state = models.CharField(max_length=50)
zipcode = models.CharField(max_length=6)
forms.py
class RestaurantForm(forms.ModelForm):
class Meta:
model = Restaurant
fields = ('name', 'owner', 'city', 'state', 'zipcode',)
labels = {
'name': _('Name of restaurant'),
'owner': _('Owner name'),
'zipcode': _('Zip Code'),
}
views.py
def content(request):
if request.method == "POST":
form = RestaurantForm(request.POST)
if form.is_valid:
form.save(commit=False)
ip_address = get_client_ip(request)
form.ip = ip_address
form.save()
else:
error= "empty fields"
return render(request, 'registration/content.html',{'error': error,'form':form})
else:
form = RestaurantForm()
return render(request, 'registration/content.html',{'form': form})
def get_client_ip(request):
x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
if x_forwarded_for:
ip = x_forwarded_for.split(',')[0]
else:
ip = request.META.get('REMOTE_ADDR')
return ip
Thanks in advance!