I got an issue with registration of Users.
I use a custom user linked to the default one.
i’ll show the code
in models.py of my accounts:
class ProfiloUtente(models.Model):
user = models.OneToOneField(User, related_name='profile', on_delete=models.CASCADE)
utente = models.ForeignKey(Utente, on_delete=models.CASCADE)
studio = models.ManyToManyField(Studio)
telefono_fisso = models.CharField(max_length=20, default=None, blank=True)
telefono_mobile = models.CharField(max_length=20, default=None, blank=True)
indirizzo = models.CharField(max_length=40, default=None, blank=True)
citta = models.CharField(max_length=50, default=None, blank=True)
cap = models.CharField(max_length=5, default=None, blank=True)
provincia = models.CharField(max_length=30, default=None, blank=True)
cod_fiscale = models.CharField(max_length=16, default=None, blank=True)
p_iva = models.CharField(max_length=27, default=None, blank=True)
def __str__(self):
return self.user.username
and in views.py my register view as:
def register(request):
if request.method =='POST':
form = RegistrationForm(request.POST)
profilo_utente_form = ProfiloUtenteForm(request.POST)
if form.is_valid() and profilo_utente_form.is_valid():
user = form.save()
profile = profilo_utente_form.save(commit=False)
profile.user = user
profile.save()
profilo_utente_form.save_m2m()
return redirect('/incarico_slice')
else:
args = {'form': form, 'profilo_utente_form': profilo_utente_form}
return render(request, 'accounts/register.html', args)
else:
form = RegistrationForm()
profilo_utente_form = ProfiloUtenteForm()
args = {'form': form, 'profilo_utente_form': profilo_utente_form}
return render(request, 'accounts/register.html', args)
lastly in forms.py using these default user fields:
class RegistrationForm(UserCreationForm):
"""docstring for RegistrationForm"""
email = forms.EmailField(required=True)
first_name = forms.CharField(max_length=30, required=True)
last_name = forms.CharField(max_length=100, required=True)
class Meta: # define a metadata related to this class
model = User
fields = (
'username',
'email',
'first_name',
'last_name',
'password1',
'password2',
)
def save(self, commit=True):
user = super(RegistrationForm, self).save(commit=False)
user.email = self.cleaned_data['email']
user.first_name = self.cleaned_data['first_name']
user.last_name = self.cleaned_data['last_name']
if commit:
user.save() # running sql in database to store data
return user
just to watch register.html
<h1>Register!</h1>
<form method="post">
{% csrf_token %}
{{ profilo_utente_form.as_p }}
{{ form.as_p }}
<button type="submit">Submit</button>
</form>
The strange thing is that if i do something wrong in my registration form, in the database appears that it creates The Default user model without creating his related userProfile ( ProfiloUtente), and this is something that shouldn’t happen, still trying to fix it.
Any help is appreciated!!!
Thanks in advance