コード例 #1
0
def signup(request):
    if not request.user.is_authenticated:
        if request.method == 'POST':
            form = SignUpForm(request.POST)
            profile_form = ProfileForm(request.POST)

            if form.is_valid() and profile_form.is_valid():
                form.save()
                user_name = form.cleaned_data['username']
                profile_form.save(user_name)
                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('/accounts')
        else:
            form = SignUpForm()
            profile_form = ProfileForm()

        return render(request, 'accounts/signup.html', {
            'form': form,
            'profile_form': profile_form
        })
    else:
        return redirect('/accounts')
コード例 #2
0
ファイル: views.py プロジェクト: joskid/snippify
def edit(request):
    """ Update UserProfile """

    if request.method == 'POST':
        form = ProfileForm(request.POST,
                           instance=UserProfile.objects.get(user=request.user))
        if form.is_valid(): # All validation rules pass
            try:
                User.objects.filter(email=form.cleaned_data['email']).\
                exclude(pk=request.user.pk).get()
                request.session['flash'] = ['This e-mail is already in use',
                                            'error']
                return HttpResponseRedirect(
                    request.META.get('HTTP_REFERER', '/'))
            except User.DoesNotExist:#Check if the e-mail is not already in use
                pass
            request.user.email = form.cleaned_data['email']
            request.user.save()
            form.save()
            request.session['flash'] = ['Your profile has been updated',
                                        'success']
            return HttpResponseRedirect(request.META.get('HTTP_REFERER', '/'))
    else:
        form = ProfileForm(instance=UserProfile.objects.get(user=request.user),
                           initial = {'email': request.user.email})
    return render_to_response('accounts/edit.html', {'form': form},
                              context_instance=build_context(request))
コード例 #3
0
def edit_profile(request):
    user = get_object_or_404(User, username=request.user.username)
    if request.method == 'GET':
        user_form = UserForm(instance=user)
        profile_form = ProfileForm(instance=user.userprofile)
        equipment_form = EquipmentForm()
        context = {
            'user_form': user_form,
            'profile_form': profile_form,
            'equipment_form': equipment_form,
        }
        return render(request, 'accounts/profile_form.html', context)
    if request.method == 'POST':
        user_form = UserForm(request.POST, instance=user)
        profile_form = ProfileForm(request.POST, instance=user.userprofile)
        equipment_form = EquipmentForm(request.POST)
        if user_form.is_valid() and profile_form.is_valid():
            user_form.save()
            profile_form.save()
            del (request.session['django_timezone'])
            messages.success(request, "Profile sucessfully updated")
            return redirect('profile', username=user.username)
        else:
            return render(
                request, 'accounts/profile_form.html', {
                    'user_form': user_form,
                    'profile_form': profile_form,
                    'equipment_form': equipment_form
                })
コード例 #4
0
ファイル: views.py プロジェクト: zouyapeng/WebTerminal
 def post(self, request, *args, **kwargs):
     form = ProfileForm(request.POST, request.FILES)
     if form.is_valid():
         form.save()
         return self.form_valid(form)
     else:
         return self.form_invalid(form)
コード例 #5
0
ファイル: views.py プロジェクト: Lomien007/memberportal
def edit(request,
         template_name='edit_profile.html',
         redirect_to='auth_profile'):

    form = ProfileForm(request.POST, instance=request.user.get_profile())
    if request.POST:
        if form.is_valid():
            form.save()
            u = request.user
            u.email = form.data['email']
            u.first_name = form.data['first_name']
            u.last_name = form.data['last_name']
            u.save()
        else:
            return render_to_response(template_name, {'form': form},
                                      context_instance=RequestContext(request))

        return HttpResponseRedirect(reverse(redirect_to))

    else:
        initial_dict = {
            'email': request.user.email,
            'username': request.user.username,
            'first_name': request.user.first_name,
            'last_name': request.user.last_name
        }

        form = ProfileForm(instance=request.user.get_profile(),
                           initial=initial_dict)

        return render_to_response(template_name, {'form': form},
                                  context_instance=RequestContext(request))
コード例 #6
0
ファイル: views.py プロジェクト: opena11y/fae1-django
def my_account(request):
    user_data = {
        'first_name': request.user.first_name,
        'last_name': request.user.last_name,
        'email': request.user.email
    }

    try:
        profile_obj = request.user.get_profile()
    except ObjectDoesNotExist:
        profile_obj = UserProfile(user=request.user, acct_type=1)

    if request.method == 'POST':
        user_form = UserForm(request.POST, instance=request.user)
        profile_form = ProfileForm(request.POST, instance=profile_obj)
        if user_form.is_valid() and profile_form.is_valid():
            user_form.save()
            profile_form.save()
            return HttpResponseRedirect('/')
    else:
        user_form = UserForm(initial=user_data)
        profile_form = ProfileForm(initial=get_profile_data(profile_obj))

    context = {
        'title': labels['profile'],
        'username': request.user.username,
        'user_form': user_form,
        'profile_form': profile_form,
    }

    # Return response
    t = get_template('my_account.html')
    html = t.render(RequestContext(request, context))
    return HttpResponse(html)
コード例 #7
0
def edit_profile(request):
    '''
	'''
    user = request.user
    form = ProfileForm()
    if request.method == "POST":
        form = ProfileForm(request.POST, request.FILES)
        if form.is_valid():
            data = form.cleaned_data
            '''
			if len(data['name']) > NAME_MAX_LEN * 3:
				messages.warning(request, u'名号输入过长,被自动截断')
			if len(data['signature']) > SIGNATURE_MAX_LEN * 3:
				messages.warning(request, u'签名输入过长,被自动截断')
			'''
            form.save(user.userprofile, data)
            messages.success(request, u'个人资料修改成功')
        else:
            messages.error(request, u'你的输入有误')
    profile = request.user.userprofile
    return render_to_response('settings/edit_profile.html', {
        'time_limit': PROFILE_NAME_CHANGE_DAYS,
        'form': form,
        'name': profile.name,
        'website': profile.website,
        'signature': profile.signature,
        'detail': profile.detail,
    },
                              context_instance=RequestContext(request))
