Skip to content

Instantly share code, notes, and snippets.

@taizarm
Last active Sep 8, 2015
Embed
What would you like to do?
Django - dúvida com transacao
@transaction.atomic()
def salva_user_profile(user, profile):
user.save()
#Aqui eu simulo um erro, para que o profile não seja salvo.
#Deveria dar o rollback em tudo, mas se eu olho no banco, o usuario (linha anterior) foi cadastrado.
profile.nome = None
profile.save()
#Tb ja tentei tirando a anotacao e colocando with transaction.atomic():
class CadastroUsuarioForm(forms.Form):
TERMO_COMPROMISSO = (
(1, 'Li e concordo'),
)
nome = forms.CharField(
max_length=255,
label='* Nome completo',
widget=forms.TextInput()
)
sexo = forms.ChoiceField(
choices=Pessoa.TIPO_SEXO,
widget=forms.RadioSelect(),
label='* Sexo'
)
email = forms.EmailField(
required=True,
widget=forms.EmailInput(attrs={'class': 'form-input'})
)
email2 = forms.EmailField(
required=True,
widget=forms.EmailInput(attrs={'class': 'form-input'}),
label='* Confirmação de e-mail'
)
password1 = forms.CharField(
widget=forms.PasswordInput(attrs={'class': 'form-input'}),
help_text='A senha deve ter no mínimo 6 caracteres.'
)
password2 = forms.CharField(
widget=forms.PasswordInput(attrs={'class': 'form-input'})
)
def signup(self, request, user):
profile = Pessoa(user=user)
profile.nome = request.POST["nome"]
profile.sexo = request.POST["sexo"]
with transaction.atomic():
salva_user_profile(user, profile)
class Pessoa(models.Model):
SEXO_FEM = 'F'
SEXO_MAS = 'M'
TIPO_SEXO = (
(SEXO_MAS, 'Masculino'),
(SEXO_FEM, 'Feminino'),
)
user = models.OneToOneField(settings.AUTH_USER_MODEL, null=True, blank=True)
nome = models.CharField(max_length=255)
sexo = models.CharField(max_length=1, choices=TIPO_SEXO)
ACCOUNT_SIGNUP_FORM_CLASS = 'site.forms.CadastroUsuarioForm'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment