示例#1
0
    def post(self, request, *args, **kwargs):

        user_form = SignUpForm(request.POST)
        profile_form = ProfileForm(request.POST)
        voluntary_form = VoluntaryForm(request.POST)

        member_form = None
        voluntary_form = None
        if request.user.is_member:
            member_form = MemberForm(request.POST)
        elif request.user.is_voluntary:
            voluntary_form = VoluntaryForm(request.POST)

        if member_form and voluntary_form:
            if user_form.is_valid() and profile_form.is_valid(
            ) and voluntary_form.is_valid() and member_form.is_valid():
                return self.form_valid(user_form)

        elif member_form:
            if user_form.is_valid() and profile_form.is_valid(
            ) and member_form.is_valid():
                return self.form_valid(user_form)

        elif voluntary_form:
            if user_form.is_valid() and profile_form.is_valid(
            ) and voluntary_form.is_valid():
                return self.form_valid(user_form)
        else:
            self.send_form_error_messages(request, messages, user_form,
                                          profile_form)

            return self.render_to_response(self.get_context_data())
    def test_form_with_one_password(self):
        form_data = {'email': '*****@*****.**', 'password1': 'password'}
        form = SignUpForm(data=form_data)
        form.is_valid()
        user = form.save()

        self.assertIsNotNone(user)
示例#3
0
def sign_up_view(request):
    if request.method != "POST":
        form = SignUpForm()
        dictionary = {"form": form}
        return render(request, "users/sign_up.html", dictionary)
    else:
        form = SignUpForm(request.POST)
        if form.is_valid():
            if form.cleaned_data["password1"] != form.cleaned_data["password2"]:
                dictionary = {"form": form, "pw": "Passwords did not match"}
                return render(request, "users/sign_up.html", dictionary)
            else:
                user = DirrUser.objects.create_user(
                    username=form.cleaned_data["username"],
                    password=form.cleaned_data["password1"],
                    email=form.cleaned_data["email"],
                    first_name=form.cleaned_data["first_name"],
                    last_name=form.cleaned_data["last_name"],
                    phone_nr=form.cleaned_data["phone_nr"],
                    address=form.cleaned_data["address"],
                    p_code=form.cleaned_data["p_code"],
                    city=form.cleaned_data["city"],
                )
                user.is_active = True
                user.is_staff = False
                user.is_superuser = False
                user.save()
                user.authenticate(form.cleaned_data["username"], form.cleaned_data["password1"])
                login(request, user)
        else:
            dictionary = {"form": form, "pw": "Some fields were left blank"}
            return render(request, "users/sign_up.html", dictionary)
        return HttpResponseRedirect(reverse("main:main"))
示例#4
0
    def post(self, request):
        """
        Method to save the new user
        :param request:
        :return:
        """
        user_form = SignUpForm(request.POST)

        if user_form.is_valid():

            user = User()
            user.username = user_form.cleaned_data.get('username')
            user.first_name = user_form.cleaned_data.get('first_name')
            user.last_name = user_form.cleaned_data.get('last_name')
            user.email = user_form.cleaned_data.get('email')
            user.set_password(user_form.cleaned_data.get('password1'))

            user.save()

            return redirect('signup_success')

        else:

            context = {'form': user_form}

            return render(request, 'users/signup.html', context)
示例#5
0
def register_franchise(request, plan_id=1):
    plan = Plan.search(plan_id)
    if not plan:
        messages.error(request, "No existe el plan buscado")
        return redirect("home")

    if request.method == "POST":
        form_franchise = FranchiseForm(request.POST)
        form_user = SignUpForm(request.POST)
        if form_franchise.is_valid() and form_user.is_valid():

            from django.db import connection
            try:
                user, user_response = signup(request, user_type='admin')
                franchise = form_franchise.save(commit=False)
                franchise.client = user
                franchise.plan = plan
                franchise.save()
                domain = Domain(
                    domain=f"{franchise.schema_name}.{settings.DOMAIN}",
                    is_primary=True,
                    tenant=franchise,
                )
                domain.save()
                connection.set_tenant(franchise)
                User.initial_user(email=franchise.client.email,
                                  hash_password=franchise.client.password)
                connection.set_schema_to_public()
                messages.success(request,
                                 "La franquicia ha sido creada exitosamente")
                return redirect("franchise_list")
            except:
                messages.error(
                    request,
                    "No se pudo registrar la franquicia, contacte al soporte")
        else:
            messages.error(
                request,
                "No se pudo registrar la franquicia, contacte al soporte")
    else:
        form_franchise = FranchiseForm()
        form_user = SignUpForm()

    return render(
        request,
        "franchises/registry_franchises.html",
        {
            "form_franchise":
            form_franchise,
            "form_user":
            form_user,
            "title":
            "Franchise registry",
            "domains":
            Domain.objects.exclude(
                tenant__schema_name="public").select_related("tenant").all(),
            "domain":
            settings.DOMAIN,
        },
    )
示例#6
0
    def post(self, request):
        """
        Gestiona el registro de un usuario
        :param request: objeto HttpRequest con los datos de la petición
        :return: HttpResponse con la plantilla
        """
        error_message = ""
        signup_form = SignUpForm(request.POST)
        if signup_form.is_valid():
            name = signup_form.cleaned_data.get('first_name')
            last_name = signup_form.cleaned_data.get('last_name')
            email = signup_form.cleaned_data.get('email')
            username = signup_form.cleaned_data.get('username')
            password = signup_form.cleaned_data.get('password')

            try:
                validate_password(password, User)
                user = User.objects.create_user(username, email, password)
                user.first_name = name
                user.last_name = last_name
                user.save()

                if user.is_authenticated:
                    return redirect(
                        request.GET.get(
                            'next', reverse('post_list',
                                            args={user.username})))

            except ValidationError as errors:
                error_message = '\n'.join(errors)

        context = {'message': error_message, 'form': signup_form}
        return render(request, 'users/sign_up.html', context)
示例#7
0
    def post(self, request):
        form = SignUpForm(request.POST)

        if form.is_valid():
            user = User()
            cleaned_data = form.cleaned_data
            user.username = cleaned_data.get("username")
            user.first_name = cleaned_data.get("first_name")
            user.last_name = cleaned_data.get("last_name")
            user.email = cleaned_data.get("email")
            user.set_password(cleaned_data.get("password"))
            user.save()

            message = 'Usuario creado con éxito'
            django_login(request, user)
            url = request.GET.get('next', 'index')
            return redirect(url)
        else:
            message = "Se ha producido un error"

        context = {
            "form": form,
            "message":message
        }

        return render(request, 'users/signup.html', context)
示例#8
0
 def post(self, request):
     form = SignUpForm(request.POST)
     if form.is_valid():
         form.save()
         return redirect('/home/')
         # return Response({'form': form}, status=status.HTTP_200_OK)
     return Response({'form': form}, status=status.HTTP_200_OK)
示例#9
0
def create_user_as_ceo(request):
    gestor = Group.objects.get_or_create(name='Gestor')[0]
    operari = Group.objects.get_or_create(name='Operari')[0]
    tecnic = Group.objects.get_or_create(name='Tecnic')[0]
    ceo = Group.objects.get_or_create(name='Ceo')[0]
    # add permisions to every group here
    if request.method == 'POST':
        form = SignUpForm(request.POST)
        if form.is_valid():
            form.save()
            username = form.cleaned_data.get('username')
            raw_password = form.cleaned_data.get('password1')
            created = authenticate(username=username, password=raw_password)
            user_type = form.cleaned_data.get('user_type')
            if user_type.name == "Gestor":
                created.groups.add(gestor)
                created.save()
            elif user_type.name == "Operari":
                created.groups.add(operari)
                created.save()
            elif user_type.name == "Tecnic":
                created.groups.add(tecnic)
                created.save()
            elif user_type.name == "Ceo":
                created.groups.add(ceo)
                created.save()
            return redirect('list_users')
    else:
        form = SignUpForm()
    return render(request, 'users/usercreate-ceo.html', {'form': form})
示例#10
0
    def post(self, request):

        form = SignUpForm(request.POST)

        if form.is_valid():
            cd = form.cleaned_data
            first_name = cd.get("first_name")
            last_name = cd.get("last_name")
            username = cd.get("username")
            email = cd.get("email")
            password1 = cd.get("password1")
            password2 = cd.get("password2")
            blogtitle = cd.get("blogtitle")

            possible_blogs = Blog.objects.filter(blog_title=blogtitle)
            possible_email = User.objects.filter(email=email)

            if len(possible_email) > 0:
                form.add_error(None, 'This email is already in use')

            if len(possible_blogs) > 0:
                form.add_error(None, 'This blog title is already in use')

            if len(possible_blogs) == 0 and len(possible_email) == 0:
                new_user = User.objects.create_user(username, email, password1, first_name=first_name, last_name=last_name)
                new_blog = Blog.objects.create(blog_title=blogtitle, user=new_user)
                new_user.save()
                new_blog.save()
                form = SignUpForm()
                message = "¡Usuario creado con éxito!"
                messages.success(request, message)
                return redirect('login_page')

        context = {'form': form}
        return render(request, "signup_form.html", context)
示例#11
0
def signup_view(request):
    if request.method == 'POST':
        form = SignUpForm(request.POST)
        if form.is_valid():
            user = form.save()
            user_profile = Profile.objects.create(user=user)
            user_profile.account_type = form.cleaned_data.get('account_type')
            user_profile.save()

            if user.profile.is_doctor():
                doctor = Doctor.objects.create(
                    profile=user.profile,
                    specialization=form.cleaned_data.get('specialization'))
                doctor.save()
            else:
                patient = Patient.objects.create(profile=user.profile)
                patient.save()

            raw_password = form.cleaned_data.get('password1')
            user = authenticate(username=user.username, password=raw_password)
            login(request, user)
            return redirect('index')
    else:
        form = SignUpForm()
    return render(request, 'signup.html', {'form': form})
示例#12
0
    def post(self, request):
        form = SignUpForm(request.POST)

        if form.is_valid():
            user = User()
            cleaned_data = form.cleaned_data
            user.username = cleaned_data.get("username")
            user.first_name = cleaned_data.get("first_name")
            user.last_name = cleaned_data.get("last_name")
            user.email = cleaned_data.get("email")
            user.set_password(cleaned_data.get("password"))
            user.save()

            message = 'Usuario creado con éxito'
            django_login(request, user)
            url = request.GET.get('next', 'index')
            return redirect(url)
        else:
            message = "Se ha producido un error"

        context = {
            "form": form,
            "message":message
        }

        return render(request, 'users/signup.html', context)
示例#13
0
    def post(self, request):
        error_messages = []
        form = SignUpForm(request.POST)
        if form.is_valid():
            username = form.cleaned_data.get('usr')     # Obtengo datos formateados o normalizados
            password = form.cleaned_data.get('pwd')
            name = form.cleaned_data.get('name')
            surnames = form.cleaned_data.get('surnames')
            email = form.cleaned_data.get('email')

            if username and password and name and surnames and email:
                User.objects.create_user(username, email=email, password=password, first_name=name, last_name=surnames )
                user = authenticate(username=username, password=password)
                if user is None:
                    error_messages.append('Usuario ya existente')
                else:
                    django_login(request, user)
                    url = request.GET.get('next', 'new_post')
                    return redirect(url)
            else:
                error_messages.append('Faltan datos')
        context = {
            'errors': error_messages,
            'login_form': form
        }
        return render(request, 'users/signup.html', context)
示例#14
0
def sign_up(request):
    if request.method == 'GET':
        if request.user.is_authenticated:
            return redirect('views:home')
        form = SignUpForm()
        fields = list(form)
        context = {
            "required": fields[:4],
            "genre": fields[4],
            "instrument": fields[5],
            "sign_in": SignInForm(),
        }
        return render(request, 'sign/signup.html', context)

    elif request.method == 'POST':
        form = SignUpForm(request.POST)

        if form.is_valid():
            user = form.save(commit=False)
            user.set_password(form.cleaned_data.get('password1'))
            user.save()
            # m2m 관계 필드 폼으로 받아서 저장
            form.save_m2m()
            login(request, user, backend='django.contrib.auth.backends.ModelBackend')
            return redirect('views:home')
        else:
            form = SignUpForm(request.POST)
            fields = list(form)
            context = {
                "required": fields[:4],
                "genre": fields[4],
                "instrument": fields[5],
                "sign_in": SignInForm(),
            }
            return render(request, 'sign/signup.html', context)
示例#15
0
def signup(request):
    """Render forms and page for sign up and create new user 
        with basic permission level.
    """
    # POST
    if request.method == 'POST':
        form = SignUpForm(request.POST)
        if form.is_valid():
            # create, authenticate, and login user
            user = form.save()
            raw_password = form.cleaned_data.get('password1')
            user = authenticate(request,
                                email=user.email,
                                password=raw_password)
            if user:
                # successful authentication
                login(request, user)
                return redirect('users:home')

    # GET (assumed)
    else:
        form = SignUpForm()

    # signup fail or first try signup
    return render(request, 'signup.html', {'form': form})
示例#16
0
文件: views.py 项目: subfor/lms
def signup(request):
    if request.method == 'POST':
        form = SignUpForm(request.POST)
        if form.is_valid():
            user = form.save(commit=False)
            user.is_active = False
            user.save()
            current_site = get_current_site(request)
            subject = 'Activate Your MySite Account'
            token = account_activation_token.make_token(user)

            pk = user.pk
            pk_bytes = force_bytes(pk)
            user_id = urlsafe_base64_encode(pk_bytes)

            message = render_to_string(
                'users/account_activation_email.html', {
                    'user': user,
                    'domain': current_site.domain,
                    'user_id': user_id,
                    'token': token
                })
            # print(form.cleaned_data)
            data = {
                'to_email': form.cleaned_data['email'],
                'subject': subject,
                'message': message
            }
            send_activation_mail.delay(data)
            return render(request, 'users/account_activation_sent.html')
    else:
        form = SignUpForm()
    return render(request, 'users/signup.html', {'form': form})
示例#17
0
def signup(request):
    if request.method == 'POST':
        form = SignUpForm(request.POST)
        if form.is_valid():
            user = form.save()
            user.refresh_from_db(
            )  # load the profile instance created by the signal

            user.profile.birthdate = form.cleaned_data.get('birthdate')
            user.profile.location = form.cleaned_data.get('location')
            user.profile.spoken_language = form.cleaned_data.get(
                'spoken_language')
            user.profile.preferred_programming_language = form.cleaned_data.get(
                'preferred_programming_language')
            user.profile.bio = form.cleaned_data.get('bio')
            if form.cleaned_data.get('sign_up_as_mentor'):
                # Mentor role
                user.profile.role = 2
            else:
                # Mentee role
                user.profile.role = 1
            user.profile.hrs_per_week_available = form.cleaned_data.get(
                'hrs_per_week_available')
            user.profile.university = form.cleaned_data.get('university')
            user.profile.company = form.cleaned_data.get('company')

            # Finally, save that data we collected
            user.save()
            raw_password = form.cleaned_data.get('password1')
            user = authenticate(username=user.username, password=raw_password)
            login(request, user)
            return redirect('challenges')
    else:
        form = SignUpForm()
    return render(request, 'signup.html', {'form': form})
示例#18
0
 def test_valid_form(self):
     form = SignUpForm(data={'username': "******",
                             'password1': 'django-tutorial1',
                             'password2': 'django-tutorial1',
                             'first_name': "test",
                             "last_name": "test",
                             "email": "*****@*****.**",
                             "birth_date": "2000-10-10"})
     self.failUnless(form.is_valid())
示例#19
0
文件: views.py 项目: Alymbekov/doc
def signup(request):
    if request.method == "POST":
        form = SignUpForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect("/")
    else:
        form = SignUpForm()
    return render(request, "registration/signup.html", {"form": form})
示例#20
0
def create(request):
    context = {}
    if (request.method == 'POST'):
        u_form = SignUpForm(request.POST)  # fill it with user details
        p_form = ProfileForm(request.POST, request.FILES)
        if u_form.is_valid() and p_form.is_valid():
            user = u_form.save()
            email = user.email
            username = user.username
            first_name = user.first_name
            password = username + str(random.randint(1000, 9999))
            Profile.objects.filter(user=user).delete()
            profile = p_form.save(commit=False)
            profile.user = user
            profile.save()
            messages.success(request, f'Account Created')
            '''
            creating mantis, slack account
            '''
            try:
                print("slack start", user.email)
                slack = requests.post(
                    f"https://slack.com/api/users.admin.invite?token=xoxp-788210951796-790883779558-790885554118-6f267c84c9b3c9a5b90e2e74986c7be9&email={email}&channel='test'"
                )
                print("slack end")
                url = "http://mantis.atg.party/api/rest/users/"
                header = {
                    'Authorization': 'mhVBa0ZRB7CCOdd2AGF2RuULv8LCKSp8',
                    'Content-Type': 'application/json'
                }
                payload = f"{{\n  \"username\":\"{username}\",\n \"password\":\"{password}\",\n \"real_name\":\"{first_name}\",\n \"email\":\"{email}\",\n  \"enabled\": true,\n \"protected\":false}}"
                mantis_resp = requests.post(url,
                                            headers=header,
                                            data=payload,
                                            timeout=100000)
                mantis = mantis_resp.json()
                mantis_confirm_mail = EmailMultiAlternatives(
                    'ATG',
                    f"Mantis Account has been created!!\nUsername :{username}\nPassword :{password}",
                    "*****@*****.**", [email])
                mantis_confirm_mail.send()

                messages.success(
                    request,
                    "Registration Successfull\nYour Intranet and Mantis Account has been created. Please check the mail for slack and mantis credentials"
                )

            except Exception as exp:
                messages.error(
                    request,
                    "The credentials such as username or email may already be used in Mantis"
                )
            return render(request, 'mainapp/homepage.html', context)
        else:
            return HttpResponse("Form was Invalid")
    return HttpResponse("You don't have the permission to access this page")
示例#21
0
文件: signup.py 项目: vvkin/dev-hub
def validate_request_and_login(request):
    """Retrieve data from request and login"""
    data = request.POST
    form = SignUpForm(data)
    if form.is_valid():
        form.save()
        username = form.cleaned_data.get('username')
        raw_password = form.cleaned_data.get('password1')  # or password2
        user = authenticate(username=username, password=raw_password)
        login(request, user)
示例#22
0
def signup(request):
    if request.method == 'POST':
        form = SignUpForm(request.POST)
        if form.is_valid():
            user = form.save()
            auth_login(request, user)
            return redirect('districts')
    else:
        form = SignUpForm()
    return render(request, 'users/signup.html', {'form': form})
示例#23
0
    def test_signupform_valid_data(self):
        form = SignUpForm(
            data={
                'username': '******',
                'first_name': 'John',
                'last_name': 'Doe',
                'password': '******'
            })

        self.assertTrue(form.is_valid())
示例#24
0
def register(request):
    if request.method == 'POST':
        form = SignUpForm(request.POST)
        if form.is_valid():
            user = form.save(commit=False)
            user.set_password(form.cleaned_data['password1'])
            user.save()
    else:
        form = SignUpForm()
    return render(request, 'users/signup.html', {'form': form})
示例#25
0
def signup_user(request):
    if request.method == 'POST':
        form = SignUpForm(request.POST)
        if form.is_valid():
            user = form.save()
            login(request, user)
            return redirect('saveNow:index')
    else:
        form = SignUpForm()
    return render(request,'users/signup.html', {'form':form})
示例#26
0
    def test_create_user(self):
        data = {
            "email": "*****@*****.**",
            "password": "******",
        }

        form = SignUpForm(data=data)
        self.assertTrue(form.is_valid())

        user = form.save()
        self.assertEqual(user.email, "*****@*****.**")
示例#27
0
 def post(self, request):
     success_message = ''
     form = SignUpForm(request.POST)
     if form.is_valid():
         form.save()
         form = SignUpForm()
         success_message = 'Usuario creado con éxito!'
     context = {
         'signup_form': form,
         'success_message': success_message
     }
     return render(request, 'users/signup.html', context)
def sign_up(request):
    if request.method == 'POST':
        form = SignUpForm(data=request.POST)
        if form.is_valid():
            user = form.save()
            login(request, user)

            return HttpResponseRedirect(reverse('index'))

        return render(request, 'users/signup.html', {'form': form})

    return render(request, 'users/signup.html', {'form': SignUpForm()})
def sign_up(request):
    if request.method == "POST":
        form = SignUpForm(data=request.POST)
        if form.is_valid():
            user = form.save()
            login(request, user)

            return HttpResponseRedirect(reverse("index"))

        return render(request, "users/signup.html", {"form": form})

    return render(request, "users/signup.html", {"form": SignUpForm()})
示例#30
0
    def post(self, request):
        form = SignUpForm(request.POST)
        if form.is_valid():
            form.save()
            username = form.cleaned_data.get('username')
            raw_password = form.cleaned_data.get('password1')
            user = authenticate(username=username, password=raw_password)
            login(request, user)
            return redirect('home')
        context = {'form': form}

        return render(request, 'users/signup.html', context)
示例#31
0
 def test_email_already_taken(self):
     self.jacob = User.objects.create_user(username='******',
                                           email='*****@*****.**',
                                           password='******')
     form = SignUpForm(
         data={
             'username': '******',
             'email': '*****@*****.**',
             'password1': 'test12345',
             'password2': 'test12345'
         })
     self.assertFalse(form.is_valid())
示例#32
0
    def post(self, request, *args, **kwargs):

        user_form = SignUpForm(request.POST)
        profile_form = ProfileForm(request.POST)

        if user_form.is_valid() and profile_form.is_valid():
            return self.form_valid(user_form)
        else:
            self.send_form_error_messages(request, messages, user_form,
                                          profile_form)

            return self.render_to_response(self.get_context_data())
示例#33
0
 def post(self, request):
     form = SignUpForm(request.POST)
     if form.is_valid():
         form.save()
         username = form.cleaned_data.get('username')
         raw_password = form.cleaned_data.get('password1')
         user = authenticate(username=username, password=raw_password)
         django_login(request, user)
         return redirect('home_page')
     else:
         form.add_error(None, "Datos no válidos")
     return render(request, 'signup_form.html', {'form': form})
示例#34
0
文件: views.py 项目: mmcmahon321/Test
def signup(request):
    if request.method == 'POST':
        form = SignUpForm(request.POST)
        if form.is_valid():
            form.save()
            username = form.cleaned_data.get('username')
            raw_password = form.cleaned_data.get('password1')
            user = authenticate(username=username, password=raw_password)
            login(request, user)
            return redirect('home')
    else:
        form = SignUpForm()
    return render(request, 'users/signup.html', {'form': form})
