Esempio n. 1
0
 def post(self, request, *arg, **kwargs):
     pk = self.kwargs.get('pk')
     instance = None
     profile = None
     coop_admin = None
     errors = dict()
     
     if pk:
         instance = User.objects.filter(pk=pk)
         if instance.exists():
             instance = instance[0]
             profile = instance.profile
             if hasattr(instance, 'cooperative_admin'):
                 coop_admin = instance.cooperative_admin
     user_form = UserForm(request.POST, instance=instance)
     profile_form = UserProfileForm(request.POST, instance=profile)
     
     if user_form.is_valid() and profile_form.is_valid():
         try:
             with transaction.atomic():
                 if not errors:     
                     user = user_form.save(commit=False);
                     if not instance:
                         user.set_password(user.password)
                     user.save()
                     profile_form = UserProfileForm(request.POST, instance=user.profile)
                     profile_form.save()
                     return redirect('profile:user_list')
         except Exception as e:
             log_error()
             errors['errors'] = "Error %s" % e
     data = {'user_form': user_form, 'profile_form': profile_form, 'coop_form': coop_form}
     data.update(errors)
     return render(request, self.template_name, data)
Esempio n. 2
0
def register(request):
    message = None
    if request.user.is_authenticated():
        return redirect("/users/my")
    if request.method == "POST":
        form = UserForm(request.POST)
        if form.is_valid():
            data = form.cleaned_data
            user = User.objects.create_user(data.get('username'), data.get('email'), data.get('password'))
            user.save()
            message = "Your account has been created!"
    elif request.method == "GET":
        form = UserForm()
    return render_to_response('userprofile/register.html', {'message':message,'form': form}, context_instance=RequestContext(request))
Esempio n. 3
0
    def post(self, request, *arg, **kwargs):
        pk = self.kwargs.get('pk')
        agrodealer = self.kwargs.get('agrodealer')
        instance = None
        errors = dict()

        if pk:
            instance = User.objects.filter(pk=pk)
            if instance.exists():
                instance = instance[0]
                profile = instance.profile
                if hasattr(instance, 'cooperative_admin'):
                    coop_admin = instance.cooperative_admin
        user_form = UserForm(request.POST, instance=instance)
        profile_form = UserProfileForm(request.POST, instance=instance)

        if user_form.is_valid() and profile_form.is_valid():
            try:
                with transaction.atomic():
                    if not errors:
                        user = user_form.save(commit=False)
                        if not instance:
                            user.set_password(user.password)
                        user.save()
                        profile_form = UserProfileForm(request.POST,
                                                       instance=user.profile)
                        profile_form.save(commit=False)
                        profile_form.access_level = get_object_or_404(
                            AccessLevel, name='AGRODEALER')
                        profile_form.save()

                        inst_s = AgroDealer.objects.get(pk=agrodealer)
                        AgroDealerUser.objects.create(
                            agrodealer=inst_s,
                            user=user,
                        )
                        return redirect('agrodealer:agrodealer_user',
                                        agrodealer=agrodealer)
            except Exception as e:
                log_error()
                errors['errors'] = "Error %s" % e
        data = {
            'user_form': user_form,
            'profile_form': profile_form,
            'active': ['_agrodealer']
        }
        data.update(errors)
        return render(request, self.template_name, data)
Esempio n. 4
0
def user_login(request):
    # if request.method == 'POST':
    #     user_login_form = UserLoginForm(request.POST)
    #     if user_login_form.is_valid():
    #         data = user_login_form.cleaned_data
    #         user = authenticate(username=data['username'], password=data['password'])
    #         if user:
    #             login(request, user)
    #             return redirect('article:article_list')
    #         else:
    #             return HttpResponse('账号密码有误')
    #     else:
    #         return HttpResponse('账号密码输入不合法')
    # elif request.method == 'GET':
    #     user_login_form = UserLoginForm()
    #     context = {
    #         'form':user_login_form
    #     }
    #     return render(request, 'userprofile/login.html', context)
    # else:
    #     return HttpResponse('请使用GET或POST请求方式!')
    if request.session.get('is_login', None):
        return redirect('article:article_list')
    if request.method == 'POST':
        login_form = UserForm(request.POST)
        message = '请填写相关信息!'
        if login_form.is_valid():
            username = login_form.cleaned_data.get('name')
            password = login_form.cleaned_data.get('password')
            try:
                user = models.User.objects.get(name = username)
            except:
                message = '用户名不存在!'
                return render(request, 'userprofile/login.html', locals())
            if user.password == password:
                request.session['is_login'] = True
                request.session['user_id'] = user.id
                request.session['user_name'] = user.name
                return redirect('article:article_list')

            else:
                message= '用户密码错误!'
                return render(request, 'userprofile/login.html',locals())
        else:
            return render(request, 'userprofile/login.html', locals())
    else:
        login_form = UserForm()
        return render(request, 'userprofile/login.html', locals())
Esempio n. 5
0
def create_profile(request):
    if request.POST:
        userprofile_form = UserProfileForm(request.POST, request.FILES, prefix='userprofile_form')
        user_form = UserForm(request.POST, request.FILES, prefix='user_form')
        if all([userprofile_form.is_valid(), user_form.is_valid()]):
            user = user_form.save()
            profile = userprofile_form.save(commit=False)
            profile.user = user
            profile.save()
    else:
        userprofile_form = UserProfileForm(prefix='userprofile_form')
        user_form = UserForm(prefix='user_form') 
    return render(request, "user_profile.html", {
        'userprofile_form': userprofile_form,
        'user_form': user_form
    })
Esempio n. 6
0
def signup(request):
    if request.POST:
        userprofile_form = UserProfileForm(request.POST, request.FILES, prefix='userprofile_form')
        user_form = UserForm(request.POST, request.FILES, prefix='user_form')
        if all([userprofile_form.is_valid(), user_form.is_valid()]):
            user = user_form.save()
            profile = userprofile_form.save(commit=False)
            profile.user = user
            profile.save()
            user_login(request, user)
            return HttpResponseRedirect(reverse("userprofile:login"))
    else:
        userprofile_form = UserProfileForm(prefix='userprofile_form')
        user_form = UserForm(prefix='user_form')
    return render(request, "signup.html", {
        'userprofile_form': userprofile_form,
        'user_form': user_form
    })
Esempio n. 7
0
def register(request):

    registered = False
    if request.method == 'POST':
        user_form = UserForm(data=request.POST)
        profile_form = UserProfileForm(data=request.POST)
        if user_form.is_valid() and profile_form.is_valid():
            user = user_form.save()
            user.set_password(user.password)
            user.save()
            profile = profile_form.save(commit=False)
            profile.user = user
            profile.save()
            registered = True
        else:
            print (user_form.errors,profile_form.errors)
    else:
        user_form = UserForm()
        profile_form = UserProfileForm()
    return render(request,'snatch/register.html',
    {'user_form':user_form,'profile_form':profile_form,'registered':registered})
Esempio n. 8
0
def register_invited_user(request):
    registered = False
    if request.method == 'POST':
        user_form = UserForm(data=request.POST)
        doctor_form = DoctorForm(data=request.POST)
        if user_form.is_valid() and doctor_form.is_valid():
            user = user_form.save()
            user.set_password(user.password)
            user.save()

            doctor = doctor_form.save(commit=False)
            doctor.verification_status = True
            doctor.user = user
            doctor.save()
            if FriendInvitation.objects.filter(email=user.email).exists():
                FriendInvitation.objects.filter(email=user.email).update(accepted=True)
            else:
                Invitation.objects.filter(email=user.email).update(accepted=True)

            registered = True

        else:
            print(user_form.errors, doctor_form.errors)

    else:
        user_form = UserForm()
        doctor_form = DoctorForm()

    return render(request, 'userprofile/register.html', locals())
