0

I am able to store an user in the User table however the UserModelInfo table is not getting updated.

project github link - https://github.com/souradip-code/Django_myproject_1

enter image description here

enter image description here

So what I basically want is an OneToOne relationship with django built-in User class with UserInfo Class and if I add one user, both tables should update and every user from the UserInfo table should point to an user in the User table.

Here is what I've done so far -

Models.py

JOB_CHOICES = (
    (1, "Designer"),
    (2, "Manager"),
    (3, "Accounting")
)
CONTACT_CHOICES = (
    (1, "+91"),
    (2, "+92"),
    (3, "+93"),
)

class UserInfoModel(models.Model):

    user = models.OneToOneField(User,on_delete=models.CASCADE)
    
    fullname = models.CharField(max_length=264,unique=True)
    email = models.EmailField(max_length=255)
    contact_pref = models.IntegerField(choices=CONTACT_CHOICES, default=1)
    contact_suff =models.IntegerField()
    job= models.IntegerField(choices=JOB_CHOICES, default=1)
    pwd1 = models.CharField(max_length=20)
    pwd2 = models.CharField(max_length=20)

    def __str__(self):
        return user.fullname
enter code here

Forms.py

JOB_CHOICES = (
    (1, "Designer"),
    (2, "Manager"),
    (3, "Accounting")
)
CONTACT_CHOICES = (
    (1, "+91"),
    (2, "+92"),
    (3, "+93"),
)

class RegisterForm(forms.ModelForm):

    fullname = forms.CharField(max_length=264,widget=forms.TextInput(attrs={'class':'form-control'}))

    email = forms.EmailField(max_length=255,widget=forms.EmailInput(attrs={'class':'form-control'}))

    contact_pref = forms.ChoiceField(choices=CONTACT_CHOICES,widget=forms.Select(attrs={'class':'custom-select'}))

    contact_suff =forms.IntegerField(widget=forms.NumberInput(attrs={'class':'form-control'}))

    job= forms.ChoiceField(choices=JOB_CHOICES,widget=forms.Select(attrs={'class':'custom-select'}))

    pwd1 = forms.CharField(max_length=20,widget=forms.PasswordInput(attrs={'class':'form-control'}))

    pwd2 = forms.CharField(max_length=20,widget=forms.PasswordInput(attrs={'class':'form-control'}))

    class Meta:
        model = UserInfoModel
        # fields = "__all__"
        exclude =("user",)

Here please check the Meta class configuration

Views.py

def user_register(request):

    template = 'basic_app/register.html'

    if request.method == 'POST':
        form = RegisterForm(request.POST)
        if form.is_valid():
            if User.objects.filter(username=form.cleaned_data['fullname']).exists():
                return render(request, template, {
                    'form': form,
                    'error_message': 'Username already exists.'
                })
            elif User.objects.filter(email=form.cleaned_data['email']).exists():
                return render(request, template, {
                    'form': form,
                    'error_message': 'Email already exists.'
                })
            elif form.cleaned_data['pwd1'] != form.cleaned_data['pwd2']:
                return render(request, template, {
                    'form': form,
                    'error_message': 'Passwords do not match.'
                })
            else:
                # Create the user:
                user = User.objects.create_user(
                    form.cleaned_data['fullname'],
                    form.cleaned_data['email'],
                    form.cleaned_data['pwd1']
                )
                user.contact_pref = form.cleaned_data['contact_pref']
                user.contact_suff = form.cleaned_data['contact_suff']
                user.job = form.cleaned_data['job']
                user.save()
                return render(request, 'basic_app/index.html')   

        return render(request, template,{'form': form})
    else:
        form = RegisterForm()

    return render(request,template,{'form': form})

Register.html

 <form action="{% url 'basic_app:register' %}" method="post">
        {% csrf_token %}
        <div class="form-group input-group">
          <div class="input-group-prepend">
            <span class="input-group-text"> <i class="fa fa-user"></i> </span>
          </div>
          <!-- <input
            name="fullname"
            class="form-control"
            placeholder="Full name"
            type="text"
          /> -->
          {‌{ form.fullname }}
        </div>
        <!-- form-group// -->
        <div class="form-group input-group">
          <div class="input-group-prepend">
            <span class="input-group-text">
              <i class="fa fa-envelope"></i>
            </span>
***********************rest of the code************************
Souradip
  • 111
  • 1
  • 10
  • Correct me if I am wrong. You have UserInfoModel which is in oneToOne relationship with User model. Now you want that whenever User is getting created your UserModelInfo should also get saved right ? – k33da_the_bug Apr 23 '20 at 04:58
  • by signal create you UserInfoModel after user registration, after that for other update request you do other changes – Baktiyar Bekbergen Apr 23 '20 at 05:18
  • @k33da_lets_debug - Yes that is what actually I want to achieve- – Souradip Apr 23 '20 at 07:02
  • @BakhtiyarBekbergen - Can you bit more illustrative. I don't get your answer. I want to use OneToOneField so that when I create one user using UserInfoModel that should also create one user in the User table. – Souradip Apr 23 '20 at 07:06
  • 1
    Ok so here I can suggest some tweaks. Already you have UserInfoModel oneToOne relationship with User. Create two model forms and then create a inline formset by combining both forms. And then render that formset. Consider [this](https://stackoverflow.com/a/60708034/8601641) example. – k33da_the_bug Apr 23 '20 at 07:33
  • @k33da_lets_debug Thanks for response but I want to use form action attribute in the html file to get the data. I know the process you have mentioned above but It would be great if you check on this. – Souradip Apr 23 '20 at 08:40

0 Answers0