示例#35
0
def view_signup(request, signup_template):
    if request.method == 'POST':
        form = SignUpForm(post_data(request))
        if form.is_valid():
            signup_data = form.cleaned_data
            userprofile = UserProfile.objects.create_profile(email=signup_data.get('email'),
                                                             password=signup_data.get('password'),
                                                             name=signup_data.get('name'))
            return _let_user_login(request,
                                   userprofile.user,
                                   email=signup_data.get('email'),
                                   password=signup_data.get('password'))
        else:
            from users.messages import USER_SIGNUP_FAILURE
            messages.error(request, USER_SIGNUP_FAILURE)
    else:
        form = SignUpForm()
    return response(request, signup_template, {'form':form})
示例#36
0
def sign_up(request):
    error_message = None

    if request.method == 'POST':
        form = SignUpForm(request.POST)
        if form.is_valid():
            # Create the user
            try:
                user = User.objects.create_user(
                        form.cleaned_data['user_name'],
                        form.cleaned_data['email'],
                        form.cleaned_data['password'])
            except IntegrityError:
                error_message = "That username is not available."
            else:
                user.first_name = form.cleaned_data['first_name']
                user.last_name = form.cleaned_data['last_name']
                user.save()

                # Create the user profile
                user_profile = UserProfile(
                        user=user,
                        alternate_email=form.cleaned_data['alternate_email'],
                        phone=form.cleaned_data['phone'],
                        tshirt=form.cleaned_data['tshirt'],
                        diet=form.cleaned_data['diet'],
                        location=form.cleaned_data['location'],
                        description=form.cleaned_data['description'],
                        notify_by_email=form.cleaned_data['notify_by_email'])
                user_profile.save()

                # Log the user in
                user = authenticate(username=user.username,
                        password=form.cleaned_data['password'])
                login(request, user)

                return HttpResponseRedirect(reverse('users-profile', args=[user.username])) # Redirect after POST
    else:
        form = SignUpForm()

    env = common_env()
    env['form'] = form
    env['error_message'] = error_message
    return render(request, 'users/signup.html', env)
示例#37
0
def sign_up(request):
    error_message = None

    if request.method == "POST":
        form = SignUpForm(request.POST)
        if form.is_valid():
            # Create the user
            try:
                user = User.objects.create_user(
                    form.cleaned_data["user_name"], form.cleaned_data["email"], form.cleaned_data["password"]
                )
            except IntegrityError:
                error_message = "That username is not available."
            else:
                user.first_name = form.cleaned_data["first_name"]
                user.last_name = form.cleaned_data["last_name"]
                user.save()

                # Create the user profile
                user_profile = UserProfile(
                    user=user,
                    tshirt=form.cleaned_data["tshirt"],
                    diet=form.cleaned_data["diet"],
                    location=form.cleaned_data["location"],
                    description=form.cleaned_data["description"],
                    notify_by_email=form.cleaned_data["notify_by_email"],
                )
                user_profile.save()

                # Log the user in
                user = authenticate(username=user.username, password=form.cleaned_data["password"])
                login(request, user)

                return HttpResponseRedirect("/users")  # Redirect after POST
    else:
        form = SignUpForm()

    env = common_env()
    env["form"] = form
    env["error_message"] = error_message
    return render(request, "users/signup.html", env)
示例#38
0
def sign_up_view(request):
    if request.method != 'POST':
        form = SignUpForm()
        dictionary = {'form': form}
        return render(request, 'users/sign_up.html', dictionary)
    else:
        form = SignUpForm(request.POST)
        if form.is_valid():
            if form.cleaned_data['password1'] != form.cleaned_data['password2']:
                dictionary = {'form': form, 'pw': 'Passwords did not match'}
                return render(request, 'users/sign_up.html', dictionary)
            else:
                user = DirrUser.objects.create_user(username=form.cleaned_data['username'], password=form.cleaned_data['password1'], email=form.cleaned_data['email'], first_name=form.cleaned_data['first_name'], last_name=form.cleaned_data['last_name'], phone_nr=form.cleaned_data['phone_nr'], address=form.cleaned_data['address'], p_code=form.cleaned_data['p_code'], city=form.cleaned_data['city'])
                user.is_active = True
                user.is_staff = False
                user.is_superuser = False
                user.save()
                user = authenticate(username=form.cleaned_data['username'], password=form.cleaned_data['password1'])
                login(request, user)
        else:
            dictionary = {'form': form, 'pw': 'Some fields were left blank'}
            return render(request, 'users/sign_up.html', dictionary)
        return HttpResponseRedirect(reverse('main:main'))
示例#39
0
    def post(self, request):
        """
        Muestra el formulario para crear un usuario nuevo
        :param request:
        :return:
        """
        user_form = SignUpForm(request.POST)

        if user_form.is_valid():
            user = User()
            user.username = user_form.cleaned_data.get('username')
            user.first_name = user_form.cleaned_data.get('first_name')
            user.last_name = user_form.cleaned_data.get('last_name')
            user.email = user_form.cleaned_data.get('email')
            user.password = user_form.cleaned_data.get('password1')

            user.save()

            return redirect('signup_success')
        else:
            context = {'form': user_form}

            return render(request, 'users/signup.html', context)
示例#40
0
def new(request):
    """Create new user."""
    if request.method == 'POST':
        form = SignUpForm(request.POST)
        if form.is_valid():
            new_user = form.save()
            user = auth.authenticate(email=request.POST.get('email').lower())
            auth.login(request, user)
            # If the user is signing up through ajax form
            pk = request.POST.get('reading')
            if pk:
                reading = get_object_or_404(Reading, pk=pk)
                # Create a dictionary of comment & vote forms for each note
                comment_forms = defaultdict(str)
                vote_forms = defaultdict(str)
                notes = reading.note_set.all()
                for note in notes:
                    d = { 
                        'comment_form': CommentForm(),
                        'note': note,
                    }
                    t = loader.get_template('comments/comment_form.html')
                    v = loader.get_template('votes/vote_form.html')
                    context = RequestContext(request, add_csrf(request, d))
                    comment_forms[str(note.pk)] = t.render(context)
                    vote_forms[str(note.pk)] = v.render(context)
                # Create a dictionary of reply forms for each comment
                reply_forms = defaultdict(str)
                comments = reading.comments()
                for comment in comments:
                    d = {
                        'comment': comment,
                        'reply_form': ReplyForm(),
                    }
                    t = loader.get_template('replies/reply_form.html')
                    context = RequestContext(request, add_csrf(request, d))
                    reply_forms[str(comment.pk)] = t.render(context)
                # Create the note & tag form
                d = {
                        'note_form': NoteForm(),
                        'reading': reading,
                        'static': settings.STATIC_URL,
                }
                favorite_form = loader.get_template('favorites/favorite_form.html')
                header = loader.get_template('header.html')
                note_form = loader.get_template('notes/note_form.html')
                tag_form = loader.get_template('tags/tag_form.html')
                context = RequestContext(request, add_csrf(request, d))
                # Ready all the partials to be outputted as JSON
                data = {
                    'comment_forms': comment_forms,
                    'favorite_form': favorite_form.render(context),
                    'header': header.render(context),
                    'note_form': note_form.render(context),
                    'reply_forms': reply_forms,
                    'success': 'yes',
                    'tag_form': tag_form.render(context),
                    'vote_forms': vote_forms,
                }
                return HttpResponse(json.dumps(data), 
                    mimetype='application/json')
            messages.success(request, 
                """Welcome %s, skim some reads and discover 
                something new""" % user.first_name)
            return HttpResponseRedirect(reverse('readings.views.discover'))
        else:
            pk = request.POST.get('reading')
            if pk:
                data = {
                    'success': 'no',
                }
                return HttpResponse(json.dumps(data), 
                    mimetype='application/json')
    else:
        form = SignUpForm()
    d = {
            'title': 'Welcome',
            'form': form,
    }
    return render_to_response('users/new.html', add_csrf(request, d), 
        context_instance=RequestContext(request))