0

Please guide and suggest me the best way to solve this problem.

I have a user information table:

first: username, first_name, last_name, email, password [ provided by django ]

Second: mobile, parent_id and other user profile related details [ want to create ]


Goal: I want the second table with some fields and connect with the auth_user ( the name provided by django ) through OneToOne relation so I can fectch all the field through one object.


What I have tried

1 case
I created a second table and connect with FK relation and download all previous data from the previous DB and sperate data manually and uploaded through CSV into new tables.

Problem: I cannot access both table data through a single object.

2nd case So I update the second table with OneToOne relation.

Problem: add new users with this relation is perfectly fine but when trying to edit/ change previously saved data then got error

error: invalid literal for int() with base 10 during change in models

Note: Hundreds of user in the previous table, just safly migrate with new DB schema.

Please, give me a tricky idea to fix this issue.

Thanks to all.

Kudos to the savior.


code:

views.py [file]

...
@login_required()
def register(request, epin):
    EPin = apps.get_model('epin', 'EPin')
    if EPin.objects.filter(epin__exact=epin, is_active=1,
                           assigned_to=request.user.username).exists():
        form = RegistrationForm()
        if request.method == 'POST':
            form = RegistrationForm(request.POST)
            if form.is_valid():
                if User.objects.filter(username__exact=request.POST['parent_id']).exists():
                    try:
                        with transaction.atomic():
                            username = generate_username()
                            password = generate_password()
                            EPin.objects.filter(epin__exact=epin,
                                                is_active=1).update(used_by=username, is_active=0,
                                                                    used_at=datetime.now())
                            Profile(mobile=request.POST['mobile'],
                                    leg=request.POST['leg'],
                                    product_id=request.POST['product'],
                                    parent_id=request.POST['parent_id'],
                                    user_id=username).save()

                            User.objects.create_user(username=username, password=password,
                                                     email=request.POST['email'],
                                                     first_name=request.POST['first_name'],
                                                     last_name=request.POST['last_name'])

                            logging.getLogger('info_logger').info('U : '+username+' P : '+password)
                    except Exception as e:
                        messages.warning(request, e)
                        logging.getLogger('error_logger').error(e)
                    # try:
                    #     user_msg = 'Username :' + username + ' and Password : ' + password
                    #     send_mail('Successfully registered ', user_msg,
                    #               'no-reply@example.in', [request.POST['email']])
                    # except Exception as e:
                    #     messages.warning(request, e)
                    #     logging.getLogger('error_logger').error(e)
                    # try:
                    #     user_msg = 'Username :' + username + ' and Password : ' + password
                    #     send_message(user_msg, request.POST['mobile'])
                    # except Exception as e:
                    #     messages.warning(request, e)
                    #     logging.getLogger('error_logger').error(e)

                    messages.success(request,
                                     'New User successfully created!, Username and password sent on mobile and email.')
                    return redirect('epin')
                else:
                    messages.warning(request, 'Invalid Sponsor ID, User not exists')
        return render(request, 'users/register.html', {'form': form})
    else:
        messages.warning(request, 'Not a valid E-Pin -- ' + epin)
        logging.getLogger('error_logger').error(epin+' not valid')
        return redirect('epin')



models.py [file]

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    # user_id = models.CharField(max_length=10)
    mobile = models.CharField(max_length=20)
    parent_id = models.CharField(max_length=10)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)


    def __str__(self):
        return f'{self.user.username}'
Umesh
  • 7
  • 2
  • 5
  • I think Case 2 is best for your case. Can you upload modles.py and views.py where you are trying to update data. – sandeep Oct 14 '19 at 13:03
  • @sandeep I just added the code that I've used, but I just want "Note: Hundreds of user in the previous table, just safely migrate with new DB schema." – Umesh Oct 14 '19 at 13:19
  • 1) "user" in Profile Model and you are saving with "user_id". 2) You should not save password like you are doing. 3) views.py is confusing. can you upload whole function. – sandeep Oct 14 '19 at 13:28
  • @sandeep added the whole function, its messed up bro, hope you can understand. – Umesh Oct 14 '19 at 13:57

1 Answers1

0

To relate Django´s user model as a Foreign key in another model use the following:

from django.contrib.auth.models import User
from django.contrib.auth import get_user_model

user = models.ForeignKey(get_user_model(), help_text="User", blank=True, null=True, on_delete=models.CASCADE)
Francisco Ghelfi
  • 872
  • 1
  • 11
  • 34
  • It's helpful but my need is different, If update the field type from CharacterField to FK or OneToOne then how to manage with existing data. Thanks, Francisco – Umesh Oct 14 '19 at 23:05
  • 1. Generate a new FK field. 2. Make your logic to populate those field from your existing field. 3. Remove old field – Francisco Ghelfi Oct 16 '19 at 17:22
  • Thanks for the reply, I did the same. – Umesh Oct 16 '19 at 19:02