Esempio n. 9
0
def register(request):

    registered = False
    if request.method == 'POST':
        user_form = UserForm(data=request.POST)
        profile_form = UserProfileForm(data=request.POST)
        if user_form.is_valid() and profile_form.is_valid():
            user = user_form.save()
            user.set_password(user.password)
            user.save()
            profile = profile_form.save(commit=False)
            profile.user = user
            profile.save()
            registered = True
        else:
            print(user_form.errors, profile_form.errors)
    else:
        user_form = UserForm()
        profile_form = UserProfileForm()
    return render(
        request, 'snatch/register.html', {
            'user_form': user_form,
            'profile_form': profile_form,
            'registered': registered
        })
Esempio n. 10
0
def register(request):
    registered = False
    if request.method == 'POST':
        user_form = UserForm(data=request.POST)
        profile_form = UserProfileInfoForm(data=request.POST)
        if user_form.is_valid() and profile_form.is_valid():
            user = user_form.save()
            user.set_password(user.password)
            user.save()
            profile = profile_form.save(commit=False)
            profile.user = user
            if 'profile_pic' in request.FILES:
                print('found it')
                profile.profile_pic = request.FILES['profile_pic']
            profile.save()
            registered = True
        else:
            print(user_form.errors,profile_form.errors)
    else:
        user_form = UserForm()
        profile_form = UserProfileInfoForm()
    return render(request,'userprofile/registration.html',
                          {'user_form':user_form,
                           'profile_form':profile_form,
                           'registered':registered})
Esempio n. 11
0
def update_profile(request):
    data = {}
    if request.POST:
        try:
            userprofile_form = UserProfileForm(request.POST, request.FILES, prefix='userprofile_form', instance=request.user.userprofile)
        except ObjectDoesNotExist:
            userprofile_form = UserProfileForm(request.POST, request.FILES, prefix='userprofile_form')
        user_form = UserForm(request.POST, request.FILES, prefix='user_form', instance=request.user)
        if all([userprofile_form.is_valid(), user_form.is_valid()]):
            user = user_form.save()
            profile = userprofile_form.save(commit=False)
            profile.user = user
            print userprofile_form
            profile.save()
            return redirect("update_profile")
    else:
        user_form = UserForm(instance=request.user, prefix='user_form')
        try:
            userprofile_form = UserProfileForm(prefix='userprofile_form', instance=request.user.userprofile)
        except ObjectDoesNotExist:
            userprofile_form = UserProfileForm(prefix='userprofile_form')
    data['userprofile_form'] = userprofile_form
    data['user_form'] = user_form
    return render(request, "user_profile.html", data)
Esempio n. 12
0
def ProfileEdit(request, pk=None, template_name='profile/profile_form.html'):
    user = request.user
    profile = request.user.profile
    if request.user.id == profile.user_id:  #elenxos gia to an to id tou profile einai tou xristi pou kanei request
        user_form = UserForm(
            request.POST or None, instance=request.user
        )  # xreaizete to or non edw gia na fanous ta dedomena stin forma
        profile_form = ProfileEditForm(request.POST or None,
                                       instance=request.user.profile)
        if request.method == "POST":
            if user_form.is_valid() and profile_form.is_valid():
                profile_form.save()
                user_form.save()

                # Save was successful, so redirect to another page

                return HttpResponseRedirect(reverse('home'))
    else:
        raise PermissionDenied

    return render(request, template_name, {
        'user_form': user_form,
        'profile_form': profile_form
    })
Esempio n. 13
0
def create_account(request):
    """Yet another way to create an account."""
    if request.method == "POST":
        form = UserForm(request.POST)
        password_form = SetNewPasswordForm(request.POST, prefix="pw")
        if form.is_valid() and password_form.is_valid():
            User = get_user_model()
            email = form.cleaned_data['email'].strip().lower()

            try:
                # Ensure the email isn't already tied to an account
                user = User.objects.get(email__iexact=email)
                messages.info(
                    request, "It looks like you already have an "
                    "account! Log in to continue.")
                return redirect("officehours:login")
            except User.DoesNotExist:
                # Create & activate the account
                # XXX This is a hack to keep these users from getting the
                # XXX `selected_by_default` content from the `goals` app.
                # XXX We *must* set this before we craete the user, hence the
                # XXX use of the email in the key.
                _key = "omit-default-selections-{}".format(slugify(email))
                cache.set(_key, True, 30)

                user = form.save(commit=False)
                user.is_active = True
                user.username = username_hash(email)
                user.set_password(password_form.cleaned_data['password'])
                user.save()

                # Set their IP address.
                user.userprofile.ip_address = get_client_ip(request)
                user.userprofile.save()

                user = authenticate(
                    email=email,
                    password=password_form.cleaned_data['password'])
                login_user(request, user)
                return redirect("officehours:index")
        else:
            messages.error(
                request, "We could not process your request. "
                "Please see the details, below.")
    else:
        password_form = SetNewPasswordForm(prefix='pw')
        form = UserForm()

    context = {
        'form': form,
        'password_form': password_form,
    }
    return render(request, "officehours/create_account.html", context)
Esempio n. 14
0
    def get(self, request, *arg, **kwarg):
        pk = self.kwargs.get('pk')
        instance = None
        profile = None
        coop_admin = None
        if pk:
            user = User.objects.get(pk=pk)
            if user:
                instance = user
                profile = instance.profile
                if hasattr(instance, 'cooperative_admin'):
                    coop_admin = instance.cooperative_admin
                
        user_form = UserForm(instance=instance)
        profile_form = UserProfileForm(instance=profile)

        data = {'user_form': user_form, 'profile_form': profile_form}
        return render(request, self.template_name, data)
Esempio n. 15
0
def addinfo(request):
    if request.method == "POST":
        user_form = UserForm(request.POST, instance=request.user)
        profile_form = ProfileForm(request.POST, instance=request.user.profile)
        if user_form.is_valid() and profile_form.is_valid():
            profileform = profile_form.save(commit=False)
            profileform.addinfoflag = True
            profileform.save()
            user_form.save()

            #return redirect('home')# HttpResponseRedirect can accept a model, view, or url as it's "to" argument. So it is a little more flexible in what it can "redirect" to.
            return HttpResponseRedirect(reverse('home'))
    else:
        user_form = UserForm()
        profile_form = ProfileForm()
        #else:
        #raise PermissionDenied

    return render(request, 'profile/profile_form.html', {
        'user_form': user_form,
        'profile_form': profile_form
    })
Esempio n. 16
0
def userprofile(request):
    # update user profile submit
    if request.method == 'POST':
        user_form = UserForm(request.POST, instance=request.user)
        user_profile = UserProfileForm(request.POST, request.FILES, instance=request.user.profile)
        if user_form.is_valid() and user_profile.is_valid():
            user_form.save()
            user_profile.save()
            return HttpResponseRedirect(reverse('profile:user'))
    else:
        # shows form with user profile's details
        user_form = UserForm(instance=request.user,
            initial={
                'first_name': request.user.first_name,
                'last_name': request.user.last_name,
                'email': request.user.email,
            })
        user = request.user
        profile = user.profile
        user_profile = UserProfileForm(instance=profile)
    

    return render(request, 'userprofile/profile.html', {'user_form': user_form, 'user_profile': user_profile})
Esempio n. 17
0
def edit_user(request, profile_id):
    user = User.objects.get(pk=request.user.id)
    user_form = UserForm(instance=user)

    ProfileInlineFormset = inlineformset_factory(User, UserProfile, fields=(
        'middle_name',
        'phone_number',
        'about',
        'avatar'),
                                                 widgets={
                                                     'middle_name': forms.TextInput(
                                                         attrs={'class': 'form-control', 'required': ''}),
                                                     'phone_number': forms.TextInput(
                                                         attrs={'class': 'form-control', 'required': ''}),
                                                     'about': forms.TextInput(
                                                         attrs={'class': 'form-control', 'required': ''}),
                                                 })
    formset = ProfileInlineFormset(instance=user)

    if request.user.is_authenticated() and request.user.id == user.id:
        if request.method == "POST":
            user_form = UserForm(request.POST, request.FILES, instance=user)
            formset = ProfileInlineFormset(request.POST, request.FILES, instance=user)

            if user_form.is_valid():
                created_user = user_form.save(commit=False)
                formset = ProfileInlineFormset(request.POST, request.FILES, instance=created_user)
                if formset.is_valid():
                    created_user.save()
                    formset.save()
                    return redirect('user_detail', user_id=request.user.id)

        return render(request, "blog/edit_profile.html", {
            "noodle": profile_id,
            "noodle_form": user_form,
            "formset": formset,
        })
    else:
        raise PermissionDenied