コード例 #8
0
ファイル: views.py プロジェクト: svigote/modoboa
def profile(request, tplname='userprefs/profile.html'):
    update_password = True
    if True in events.raiseQueryEvent("PasswordChange", request.user):
        update_password = False

    if request.method == "POST":
        form = ProfileForm(update_password,
                           request.POST,
                           instance=request.user)
        if form.is_valid():
            form.save()
            if update_password and form.cleaned_data["confirmation"] != "":
                request.session["password"] = encrypt(
                    form.cleaned_data["confirmation"])
            return ajax_simple_response(
                dict(status="ok", respmsg=_("Profile updated")))
        return ajax_simple_response({"status": "ko", "errors": form.errors})

    form = ProfileForm(update_password, instance=request.user)
    return ajax_simple_response({
        "status":
        "ok",
        "content":
        _render_to_string(request, tplname, {"form": form})
    })
コード例 #9
0
ファイル: views.py プロジェクト: hackerspace/memberportal
def edit(request, template_name='edit_profile.html',
    redirect_to='auth_profile'):

    form = ProfileForm(request.POST, instance=request.user.get_profile())
    if request.POST:
        if form.is_valid():
            form.save()
            u = request.user
            u.email = form.data['email']
            u.first_name = form.data['first_name']
            u.last_name = form.data['last_name']
            u.save()
        else:
            return render_to_response(template_name, {'form': form},
                context_instance=RequestContext(request))

        return HttpResponseRedirect(reverse(redirect_to))

    else:
        initial_dict = {'email': request.user.email,
            'username': request.user.username,
            'first_name': request.user.first_name,
            'last_name': request.user.last_name}

        form = ProfileForm(instance=request.user.get_profile(),
            initial=initial_dict)

        return render_to_response(template_name, {'form': form},
            context_instance=RequestContext(request))
コード例 #10
0
ファイル: views.py プロジェクト: readingr/provenance
def registration(request):
    if(request.user.is_authenticated()):
        return redirect(list_bundles)
    
    if request.method == 'POST':
        form = ProfileForm(request.POST)
        if form.is_valid():
            form.save()
            user = authenticate(username=form.cleaned_data['username'], password=form.cleaned_data['password'])
            login(request,user)
            messages.success(request, 'You have successfully registered!')
            if form.data['next']:
                return redirect(form.data['next'])
            return redirect('/')
        else:
            for error in form.non_field_errors():
                messages.error(request,error)
            return render_to_response('server/register.html',{'form': form, 'next': form.data['next']}, 
                                      context_instance=RequestContext(request))
            
    form = ProfileForm()
    if 'next' in request.GET:
        next_page = request.GET['next']
    else:
        next_page = ''
    return render_to_response('server/register.html', {'form': form, 'next': next_page}, 
                              context_instance=RequestContext(request))
コード例 #11
0
ファイル: views.py プロジェクト: adamfeuer/ArtOfGratitude_app
def activate(request, activation_key,
             template_name='userena/activate_fail.html',
             extra_context=None):
   """
   Activate a user with an activation key.
   """
   user = UserenaSignup.objects.activate_user(activation_key)
   if user:
      # Sign the user in.
      auth_user = authenticate(identification=user.username,
                               check_password=False)
      UserDetail.set_activation_datetime(auth_user)
      login(request, auth_user)
      if userena_settings.USERENA_USE_MESSAGES:
          messages.success(request, _('Congratulations -- your Art of Gratitude account is confirmed!'),
                           fail_silently=True)
      if request.method == 'POST':
         form = ProfileForm(request.POST, user=user)
         if form.is_valid():
            form.save()
      redirect_to = settings.LOGIN_REDIRECT_URL % {'username': user.username }
      return redirect(redirect_to)
   else:
      if not extra_context: extra_context = {}
      return ExtraContextTemplateView.as_view(template_name=template_name,
                                            extra_context=extra_context)(request)
コード例 #12
0
ファイル: views.py プロジェクト: hisoka999/silverbb
def base_profile(request):
    f_password = forms.PasswordChangeForm(request.POST)
    f_profile = ProfileForm(instance=request.user.profile)
    f_user = UserEditForm(instance=request.user)
    commit = False
    if request.method == "POST":
        f_profile = ProfileForm(request.POST, request.FILES, instance=request.user.profile)
        f_user = UserEditForm(request.POST, request.FILES, instance=request.user)
        if f_password.is_valid():
            f_password.save(commit=True)
            # handle_uploaded_file(request.FILES['avatar'])
            f_profile.save(commit=True)
            commit = True
        if f_profile.is_valid():
            f_profile.save(commit=True)
            # handle_uploaded_file(request.FILES['avatar'])
            commit = True
        if f_user.is_valid():
            user = f_user.save(commit=True)
            commit = True
    return render_to_response(
        "user/profile.html",
        {"profile": f_profile, "f_pw": f_password, "f_user": f_user, "commit": commit},
        context_instance=RequestContext(request),
    )
コード例 #13
0
ファイル: views.py プロジェクト: tulsawebdevs/ottozen
def old_profile(request):
    try:
        profile = request.user.get_profile()
    except UserProfile.DoesNotExist:
        profile = UserProfile.objects.create(user=request.user)
    if request.method == 'POST':
        data = {
            'user': request.user.id,
            'home_address': request.POST['home_address'],
            'home_city': request.POST['home_city'],
            'mobile_num': request.POST['mobile_num']
        }
        form = ProfileForm(data, instance=profile)
        print request.POST
        print form.is_valid()
        print form.errors
        if form.is_valid():
            print 'valid!'
            form.save()
    else:
        form = ProfileForm(instance=profile)

    commutes = Commute.objects.filter(user=request.user)
    profile = request.user.get_profile()

    return render(request, 'users/profile.html', {
        'commutes': commutes,
        'profile': profile,
        'form': form
    })
コード例 #14
0
ファイル: views.py プロジェクト: rushil02/Vidzert
def update_profile(request):
    try:
        promoter = request.user.promoterprofile
    except PromoterProfile.DoesNotExist:
        error_meta = {
            "method": "promoter.views.update_profile",
        }
        ErrorLog.objects.create_log(4, "Promoter Object Error", error_meta,
                                    request)
        raise SuspiciousOperation('Error Code: 4')
    form = ProfileForm(request.POST or None, instance=promoter)
    context = {"form": form}
    if request.POST:
        if form.is_valid():
            form.save()
            activity_meta = {
                "method": "promoter.views.update_profile",
                "form_validation": "True"
            }
            ActivityLog.objects.create_log(request, "Update Promoter Account",
                                           activity_meta)
            return redirect('/pr/account/')
        else:
            return render(request, "promoter/edit_profile.html", context)
    else:
        activity_meta = {
            "method": "promoter.views.update_profile",
        }
        ActivityLog.objects.create_log(request, "Update Promoter Account",
                                       activity_meta)
        return render(request, "promoter/edit_profile.html", context)
コード例 #15
0
ファイル: views.py プロジェクト: yusufdemir/newblog
def getProfile(request):
    # get user profile
    user = request.user
    profile = user.get_profile()

    if request.method == 'POST':
        profile_form = ProfileForm(request.POST,
                                   request.FILES,
                                   instance=profile)

        user_form = UserForm(request.POST,
                             instance=request.user)
        if profile_form.is_valid() and user_form.is_valid():

            profile_form.save()
            user_form.save()

            resize_post_image.delay(profile_form.save())
            messages.success(request, _("Profile updated succesfully."))
            return redirect('index')
    else:
        profile_form = ProfileForm(instance=profile)
        user_form = UserForm(instance=request.user)

    return render(request, 'account/profile.html', {
        'formProfile': profile_form,
        'formUser': user_form
    })
コード例 #16
0
def personal(request):
    """
    Personal data of the user profile
    """
    if (request.user.password == "!"):
        return HttpResponseRedirect('/accounts/social')

    profile, created = Profile.objects.get_or_create(user=request.user)

    if request.method == "POST":
        form = ProfileForm(request.POST, instance=profile)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect(reverse("profile_edit_personal_done"))
    else:
        form = ProfileForm(instance=profile)

    template = "userprofile/profile/personal.html"
    data = {
        'section': 'personal',
        'GOOGLE_MAPS_API_KEY': GOOGLE_MAPS_API_KEY,
        'form': form,
    }
    return render_to_response(template,
                              data,
                              context_instance=RequestContext(request))
コード例 #17
0
ファイル: views.py プロジェクト: haipome/Newsnavig
def edit_profile(request):
	'''
	'''
	user = request.user
	form = ProfileForm()
	if request.method == "POST":
		form = ProfileForm(request.POST, request.FILES)
		if form.is_valid():
			data = form.cleaned_data
			'''
			if len(data['name']) > NAME_MAX_LEN * 3:
				messages.warning(request, u'名号输入过长,被自动截断')
			if len(data['signature']) > SIGNATURE_MAX_LEN * 3:
				messages.warning(request, u'签名输入过长,被自动截断')
			'''
			form.save(user.userprofile, data)
			messages.success(request, u'个人资料修改成功')
		else:
			messages.error(request, u'你的输入有误')
	profile = request.user.userprofile
	return render_to_response('settings/edit_profile.html', 
	                         {'time_limit': PROFILE_NAME_CHANGE_DAYS,
	                          'form': form,
	                          'name': profile.name,
	                          'website': profile.website,
	                          'signature': profile.signature,
	                          'detail': profile.detail,
	                          },
	                           context_instance=RequestContext(request))
コード例 #18
0
ファイル: views.py プロジェクト: Tdey/modoboa
def profile(request, tplname='userprefs/profile.html'):
    update_password = True
    if True in events.raiseQueryEvent("PasswordChange", request.user):
        update_password = False

    if request.method == "POST":
        form = ProfileForm(
            update_password, request.POST, instance=request.user
        )
        if form.is_valid():
            form.save()
            if update_password and form.cleaned_data["confirmation"] != "":
                request.session["password"] = encrypt(form.cleaned_data["confirmation"])
            return ajax_simple_response(dict(
                status="ok", respmsg=_("Profile updated")
            ))
        return ajax_simple_response({
            "status": "ko",
            "errors": form.errors
        })

    form = ProfileForm(update_password, instance=request.user)
    return ajax_simple_response({
        "status": "ok",
        "content": _render_to_string(request, tplname, {
            "form": form
        })
    })
コード例 #19
0
def update_profile(request):
    if request.method == 'POST':
        member_form = MemberForm(request.POST)
        if not is_member(request.user):
            if member_form.is_valid(
            ) and member_form.cleaned_data['becomeMember']:
                group_name = models.SchoolYear.objects.current(
                ).get_member_group()
                g = Group.objects.get(name=group_name)
                g.user_set.add(request.user)
        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():
            user_form.save()
            profile_form.save()
            messages.success(request, 'Your profile was successfully updated!')
            return redirect('/profile')
        else:
            messages.error(request, 'Please correct the error below.')
    else:
        member_form = MemberForm()
        user_form = UserForm(instance=request.user)
        profile_form = ProfileForm(instance=request.user.profile)
    return render(
        request, 'profile.html', {
            'member_form': member_form,
            'user_form': user_form,
            'profile_form': profile_form,
            'school_year': models.SchoolYear.objects.current()
        })
コード例 #20
0
ファイル: views.py プロジェクト: recoded-co/auth_page
def profile(request):
    """
    Form for modifying and adding profile values
    """
    if request.method == 'POST':
        form = ProfileForm(request.POST,
                           instance = request.user)
        
        email = request.POST.get('email', '')
        if not email == '' and not email == request.user.email:
            #confirm the email
            salt = sha_constructor(str(random())).hexdigest()[:5]
            confirmation_key = sha_constructor(salt + email).hexdigest()
            current_site = Site.objects.get_current()
       
            path = reverse('confirm_email',
                            args=[confirmation_key])
                
            activate_url = u"http://%s%s" % (unicode(current_site.domain),
                                             path)
            context = {
                "user": request.user,
                "activate_url": activate_url,
                "current_site": current_site,
                "confirmation_key": confirmation_key,
            }
            subject = render_to_string(
                "email_confirmation_subject.txt",
                context)
        
            # remove superfluous line breaks
            subject = "".join(subject.splitlines())
            message = render_to_string(
                "email_confirmation_message.txt",
                context)
            print email
            send_mail(subject,
                      message,
                      getattr(settings,
                              'DEFAULT_FROM_EMAIL',
                              'do-not-reply@%s' % current_site),
                      [email])
        
            Email.objects.create(
                owner = request.user,
                email = email,
                email_is_verified = False,
                sent = datetime.now(),
                confirmation_key = confirmation_key)
        
        form.save()
        return HttpResponseRedirect(request.POST.get('next', '/'))

    else:
        form = ProfileForm(instance = request.user)
        next = request.GET.get('next', '/')
        return render_to_response('profile.html',
                                  {'form': form,
                                   'next': next},
                                  context_instance = RequestContext(request))
コード例 #21
0
ファイル: views.py プロジェクト: rushil02/Vidzert
def update_profile(request):
    try:
        promoter = request.user.promoterprofile
    except PromoterProfile.DoesNotExist:
        error_meta = {
            "method": "promoter.views.update_profile",
        }
        ErrorLog.objects.create_log(4, "Promoter Object Error", error_meta, request)
        raise SuspiciousOperation('Error Code: 4')
    form = ProfileForm(request.POST or None, instance=promoter)
    context = {
        "form": form
    }
    if request.POST:
        if form.is_valid():
            form.save()
            activity_meta = {
                "method": "promoter.views.update_profile",
                "form_validation": "True"
            }
            ActivityLog.objects.create_log(request, "Update Promoter Account", activity_meta)
            return redirect('/pr/account/')
        else:
            return render(request, "promoter/edit_profile.html", context)
    else:
        activity_meta = {
            "method": "promoter.views.update_profile",
        }
        ActivityLog.objects.create_log(request, "Update Promoter Account", activity_meta)
        return render(request, "promoter/edit_profile.html", context)
コード例 #22
0
ファイル: views.py プロジェクト: akatsoulas/wearitproudly
def edit_user(request):
    profile_form = ProfileForm(request.POST, instance=request.user)
    if profile_form.is_valid():
        profile_form.save()
        messages.success(request, 'Yup, changes made.')
    else:
        messages.error(request, 'Nop, something is wrong.')
    return redirect('view_user', request.user.id)
コード例 #23
0
ファイル: views.py プロジェクト: dafma/Frikr2
    def post(self, request, pk=None):
        if request.user.is_authenticated():
            user = Profile.objects.get_or_create(user=request.user)[0]
            form = ProfileForm(request.POST, request.FILES or None, instance=user)
            if form.is_valid():
                form.save()

        return redirect("profile")
コード例 #24
0
ファイル: views.py プロジェクト: ss2727/wearitproudly
def edit_user(request):
    profile_form = ProfileForm(request.POST, instance=request.user)
    if profile_form.is_valid():
        profile_form.save()
        messages.success(request, 'Yup, changes made.')
    else:
        messages.error(request, 'Nop, something is wrong.')
    return redirect('view_user', request.user.id)
コード例 #25
0
ファイル: views.py プロジェクト: cato-/django-feadme
def profile_edit(request):
    data = request.POST or None
    profile_form = ProfileForm(data, instance=request.user)
    if profile_form.is_valid():
        profile_form.save()
        messages.success(request, "Profile saved")
    elif not data is None:
        messages.error(request, "Profile could not be saved, because of invalid data")
    return render(request, "profiles/edit.html", {'form': profile_form})
コード例 #26
0
ファイル: views.py プロジェクト: nims11/Foo-Barketplace
def edit_profile(request, curr_user):
	"Edit Profile Page"
	if request.method == 'POST':
		form = ProfileForm(request.POST, instance=curr_user.user_obj)
		if form.is_valid():
			form.save()
			return render(request, 'edit_profile.html', {'form': form, 'saved': True, 'links': main.myprofile_links})
	else:
		form = ProfileForm(instance=curr_user.user_obj)
	return render(request, 'edit_profile.html', {'form': form, 'links': main.myprofile_links})
コード例 #27
0
ファイル: views.py プロジェクト: jpablonc94/aulaslimpias
    def post(self, request):
        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():
            user_form.save()
            profile_form.save()
            messages.success(request,
                             _('Your profile was successfully updated!'))
            return redirect('settings:profile')

        messages.error(request, _('Please correct the error below.'))
コード例 #28
0
def profile(request):
    """
    Form for modifying and adding profile values
    """
    if request.method == 'POST':
        form = ProfileForm(request.POST, instance=request.user)

        email = request.POST.get('email', '')
        if not email == '' and not email == request.user.email:
            #confirm the email
            salt = sha_constructor(str(random())).hexdigest()[:5]
            confirmation_key = sha_constructor(salt + email).hexdigest()
            current_site = Site.objects.get_current()

            path = reverse('confirm_email', args=[confirmation_key])

            activate_url = u"http://%s%s" % (unicode(
                current_site.domain), path)
            context = {
                "user": request.user,
                "activate_url": activate_url,
                "current_site": current_site,
                "confirmation_key": confirmation_key,
            }
            subject = render_to_string("email_confirmation_subject.txt",
                                       context)

            # remove superfluous line breaks
            subject = "".join(subject.splitlines())
            message = render_to_string("email_confirmation_message.txt",
                                       context)
            print email
            send_mail(
                subject, message,
                getattr(settings, 'DEFAULT_FROM_EMAIL',
                        'do-not-reply@%s' % current_site), [email])

            Email.objects.create(owner=request.user,
                                 email=email,
                                 email_is_verified=False,
                                 sent=datetime.now(),
                                 confirmation_key=confirmation_key)

        form.save()
        return HttpResponseRedirect(request.POST.get('next', '/'))

    else:
        form = ProfileForm(instance=request.user)
        next = request.GET.get('next', '/')
        return render_to_response('profile.html', {
            'form': form,
            'next': next
        },
                                  context_instance=RequestContext(request))
コード例 #29
0
ファイル: views.py プロジェクト: pysecl1/pyblog1
def profile(request):
    form=ProfileForm(instance=request.user.get_profile())
    if request.method=='POST':
        form=ProfileForm(instance=request.user.get_profile(), data=request.POST, files=request.FILES)
        if form.is_valid():
            print "VALID"
            form.save()
            return redirect ('/accounts/profile/')


    return render_to_response('sprof/profile.html',{'form':form}, context_instance=RequestContext(request))
コード例 #30
0
ファイル: views.py プロジェクト: devfest-ufrn/DogLove
def configuracoes(request):
    if request.method == 'POST':
        form = ProfileForm(request.POST, instance=request.user.profile)
        if form.is_valid():
            form.save()
            return redirect('principal')
        else:
            return redirect('configuracoes')
    else:
        form = ProfileForm(instance=request.user.profile)
        return render(request, 'configuracoes.html', {'form': form})
コード例 #31
0
ファイル: views.py プロジェクト: Heldroe/pyverts
def edit_profile(request):
    if request.method == 'POST':
        form = ProfileForm(request.POST, instance=request.user.get_profile())
        if form.is_valid():
            form.save()
    else:
        form = ProfileForm(instance=request.user.get_profile())

    return render_to_response('users/edit_profile.html',
            {'form': form},
            context_instance=RequestContext(request))
コード例 #32
0
ファイル: views.py プロジェクト: sanchitbareja/cetweb
def signup(request):
    form = ProfileForm()
    print form
    if request.method=="POST":
        print request.POST
        form = ProfileForm(request.POST)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect(reverse("dashboard"))
        else:
            print form.errors
    return render_to_response('profiles/signup.html', {'form': form}, context_instance=RequestContext(request))
コード例 #33
0
ファイル: views.py プロジェクト: mth2610/ewatec
def profile(request):
    if request.method == 'POST':
        form = ProfileForm(request.POST,request.FILES,instance=request.user.profile)
        print request.FILES
        if form.is_valid():
            form.save()
            return  HttpResponseRedirect('/auth/profile')
    else:
        form = ProfileForm()
    args = {}
    args.update(csrf(request))
    args['form'] = form
    return render_to_response('profile.html', args,context_instance=RequestContext(request))
コード例 #34
0
ファイル: views.py プロジェクト: beanmind/Soybean
def register(request):
    if "back_button_register" in request.POST:
        return HttpResponseRedirect('/login')
    elif len(request.POST)>0:
        form=ProfileForm(request.POST)
        if form.is_valid():
            form.save(commit=True)
            return HttpResponseRedirect('/login')
        else:
            return render(request, 'user_profile.html', {'ban':form})
    else:
        form = ProfileForm()
        return render(request, 'user_profile.html', {'ban':form})
コード例 #35
0
ファイル: views.py プロジェクト: arcalinea/possibility-space
def create_profile(request, args):
    user_id = request.user.id
    logging.debug("TEST CREATE PROFILE")
    profile = Profile.objects.get(id=user_id)
    if request.method == "POST":
        form = ProfileForm(request.POST, instance=profile)
        if form.is_valid():
            print "CREATE PROFILE FORM VALID"
            form.save()
            return HttpResponseRedirect('/participate/profile')
    else:
        form = ProfileForm(instance=profile)
        return render(request, 'accounts/create_profile.html', {'form': form})
コード例 #36
0
def my_profile(request):

    if request.method == "POST":
        form = ProfileForm(instance=request.user, data=request.POST)
        if form.is_valid():
            form.save()
            messages.success(request, "Your account is now up to date !")
    else:
        form = ProfileForm(instance=request.user)

    context = {}
    context.update({"form": form})
    return render(request, 'registration/my_profile.html', context)
コード例 #37
0
def register(request):
    if "back_button_register" in request.POST:
        return HttpResponseRedirect('/login')
    elif len(request.POST) > 0:
        form = ProfileForm(request.POST)
        if form.is_valid():
            form.save(commit=True)
            return HttpResponseRedirect('/login')
        else:
            return render(request, 'user_profile.html', {'ban': form})
    else:
        form = ProfileForm()
        return render(request, 'user_profile.html', {'ban': form})
コード例 #38
0
ファイル: stu.py プロジェクト: ihciah/xk-database
def profile():
    user = Student.query.get(g.user.username)
    if request.method == 'GET':
        return render_template('student/profile.html',user=user)
    form = ProfileForm(request.form)
    if form.validate():
        form.save()
        flash(u"资料成功更新!")
        user = Student.query.get(g.user.username)
        render_template('student/profile.html',user=user)
    for fieldName, errorMessages in form.errors.iteritems():
        for err in errorMessages:
            flash(err)
    return render_template('student/profile.html',user=user)
コード例 #39
0
def create_profile(request):
    if request.POST:
        profile_form = ProfileForm(request.POST)
        if profile_form.is_valid():
            profile_form.save()
            return HttpResponseRedirect('/articles/all')
    else:
        profile_form = ProfileForm()

    args = {}
    args.update(csrf(request))

    args['profile_form'] = profile_form
    return render_to_response('user_information.html', args)
コード例 #40
0
def profile():
    user = Student.query.get(g.user.username)
    if request.method == 'GET':
        return render_template('student/profile.html', user=user)
    form = ProfileForm(request.form)
    if form.validate():
        form.save()
        flash(u"资料成功更新!")
        user = Student.query.get(g.user.username)
        render_template('student/profile.html', user=user)
    for fieldName, errorMessages in form.errors.iteritems():
        for err in errorMessages:
            flash(err)
    return render_template('student/profile.html', user=user)
コード例 #41
0
ファイル: views.py プロジェクト: pkeeper/42-test-keeper
def edit_profile(request, template_name="profile_edit.html"):
    profile = get_object_or_404(Profile, pk=1)
    CFormSet = modelformset_factory(ContactField, can_delete=True,
                                           formset=ContactsFormSet,
                                           extra=2,
                                           fields=('uid', 'contact_type'))

    if request.method == 'POST':
        postdata = request.POST.copy()
        profile_form = ProfileForm(postdata, instance=profile)
        contact_forms = CFormSet(postdata, profile=profile)
        if request.is_ajax():
            # This is for formset validation if profile form is not valid
            contact_forms.is_valid()
            if profile_form.is_valid() and contact_forms.is_valid():
                # Save changes in forms
                profile_form.save()
                contact_forms.save()

                ret = {'status': 'ok'}
            else:
                ret = {
                    'status': 'fail',
                    'profile_errors': profile_form.errors,
                    'contacts_errors': contact_forms.errors,
                    'contacts_nonform_errors': contact_forms.non_form_errors(),
                }
            json = simplejson.dumps(ret)
            return HttpResponse(json, mimetype='application/json')

        else:
            # This is for formset validation if profile form is not valid
            contact_forms.is_valid()
            if profile_form.is_valid() and contact_forms.is_valid():
                # Save changes in forms
                profile_form.save()
                contact_forms.save()
                return HttpResponseRedirect(reverse('edit_profile'))
    else:
        profile_form = ProfileForm(instance=profile)
        contact_forms = CFormSet(profile=profile)

    context_dict = {
                    'profile_form': profile_form,
                    'contatcs_forms': contact_forms,
                   }

    return render_to_response(template_name,
                              context_dict,
                              context_instance=RequestContext(request))
コード例 #42
0
 def post(self, request):
     if not request.user.is_authenticated():
         return HttpResponseRedirect('/')
     profile = UserProfile.objects.get_or_create(user=request.user)[0]
     form = ProfileForm(self.request.POST, instance=profile)
     if form.is_valid():
         form.save()
         context = {'msg': 'Thank you for your support!',
                    'request': request}
         return self.render_to_response(context)
     else:
         context = self.get_context_data(request)
         context['form'] = form
         return self.render_to_response(context)
コード例 #43
0
def profile_form(request):
    if request.method == 'POST':
        if 'cancel' in request.POST:
            return redirect('/accounts/profile')

        user = User.objects.get(username=request.user.username)
        #post = request.POST.copy() # To keep Email Read-Only
        #post['email'] = user.email
        # and update original POST in the end
        #request.POST = post

        user_form = UserForm(request.POST, instance=user)
        if user_form.is_valid():
            user_form.save()
            try:
                profile_instance = Userprofile.objects.get(user_id=user.id)
            except Userprofile.DoesNotExist:
                profile_instance = Userprofile(user_id=user.id)

            user_profile_form = ProfileForm(request.POST,
                                            instance=profile_instance)
            if user_profile_form.is_valid():
                user_profile_form.save()
            return redirect('/accounts/profile')
    else:

        user_profile = _get_profile(request)
        print user_profile
        user_form = \
            UserForm(initial={'first_name': user_profile['first_name'],
                     'last_name': user_profile['last_name'], 'email':user_profile['email']})
        phone = ''
        address = ''
        if 'phone' in user_profile:
            phone = user_profile['phone']
        if 'address' in user_profile:
            address = user_profile['address']

        user_profile = \
            ProfileForm(initial={'phone': phone, 'address': address, } )
        return render(
            request,
            'profile_form.html',
            {
                'user_form': user_form,
                'user_profile': user_profile,
            },
        )
コード例 #44
0
def contact_edit(request, first_name, last_name):
    '''
    get contact page
    @param request:
    @param first_name: Profile.first_name
    @param last_name: Profile.last_name
    '''
    profile = get_object_or_404(Mybio, 
                                pk=1)

    if request.method == "POST":
        profile_form = ProfileForm(request.POST, instance=profile)
        if profile_form.is_valid():
            profile = profile_form.save()

    if request.method == "GET":
        profile_form = ProfileForm(instance=profile)

    return {
            "profile": profile,
            "profile_form": profile_form,
            "utility_links": ((reverse('profile-view',
                                      kwargs={"first_name": profile.first_name,
                                              "last_name": profile.last_name, }), 
                              _("View profile"),
                              {}),)}
コード例 #45
0
ファイル: views.py プロジェクト: erikahellquist/PLANtastic
def editInformation(request):
	if request.method == "POST":
		profileform = ProfileForm(request.POST, request.FILES, instance = request.user.profile)
		userform = UserForm(request.POST, instance = request.user)
		if userform.is_valid() and profileform.is_valid():
			avatar = profileform.cleaned_data['avatar']
			profileform.save()
			userform.save()
			profile = request.user.profile
			if avatar:
				profile.avatar = avatar
			profile.save()
			return HttpResponseRedirect(reverse('profile:manageAccount'))


	return HttpResponseRedirect(reverse('profile:manageAccount'))
