I'm sorry. Let me ask you again. I have a question about Django's from.

Asked 2 years ago, Updated 2 years ago, 48 views

Hello. I have a question about Django. It's not an error problem. I'm inquiring about changing the membership form. You created a class called profile in models and created an object in it.

class profile (models.Model):
    user=models.OneToOneField(User,on_delete=models.CASCADE)
    company=models.CharField(max_length=30)
    office = models.CharField(max_length=30)
    name = models.CharField(max_length=10)

And I want to create a User Creation Form in forms and save it in the profile in models I'm inquiring because I don't know how.

def save(self, commit=True):
        user = super(RegistrationForm, self).save(commit=False)
        company = self.cleaned_data.get('company')
        office = self.cleaned_data.get('office')
        name = self.cleaned_data.get('name')
        profile.objects.create(
            user=user,
            company=company,
            office=office,
            name=name
        )
        if commit:
            user.save()
        return user'''

In the above method, the basic form is saved, but the rest of the company/office/name is not saved

The above one has an error in the profile.objects.create part What should I do to save it in the model and in the profile.

django

2022-09-22 15:22

2 Answers

We found the cause.

If you look at def save ,

if commit:
    user.save()

There's this part.

The user is saved to db only after the save is executed. That way, the user can be saved in the profile using foreignkey. user.save() first and profile.objects.create works well.


2022-09-22 15:22

from django import forms
from django.contrib.auth.forms import UserCreationForm
from .models import profile

class RegistrationForm(UserCreationForm):
     "Omitted"
   company=forms.CharField
   office=forms.CharField
   name=forms.CharField

class Meta:
        model = User
        fields = ("username", "email", "password1", "password2",'company','office','name')


def save(self,commit=True):
        user=super(RegistrationForm,self).save(commit=False)
        company=self.cleaned_data.get('company')
        office=self.cleaned_data.get('office')
        name=self.cleaned_data.get('name')
       if commit:
            user.save()
            profile.objects.create(
                user=user,
                company=company,
                office=office,
                name=name)
        return user
        user.save() ...

▶ I see an error saying Local vars


2022-09-22 15:22

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.