Esempio n. 18
0
def signup(request, content_viewer=False, enduser=False):
    """This view handles user account creation. There are different scenarios
    for different types of users, as indicated by the keyword arguments to
    this function:

    - content_viewer: If True, the account will be created as a content viewer
      (ie. a user who may need access to the editing tools at some point). This
      user account will be automatically activated, logged in, and added to
      some groups.

        /utils/signup/

    - enduser: If True, the account will be created as if the user intends to
      download and use the mobile app. Their account will be created, and the
      user will be redirected to links to the mobile app(s).

        /join/

    For Endusers: The request may also include one or more parameters indicating
    the Organization & Program in which the user should be a member. For
    example: `/join/?organization=42&program=7`

        - Organization ID: The user will be added as a member of the specified
          organization.
        - Program ID: The user will be added as a member of the specified
          program and will be auto-enrolled in certain goals from the program

    """
    organization = get_object_or_none(Organization,
                                      pk=request.GET.get('organization'))
    program = get_object_or_none(Program, pk=request.GET.get('program'))

    # Stash these in a session for later... (see `confirm_join`).
    if organization or program:
        request.session['organization'] = organization.id if organization else None
        request.session['program'] = program.id if program else None

    # Set the template/redirection based on the type of user signup
    if enduser:
        template = 'utils/signup_enduser.html'
        redirect_to = 'join'
        login_url = "{}?next={}".format(reverse('login'), reverse('utils:confirm'))
    else:
        template = 'utils/signup_content_viewer.html'
        redirect_to = '/'
        login_url = "{}".format(reverse('login'))

    if request.method == "POST":
        form = UserForm(request.POST)
        password_form = SetNewPasswordForm(request.POST, prefix="pw")
        if form.is_valid() and password_form.is_valid():
            User = get_user_model()
            try:
                # Ensure the email isn't already tied to an account
                u = User.objects.get(email=form.cleaned_data['email'])
                messages.info(request, "It looks like you already have an "
                                       "account! Log in to continue.")
                return redirect(login_url)
            except User.DoesNotExist:
                # Create & activate the account, and do initial record-keeping
                u = form.save(commit=False)
                u.is_active = True
                u.username = username_hash(u.email)
                u.set_password(password_form.cleaned_data['password'])
                u.save()

                # Set their IP address.
                u.userprofile.ip_address = get_client_ip(request)
                u.userprofile.save()

                if content_viewer:
                    password = password_form.cleaned_data['password']
                    _setup_content_viewer(request, u, password)

                if enduser:
                    _setup_enduser(request, u)
                    redirect_to = reverse(redirect_to) + "?c=1"

                return redirect(redirect_to)
        else:
            messages.error(request, "We could not process your request. "
                                    "Please see the details, below.")
    elif enduser and request.user.is_authenticated():
        # Redirect to the confirmation page.
        return redirect(reverse("utils:confirm"))
    else:
        password_form = SetNewPasswordForm(prefix='pw')
        if organization:
            form = UserForm(for_organization=organization.name)
        elif program:
            form = UserForm(for_organization=program.organization.name)
        else:
            form = UserForm()

    # The following is a list of GET request variables that we'll pass along
    # as POST request vars once a user submits the login form.
    passthru_vars = ['organization', 'program']
    passthru_vars = {
        key: request.GET.get(key) for key in passthru_vars
        if request.GET.get(key)
    }

    context = {
        'organization': organization,
        'program': program,
        'passthru_vars': passthru_vars,
        'form': form,
        'password_form': password_form,
        'completed': bool(request.GET.get("c", False)),
        'android_url': settings.PLAY_APP_URL,
        'ios_url': settings.IOS_APP_URL,
        'login_url': login_url,
    }
    return render(request, template, context)