コード例 #46
0
ファイル: views.py プロジェクト: jangau/online_library
def show_profile(request):
    authenticated = False
    if request.user.is_authenticated():
        authenticated = True
    try:
        profile_obj = Profile.objects.get(user=request.user)
    except:
        profile_obj = None

    form = ProfileForm(request.POST or None, instance=profile_obj)
    if request.method == 'POST':
        if form.is_valid():
            profile = form.save(commit=False)
            profile.user = request.user
            profile.save()

    borrowed_books = Borrow.objects.filter(
        user=request.user, date_return__gte=datetime.now().date())
    # TODO check if books are reserved
    # What do we do if they are reserved? Don't show extend? How? :)

    return render_to_response("profile.html",
                              context_instance=RequestContext(
                                  request, {
                                      'authenticated': authenticated,
                                      'form': form,
                                      'borrowed_books': borrowed_books
                                  }))
コード例 #47
0
ファイル: views.py プロジェクト: JerichoKain/mustache2013
def profile(req):

	g = get_object_or_404(Gentleman, pk=req.user.gentleman.id)

	if req.method == 'POST':
		pf = ProfileForm(req.POST, req.FILES, instance=g)

		if pf.is_valid():
			ng = pf.save()

			if 'before_pic' in req.FILES:
				g.before_pic.file = req.FILES['before_pic']
			if 'after_pic' in req.FILES:
				g.after_pic.file = req.FILES['after_pic']

			ng.user_id = g.user_id
			ng.id = g.id
			ng.save()

			pf = ProfileForm(instance=ng)

			messages.info(req, 'Gentleman updated successfully.')

	else:
		pf = ProfileForm(instance=g)

	return render(req, 'voting/profile.html', {'pf': pf })
コード例 #48
0
 def obj_create(self, bundle, request=None, **kwargs):
     try:
         uForm = UserForm(data=bundle.data)
         pForm = ProfileForm(data=bundle.data)
         if uForm.is_valid() and pForm.is_valid():
             user = uForm.save()
             user.save()
             profile = pForm.save(commit=False)
             profile.user = user
             if not profile.invites:
                 profile.invites = 0
             profile.save()
             user = authenticate(username=bundle.data.get('username'),
                                 password=bundle.data.get('password'))
             login(request, user)
             bundle.obj = profile
         else:
             return self.create_response(request, {
                 'error':
                 dict(uForm.errors.items() + pForm.errors.items())
             })
     except IntegrityError:
         pass
     # do any other Profile instantiation stuff here
     return bundle
コード例 #49
0
def profile(request, nickname, template_name = "account/profile.html"):
    profile = get_object_or_404(Profile, nick = nickname)
    if request.user.is_authenticated():
        if request.user == profile.user:
            is_me = True
        else:
            is_me = False
    else:
        is_me = False


    if is_me:
        if request.method == "POST":
            if request.POST["action"] == "update":
                profile_form = ProfileForm(request.POST, instance=profile)
                profile = profile_form.save(commit=False)
                profile.save()
        profile_form = ProfileForm(instance=profile)
    else:
        profile_form = None

    return render_to_response(template_name, {
        "profile": profile,
        "profile_form": profile_form,
        "is_me": is_me,
        "other_user": profile.user,
    }, context_instance=RequestContext(request))
コード例 #50
0
ファイル: views.py プロジェクト: baugarten/Heartbeat
def register(request):
  if request.method == "POST":
    data = json.loads(request.raw_post_data)
    uForm = UserForm(data = data)
    pForm = ProfileForm(data = data)
    aForm = None 
    if data['artist']:
      aForm = ArtistForm(data = data)
    if uForm.is_valid() and pForm.is_valid() and (aForm == None or aForm.is_valid()):
      user = uForm.save()
      user.save()
      profile = pForm.save(commit = False)
      profile.user = user
      if not profile.invites:
        profile.invites = 0
      profile.save()
      if aForm:
        artist = aForm.save(commit = False)
        artist.profile = profile
        artist.save()
      user = authenticate(username = data['username'],
                          password = data['password1'])
      login(request, user)
      resp = HttpResponse(json.dumps({'success': 'true'}), mimetype="application/json")
      resp.status_code = 201
      return resp 
    else:
      error = dict(uForm.errors.items()
                  + pForm.errors.items())
  else:
    error = "The request must be a POST"
  resp = HttpResponse(json.dumps({'error': error}), mimetype="applcation/json")
  resp.status_code = 400
  return resp
コード例 #51
0
ファイル: views.py プロジェクト: MAPC/myschoolcommute
def profile_edit(request, username=None):
    if username is None:
        p = request.user.get_profile()
        user = request.user
    else:
        user = User.objects.get(username=username)
        p = user.get_profile()

    if request.method == 'POST':
        user_form = UserForm(request.POST, instance=user)
        profile_form = ProfileForm(request.POST, instance=p, editor=request.user)
        if user_form.is_valid() and profile_form.is_valid():
            user = user_form.save()
            p = profile_form.save()

            if 'is_active' in request.POST and request.user.has_perm('auth.change_user'):
                user.is_active = True
                user.save()
                send_mail(
                    "Your myschoolcommute.com account has been approved",
                    "You may login at http://%s/%s" % (request.META['HTTP_HOST'], reverse('login'),),
                    settings.SERVER_EMAIL,
                    [user.email]
                )

            return HttpResponseRedirect(reverse('user_detail', args=[user.username]))
    else:
        user_form = UserForm(instance=user)
        profile_form = ProfileForm(instance=p, editor=request.user)

    profile_form.helper.add_input(Submit('submit', 'Save account'))

    return render_to_response("accounts/edit.html", {
        'user_form' : user_form, 'profile_form': profile_form, 'user': user
    }, context_instance=RequestContext(request) )
コード例 #52
0
def RegistroUsuario(request):
    if request.method == 'POST':
        user_form = RegistroForm(request.POST)
        profile_form = ProfileForm(request.POST)
        if user_form.is_valid() and profile_form.is_valid():
            usuario = user_form.save()
            profile_form = ProfileForm(request.POST, instance=usuario.profile)
            profile = profile_form.save()
            usuario.email = profile.email
            usuario.save()
            html_content = '<p>El usuario <strong>' + usuario.username + ' - ' + profile.empresa + '</strong> se ha registrado en INDICAGRO.</p>'
            email = EmailMultiAlternatives('Usuario ' + usuario.username +
                                           ' creado exitosamente',
                                           'Este es el mensaje del email',
                                           to=['*****@*****.**'],
                                           bcc=['*****@*****.**'])
            email.attach_alternative(html_content, "text/html")
            email.send()
            print("se mando el email")
            messages.success(
                request,
                'Ya te encuentras habilitado para aplicarte IndicAgro. '
                'Gracias por formar parte de un #AgroComprometido!')
            return redirect('usuarios:usuarios_home')
    else:
        user_form = RegistroForm()
        profile_form = ProfileForm()
    return render(request, 'usuarios/registrar.html', {
        'user_form': user_form,
        'profile_form': profile_form
    })
コード例 #53
0
ファイル: site.py プロジェクト: ekaputra07/bokerface
    def post(self):

        if self.request.get('tab') == 'profile' or not self.request.get('tab'):
            title = 'Profile Settings'
            tab = 'profile'

            user = User.get_by_key_name(self.current_user['id'])
            form = ProfileForm(self.session, self.request.POST, instance=user)

            if form.is_valid():
                form.save()
                self.redirect(self.uri_for('settings')+'?tab=profile&success=1')

            return self.render_response(self.template, locals())

        elif self.request.get('tab') == 'sharing':
            pass
コード例 #54
0
def RegistroUsuario(request):
    if request.method == 'POST':
        user_form = RegistroForm(request.POST)
        profile_form = ProfileForm(request.POST)
        if user_form.is_valid() and profile_form.is_valid():
            usuario = user_form.save()
            profile_form = ProfileForm(request.POST, instance=usuario.profile)
            profile_form.save()
            messages.success(request, 'Usuario creado exitosamente!')
            return redirect('usuarios:usuarios_home')
    else:
        user_form = RegistroForm()
        profile_form = ProfileForm()
    return render(request, 'usuarios/registrar.html', {
        'user_form': user_form,
        'profile_form': profile_form
    })
コード例 #55
0
def update_profile(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():
            user_form.save()
            profile_form.save()
            #messages.success(request, _('Your profile was successfully updated!'))
            return redirect('usuarios:usuarios_home')
        #else:
        #messages.error(request, _('Please correct the error below.'))
    else:
        user_form = UserForm(instance=request.user)
        profile_form = ProfileForm(instance=request.user.profile)
    return render(request, 'usuarios/actualizar.html', {
        'user_form': user_form,
        'profile_form': profile_form
    })
コード例 #56
0
ファイル: views.py プロジェクト: MAPC/myschoolcommute
def register(request):
    if request.method == 'POST':
        user_form = RegistrationForm(request.POST)
        profile_form = ProfileForm(request.POST)

        if user_form.is_valid() and profile_form.is_valid():
            new_user = user_form.save()
            p = Profile.objects.get(user=new_user)
            profile_form = ProfileForm(request.POST, instance=p)
            profile_form.save()

            users_page = 'http://' + request.META['HTTP_HOST'] + reverse('user_list')
            approve_page = 'http://' + request.META['HTTP_HOST'] + reverse('user_edit', args=[new_user.username])
            message = "New user registration!\n\n%s\n%s, %s\nActivate user: %s\nView all users: %s" % (
                new_user.username, new_user.first_name, new_user.last_name, approve_page, users_page,
            )

            try:
                try:
                    g = Group.objects.get(name="Account Admins")
                    emails = [u.email for u in g.user_set.all()]
                except:
                    # email to single email for now
                    # https://github.com/MAPC/myschoolcommute/issues/49
                    emails = ['*****@*****.**']
                send_mail(
                    'myschoolcommute.com new user '+new_user.username,
                    message,
                    settings.SERVER_EMAIL,
                    emails
                )
            except:
                #Problem finding group or emailing
                mail_admins('myschoolcommute.com new user '+new_user.username, message)

            return HttpResponseRedirect("/accounts/register/success/")
    else:
        profile_form = ProfileForm()
        user_form = RegistrationForm()

    profile_form.helper.add_input(Submit('submit', 'Create the account'))
    return render_to_response("accounts/register.html", {
        'user_form' : user_form, 'profile_form': profile_form
    }, context_instance=RequestContext(request))
コード例 #57
0
def update_profile(request):
    if request.method == 'POST':
        print('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():
            user_form.save()
            profile_form.save()
            messages.success(request, ('Ваши данные успешно обновлены'))
            print('form too is valid')
            return redirect('update_profile')
        else:
            messages.error(request,
                           ('Error:Пожалуйста проверьте введенные данные!'))
    else:
        user_form = UserForm(instance=request.user)
        profile_form = ProfileForm(instance=request.user.profile)
    return render(request, 'accounts/profile.html', {
        'user_form': user_form,
        'profile_form': profile_form
    })
コード例 #58
0
ファイル: views.py プロジェクト: satra/brainspell
def profile(request):
    profile = Profile.objects.get_or_create(user=request.user,
                                            email=request.user.email)
    if profile[1]:
        profile[0].save()
    profile = profile[0]

    if request.method == 'POST':
        form = ProfileForm(request.POST, instance=profile)
        if form.is_valid():
            form.save()
            return redirect('profile')

    else:
        form = ProfileForm(instance=profile)

    context = {
        'form': form,
        'profile': profile,
    }
    return render_to_response('profile.html', context, RequestContext(request))