Friday, February 20, 2015

Re: Create a new object for the newly registered user

You can use a post_save signal for the User Model


from django.db.models.signals import post_save
from django.contrib.auth.models import User

def create_about(sender, **kwargs):
    user = kwargs['instance']
    if kwargs['created']:
        about = About()
        about.user = user
        about.save()

post_save.connect(create_about, sender=User)


On Fri, Feb 20, 2015 at 4:58 PM, <tiklitaba123@gmail.com> wrote:
I am very new to django, so please bear with me. What I want is whenever a new user is registered I would like to create an `About` for that user. How will I do that? Please help me. Thank you.

views:

    def register(request):
        if request.method == 'POST':
            form = UserCreationForm(request.POST or None)
            if form.is_valid():
                form.save()
                return HttpResponseRedirect('/')
            else:
                return render(request, 'register.html', {'form':form})
        else:
            form = UserCreationForm()
            return render(request, 'register.html', {'form':form})

model:

    class About(models.Model):
        user = models.OneToOneField(User)
        gender = models.CharField(max_length=1, choices=GENDER)
        dob = models.DateField(null=True, blank=True)
        place = models.CharField(max_lenght=100)

--
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+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/a9958449-22b8-437d-bdd0-8a25372a99fe%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

--
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+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CALn3ei3jaPf1Ua1kvfsEvVDs9KoWxfpzgJru6YyDigWKL5BJXA%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment