Hello folks,

I'm studying Django and everything was ok until this morning. After 
creating a form using inlineformset_factory, I can't create an user. I got 
this error when creating the user inside the form I've created:

Exception Value: 

UNIQUE constraint failed: accounts_profile.user_id


Analising and debugging a little, I think that the error occurs because, on 
this SQL line code (generated automatically by django) it tries to save a 
String inside an integer field (user_id).


   - 
   
/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/db/backends/utils.py
    in execute
   1. 
      
                      return self.cursor.execute(sql, params)
      
      ...
   ▼ Local vars <http://127.0.0.1:8000/signup/#>
   VariableValue
   params 
   
   [19, '', None, None, 'F', '', '', '']
   
   self 
   
   <django.db.backends.utils.CursorDebugWrapper object at 0x10d94fc18>
   
   sql 
   
   ('INSERT INTO "accounts_profile" ("user_id", "location", "birthdate", 
"role", '
    '"gender", "site_facebook", "site_twitter", "profile_picture") VALUES (%s, '
    '%s, %s, %s, %s, %s, %s, %s)')
   
   


   1. 
   
               profile_formset.save()
   
   ...

▼ Local vars <http://127.0.0.1:8000/signup/#>
VariableValue
__class__ 

<class 'accounts.views.CreateUser'>

context 

{'form': <FormSignUp bound=True, valid=Unknown, 
fields=(username;email;password1;password2)>,
 'profile': <django.forms.formsets.ProfileFormFormSet object at 0x10d934518>,
 'view': <accounts.views.CreateUser object at 0x10d9436d8>}

form 

<FormSignUp bound=True, valid=True, fields=(username;email;password1;password2)>

profile_formset 

<django.forms.formsets.ProfileFormFormSet object at 0x10d934518>

self 

<accounts.views.CreateUser object at 0x10d9436d8>



Here is the codes:

models.py
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
location = models.CharField(max_length=30, blank=True)
birthdate = models.DateField(null=True, blank=True)

profile_picture = models.ImageField(upload_to='profile_pictures', 
blank=True)

def __str__(self):
return self.user.username

@property
def age(self):
TODAY = datetime.date.today()
if self.birthdate:
return u"%s" % relativedelta.relativedelta(TODAY, self.birthdate).years
else:
return None

@receiver(post_save, sender=User)
def create_or_update_user_profile(sender, instance, created, **kwargs):
if created:
Profile.objects.create(user=instance)
instance.profile.save()

forms.py
class FormSignUp(UserCreationForm):
email = forms.CharField(max_length=254, required=True, 
widget=forms.EmailInput())

class Meta:
model = User
fields = ['username', 'email', 'password1', 'password2']

class FormProfile(forms.ModelForm):
class Meta:
model = Profile
fields = ['birthdate', 'gender', 'site_facebook', 'site_twitter', 
'profile_picture']

FormSetProfile = inlineformset_factory(User, Profile, form=FormProfile)




view.py
class CreateUser(CreateView):
    form_class = FormSignUp
    template_name = 'signup.html'
    success_url = reverse_lazy('home')

    def get_context_data(self, **kwargs):
        data = super(CreateUser, self).get_context_data(**kwargs)
        if self.request.POST:
            data['profile'] = FormSetProfile(self.request.POST)
        else:
            data['profile'] = FormSetProfile()
        return data

    def form_valid(self, form):
        context = self.get_context_data()
        profile_formset = context['profile']


        with transaction.atomic():
            form.instance.created_by = self.request.user
            form.instance.updated_by = self.request.user
            self.object = form.save()
        if profile_formset.is_valid():
            profile_formset.instance = self.object
            profile_formset.save() # Linha onde está dando o erro

        return super(CreateUser, self).form_valid(form)

Thanks for your help

Luiz Guilherme

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/ec6cbe06-6252-408f-a36c-7b863b33ad6c%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to