When the user signs up, I want to add their country to their profile. But, the field remains blank in the database and doesn’t get populated with the country. I am new to authentication in Django, so it may be wrong in other ways.I think the order may be the problem? I am really unsure.
Views.py
def get_country(ip):
if ip in ['127.0.0.1', 'localhost', '::1']:
return 'Localhost'
# Perform GeoIP lookup
g = GeoIP2()
try:
result = g.city(ip)
country = result["country_name"]
except Exception as e:
print(f'Error: {e}')
country = "Unknown"
return country
def signup_view(request):
if request.method == 'POST':
form = UserCreateForm(request.POST)
if form.is_valid():
user = form.save()
# Get the user's IP address
x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
if x_forwarded_for:
ip = x_forwarded_for.split(',')[0].strip()
else:
ip = request.META.get('REMOTE_ADDR')
# Determine the user's country
country = get_country(ip)
# Create the profile with the country information
username = form.cleaned_data.get('username')
raw_password = form.cleaned_data.get('password1')
Profile.objects.create(user=user, country=country)
user = authenticate(username=username, password=raw_password)
login(request, user)
return redirect('/')
else:
form = UserCreateForm()
return render(request, 'signup.html', {'form': form})
models.py
from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.dispatch import receiver
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
image = models.ImageField(
default='profile_pics/default.jpg', upload_to='profile_pics')
country = models.CharField(max_length=100)
def __str__(self):
return f'{self.user.username} Profile'
@receiver(post_save, sender=User)
def manage_profile(sender, instance, created, **kwargs):
if created:
Profile.objects.get_or_create(user=instance)
I have run the get_country function in shell using RequestFactory() and I get the correct country depending on ip. So, that function is fine. It is updating the profile with the country during sign up that won’t work.
Aaron is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.