Esempio n. 19
0
def userprofile_register(request):
    # Like before, get the request's context.
    context = RequestContext(request)

    # A boolean value for telling the template whether the registration was successful.
    # Set to False initially. Code changes value to True when registration succeeds.
    registered = False

    # If it's a HTTP POST, we're interested in processing form data.
    if request.method == 'POST':
        # Attempt to grab information from the raw form information.
        # Note that we make use of both UserForm and UserProfileForm.

        data_with_username = request.POST
        data_with_username['username'] = data_with_username['email']
        user_form = UserForm(data=data_with_username)
        profile_form = UserProfileForm(data=data_with_username)

        # If the two forms are valid...
        if user_form.is_valid() and profile_form.is_valid():
            # Save the user's form data to the database.
            user = user_form.save()
            user.is_staff = True

            #my stuff

            #g = Group.objects.get(name='normal_users')
            #g.user_set.add(user)


            # Now we hash the password with the set_password method.
            # Once hashed, we can update the user object.
            user.set_password(user.password)
            user.save()

            # Now sort out the UserProfile instance.
            # Since we need to set the user attribute ourselves, we set commit=False.
            # This delays saving the model until we're ready to avoid integrity problems.
            profile = profile_form.save(commit=False)
            profile.user = user

            # Did the user provide a profile picture?
            # If so, we need to get it from the input form and put it in the UserProfile model.
            if 'picture' in request.FILES:
                profile.picture = request.FILES['picture']

            # Now we save the UserProfile model instance.
            profile.save()

            # Update our variable to tell the template registration was successful.
            registered = True

        # Invalid form or forms - mistakes or something else?
        # Print problems to the terminal.
        # They'll also be shown to the user.
        else:
            user_form.errors, profile_form.errors
            #CHECK: had print next to above line

    #------------ log em in---

        email = request.POST['email']
        password = request.POST['password']
        user = authenticate(email=email, password=password)
        if user:
            # Is the account active? It could have been disabled.
            if user.is_active:
                # If the account is valid and active, we can log the user in.
                # We'll send the user back to the homepage.
                login(request, user)

    #-------------------------

    # Not a HTTP POST, so we render our form using two ModelForm instances.
    # These forms will be blank, ready for user input.
    else:
        user_form = UserForm()
        profile_form = UserProfileForm()


    # Render the template depending on the context.
    return render_to_response(
            'userprofile_register.html',
            {'user_form': user_form, 'profile_form': profile_form, 'registered': registered},
            context)
Esempio n. 20
0
def register(request):

    # create flag for successful registration
    registered = False

    # if submitted, process form
    if request.method == 'POST':

        # grab information from forms
        user_form = UserForm(data=request.POST)
        profile_form = UserProfileForm(data=request.POST)
        payment_form = PaymentForm(data=request.POST)

        # if those are valid, continue
        if user_form.is_valid() and profile_form.is_valid(
        ) and payment_form.is_valid():

            # save user form to database
            user = user_form.save()

            # hash password and send to user object
            user.set_password(user.password)

            # save user
            user.save()

            # prepare userprofile form
            profile = profile_form.save(commit=False)

            # connect userprofile with user
            profile.user = user

            # if profile picture provided, save it
            if 'picture' in request.FILES:
                profile.picture = request.FILES['picture']

            # save userprofile
            profile.save()

            # Do same thing for payment as profile
            payment = payment_form.save(commit=False)
            payment.user = user
            payment.save()

            # flag successful registration
            registered = True

        # else forms invalid, print errors
        else:
            print(user_form.errors, profile_form.errors)

    # else show the registration form
    else:
        user_form = UserForm()
        profile_form = UserProfileForm()
        payment_form = PaymentForm()

    # Render the template depending on the context.
    return render(
        request, 'userprofile/register.html', {
            'user_form': user_form,
            'profile_form': profile_form,
            'payment_form': payment_form,
            'registered': registered
        })